Of course! The wxBizMsgCrypt library is essential for any Python application that needs to communicate securely with WeChat's official accounts or mini-programs. It's used for two main purposes:

- Message Encryption (Server -> WeChat): When your server sends messages (like responses to user text), you must encrypt them using a signature and token provided by the WeChat backend.
- Message Decryption (WeChat -> Server): When WeChat sends messages to your server (like user input or events), you must decrypt and verify them to ensure they are authentic.
This process is part of WeChat's "Server-as-a-Service" (SaaS) integration model, ensuring that only the official WeChat server can send messages to your endpoint.
Prerequisites
Before you start, you need to get three pieces of information from your WeChat Official Account backend:
- Token (令牌): A string you define in the WeChat backend. It must match the one in your Python code.
- EncodingAESKey (消息加解密密钥): A Base64-encoded key provided by WeChat. You'll need to decode it to get the actual AES key.
- AppID (应用ID): Your unique application identifier.
Where to find them: Log in to the WeChat Official Account Platform, go to "开发" -> "基本配置" -> "服务器配置". You will see these fields there.
Installation
The most common and recommended Python library for this is wechatpy. It's a comprehensive library that handles the entire WeChat ecosystem, including message encryption/decryption.

pip install wechatpy
Core Concepts
The wechatpy library provides a WXBizMsgCrypt class to handle all the cryptographic operations.
WXBizMsgCrypt(token, encoding_aes_key, app_id): The main class you'll instantiate.EncryptMsg(xml_to_encrypt): Encrypts a plain XML message.DecryptMsg(encrypted_msg, signature, timestamp, nonce): Decrypts a message and verifies its authenticity. It returns the decrypted plain XML.
Step-by-Step Implementation
Let's walk through a complete example of a web server that handles both incoming and outgoing messages.
Step 4.1: Setup and Configuration
First, set up your project and get your credentials ready.
# config.py # Paste your actual credentials here WECHAT_TOKEN = "your_token" WECHAT_ENCODING_AES_KEY = "your_encoding_aes_key" # e.g., "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH" WECHAT_APP_ID = "your_app_id"
Step 4.2: The Web Server (using Flask)
A simple Flask application is perfect for demonstrating the logic. We'll create two endpoints: one for the WeChat server to verify the URL (GET request) and one for handling incoming messages (POST request).

pip install flask
Step 4.3: Complete Code Example
Here is the full code for app.py.
import xml.etree.ElementTree as ET
from flask import Flask, request, make_response
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy import parse_message, create_reply
from wechatpy.crypto import WXBizMsgCrypt
from wechatpy.messages import TextMessage
# Import your configuration
from config import WECHAT_TOKEN, WECHAT_ENCODING_AES_KEY, WECHAT_APP_ID
app = Flask(__name__)
# --- Global WXBizMsgCrypt instance ---
# It's good practice to instantiate this once when your app starts.
# The library handles the key decoding internally.
wxcpt = WXBizMsgCrypt(WECHAT_TOKEN, WECHAT_ENCODING_AES_KEY, WECHAT_APP_ID)
@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
# 1. Handle WeChat's URL verification (GET request)
if request.method == 'GET':
signature = request.args.get('signature', '')
timestamp = request.args.get('timestamp', '')
nonce = request.args.get('nonce', '')
echostr = request.args.get('echostr', '')
# WeChat uses this to verify that your server is valid
try:
check_signature(WECHAT_TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
# Signature is invalid, return an error
app.logger.error("Invalid signature during URL verification.")
return "Invalid signature", 403
# If signature is valid, return the echostr to complete the verification
return echostr
# 2. Handle incoming messages (POST request)
elif request.method == 'POST':
# Get the raw XML data from WeChat
body = request.data
app.logger.info(f"Received raw XML: {body.decode('utf-8')}")
# Parse the incoming XML to get necessary fields for decryption
# Note: The XML is encrypted, so we can't parse it with ET directly yet.
# We need to extract the fields manually.
root = ET.fromstring(body)
encrypt = root.find('Encrypt').text
msg_signature = root.get('MsgSignature')
timestamp = root.get('Timestamp')
nonce = root.get('Nonce')
# Decrypt the message
try:
# The decrypted message is in XML format
decrypted_xml = wxcpt.decrypt_message(
body,
msg_signature,
timestamp,
nonce
)
app.logger.info(f"Decrypted XML: {decrypted_xml}")
except Exception as e:
app.logger.error(f"Decryption failed: {e}")
return "Decryption failed", 500
# Now, parse the decrypted XML
msg = parse_message(decrypted_xml)
# --- Your Business Logic ---
# Here you process the message and create a reply
if isinstance(msg, TextMessage):
# User sent a text message
user_content = msg.content
app.logger.info(f"Received text from {msg.source}: {user_content}")
# Create a reply
reply_text = f"你发送了: {user_content}"
reply = create_reply(reply_text, msg=message)
else:
# Handle other message types (images, events, etc.)
reply = create_reply("我只支持文字消息哦。", msg=message)
# --- Encrypt the Reply for Sending Back to WeChat ---
# The reply we created is a plain text message object.
# We need to convert it to XML and then encrypt it.
reply_xml = reply.render()
app.logger.info(f"Reply XML (before encryption): {reply_xml}")
try:
encrypted_reply_xml = wxcpt.encrypt_msg(reply_xml)
app.logger.info(f"Encrypted Reply XML: {encrypted_reply_xml}")
except Exception as e:
app.logger.error(f"Encryption failed: {e}")
return "Encryption failed", 500
# Return the encrypted XML in the correct format
# WeChat expects an XML with <Encrypt> and <MsgSignature> tags
response = make_response(encrypted_reply_xml)
response.content_type = 'application/xml'
return response
if __name__ == '__main__':
# In production, use a proper WSGI server like Gunicorn or uWSGI
app.run(host='0.0.0.0', port=5000, debug=True)
How to Run and Test
- Save the files:
config.pyandapp.py. - Configure: Fill in your actual
Token,EncodingAESKey, andAppIDinconfig.py. - Run the server:
python app.py
Your server will be running on
http://localhost:5000. - Configure WeChat:
- Go to your WeChat Official Account's "Server Configuration".
- For the URL, enter
http://your-server-ip:5000/wechat. (If running locally,http://127.0.0.1:5000/wechatmight work for some tunneling tools, but for public testing, you need a publicly accessible URL). - For Token, enter the same
your_tokenfrom yourconfig.py. - Select "Encryption Mode" as "Compatible Mode" or "Safe Mode". "Safe Mode" is recommended as it encrypts all messages.
- Click "Submit". WeChat will send a GET request to your server to verify the URL. Your
GEThandler in the code will respond withechostr, and the configuration will succeed.
- Test:
- Follow your official account on WeChat.
- Send it a text message.
- Your server's logs will show the incoming encrypted XML, the decrypted content, and the outgoing encrypted reply.
- You will receive the reply message in WeChat.
Common Pitfalls and Troubleshooting
InvalidSignatureExceptionduring URL verification:- Cause: The
Tokenin your Python code does not match theTokenconfigured in the We
- Cause: The
