Of course! Here is a comprehensive guide to using Python with the WeChat SDK, covering the most common scenarios like Official Accounts (公众号), Mini Programs (小程序), and WeChat Pay.

Overview
WeChat doesn't provide a single, all-in-one "Python SDK" like a company might for its own API. Instead, it provides well-documented REST APIs and standardized data formats (like XML and JSON). The Python "SDK" is typically a collection of third-party libraries that help you interact with these APIs more easily.
The choice of library depends heavily on what you're building:
- WeChat Official Account (公众号): For public accounts, used for customer service, content delivery, etc.
- WeChat Mini Program (小程序): For building small, lightweight apps inside WeChat.
- WeChat Pay (微信支付): For integrating payment functionality.
WeChat Official Account (公众号)
This is the most common use case for a Python WeChat SDK. You'll need a library to handle message parsing, signature verification, and API calls.
Recommended Library: wechatpy
wechatpy is a mature, feature-rich, and widely used library for handling WeChat Official Account APIs in Python.

Installation:
pip install wechatpy
Key Features of wechatpy:
- Message Handling: Easily parse incoming messages (text, image, voice, etc.) and create responses.
- Signature Verification: Automatically verifies requests from WeChat servers to ensure they are legitimate.
- API Client: Provides a client to make calls to the Official Account API (e.g., to get user info, send messages).
- OAuth2: Handles WeChat's OAuth2 login flow.
- JS-SDK: Helps with using WeChat's JS-SDK for features like sharing, location, etc., on your web pages.
Example: A Basic Echo Server for a Public Account
This is the "Hello, World!" of WeChat bots. When a user sends a text message to your Official Account, your server will reply with the same message.
Step 1: Configure Your Official Account
- Go to your WeChat Official Account backend (微信公众平台).
- Navigate to
开发->基本配置(Development -> Basic Configuration). - Click
修改配置(Modify Configuration). - Fill in:
- URL: The public URL of your Python web server (e.g.,
https://yourdomain.com/wechat). Must behttporhttpsand accessible from the internet. - Token: A secret string you create. This will be used in your Python code.
- EncodingAESKey: Generate a random one. This is for encrypting messages.
- Message Type: Select
安全模式(Security Mode) or开发者模式(Developer Mode). For this example,开发者模式is fine.
- URL: The public URL of your Python web server (e.g.,
Step 2: Python Code using Flask and wechatpy

Let's create a simple web server with Flask.
# app.py
from flask import Flask, request, make_response
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
# 1. Replace with your own Token
WECHAT_TOKEN = 'your_token_here'
WECHAT_APP_ID = 'your_app_id'
WECHAT_APP_SECRET = 'your_app_secret'
app = Flask(__name__)
@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
# For GET requests (WeChat's server validation)
if request.method == 'GET':
signature = request.args.get('signature', '')
timestamp = request.args.get('timestamp', '')
nonce = request.args.get('nonce', '')
echostr = request.args.get('echostr', '')
try:
# 2. Verify the signature
check_signature(WECHAT_TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
abort(403)
# 3. Return echostr to confirm
return echostr
# For POST requests (handling actual messages from users)
if request.method == 'POST':
# WeChat sends XML data, so we need to parse it
# wechatpy helps by parsing the XML into a Message object
try:
# The request data is in bytes, decode it to string
xml_data = request.data.decode('utf-8')
msg = parse_message(xml_data)
except Exception as e:
# Handle parsing errors
print(f"Error parsing message: {e}")
return 'error', 400
# Handle different message types
if msg.type == 'text':
# Create a reply message
reply_content = f"You said: {msg.content}"
reply = create_reply(reply_content, msg)
elif msg.type == 'image':
reply = create_reply("Nice picture!", msg)
else:
reply = create_reply("Unsupported message type.", msg)
# The reply object can be converted to XML
# We need to return it as a response with the correct content type
response = make_response(reply.render())
response.content_type = 'application/xml'
return response
if __name__ == '__main__':
# Use a production-grade server like Gunicorn or uWSGI in real scenarios
# For local testing, this is fine.
app.run(host='0.0.0.0', port=5000, debug=True)
Step 3: Run and Test
- Run the Flask app:
python app.py. - Use a tool like ngrok to expose your local server to the internet:
ngrok http 5000. - In your WeChat Official Account configuration, set the
URLtohttps://<ngrok-id>.ngrok.io/wechat. - Click "Submit". If the
echostrvalidation works, it's configured correctly. - Now, send a message to your Official Account's WeChat ID from your personal WeChat. You should get an echo reply!
WeChat Mini Program (小程序)
For Mini Programs, the interaction is different. Your Mini Program's frontend (WXML/JS) makes API calls to your backend server, which then in turn calls the WeChat Mini Program API.
The Python SDK's role here is to be your backend server that communicates with WeChat's API.
Recommended Library: requests
The standard requests library is all you need. You'll be making HTTP requests to WeChat's API endpoints.
Common API Tasks:
- Code2Session: This is the most crucial one. A Mini Program sends a temporary
code(obtained after user login) to your server. Your server exchanges thiscodewith WeChat for a permanentsession_keyandopenid.
Example: Code2Session Flow
import requests
import json
# Your Mini Program's AppID and AppSecret
APP_ID = 'your_mini_program_app_id'
APP_SECRET = 'your_mini_program_app_secret'
def get_openid(js_code):
"""
Exchanges the js_code from Mini Program login for an openid and session_key.
"""
url = f"https://api.weixin.qq.com/sns/jscode2session"
params = {
'appid': APP_ID,
'secret': APP_SECRET,
'js_code': js_code,
'grant_type': 'authorization_code'
}
try:
response = requests.get(url, params=params)
data = response.json()
if 'errcode' in data:
# WeChat returned an error
print(f"WeChat API Error: {data['errmsg']}")
return None
# Success! You now have the session_key and openid
# Store the session_key securely and associate it with the user in your database
openid = data['openid']
session_key = data['session_key']
print(f"Successfully retrieved openid: {openid}")
return openid, session_key
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
# Example usage:
# This 'js_code' would be sent from your Mini Program's frontend after login.
# dummy_js_code = "071Jxx000ikXa012A3d00050yJ0J1XKZ"
# get_openid(dummy_js_code)
WeChat Pay (微信支付)
Integrating WeChat Pay is complex and involves two main parts:
- Creating an Order: Your server tells WeChat's server to create a payment order.
- Handling a Callback: After the user pays, WeChat's server sends a notification (a callback) to your server to confirm the payment.
Recommended Library: wechatpay-v3
This is the official and recommended library for WeChat Pay v3. It handles signature generation and verification automatically, which is the most challenging part.
Installation:
pip install wechatpay-v3
Example: Creating a Native (QR Code) Payment Order
This is a simplified example. Real-world implementation requires more details like merchant certificates, proper key management, and handling the asynchronous callback.
import os
import json
from datetime import datetime
from wechatpay.v3 import WeChatPay
from wechatpay.v3.utils import get_random_string
# --- Configuration ---
# Get these from your WeChat Pay Merchant Platform
MERCHANT_ID = 'your_mch_id' # 商户号
API_KEY = 'your_api_key' # API密钥
API_CERT_PATH = 'path/to/your/apiclient_cert.pem' # 证书路径
API_KEY_PATH = 'path/to/your/apiclient_key.pem' # 私钥路径
# Initialize the WeChatPay client
# This handles all the signing and verification for you
client = WeChatPay(
merchant_id=MERCHANT_ID,
api_key=API_KEY,
api_cert_path=API_CERT_PATH,
api_key_path=API_KEY_PATH,
)
def create_wechatpay_order(total_fee, description, notify_url):
"""
Creates a WeChat Pay order and returns a QR code URL.
total_fee: Amount in Fen (1 CNY = 100 Fen). e.g., 100 for 1.00 CNY.
description: Order description.
notify_url: Your server's endpoint to receive payment notifications.
"""
# 1. Prepare the order data
order_data = {
"appid": client.appid, # Your Mini Program or Official Account AppID
"mchid": MERCHANT_ID,
"description": description,
"out_trade_no": get_random_string(32), # Your unique order ID
"notify_url": notify_url,
"amount": {
"total": total_fee, # Must be an integer
"currency": "CNY"
},
"scene_info": {
"payer_client_ip": "127.0.0.1" # Get from the actual request
}
}
# 2. Make the API call to create the order
# The client automatically adds the 'Wechatpay-Timestamp' and 'Wechatpay-Signature' headers
response = client.post(
'/v3/pay/transactions/native',
data=json.dumps(order_data)
)
# 3. Parse the response
response_data = response.json()
if 'code_url' in response_data:
# Success! The 'code_url' is used to generate the QR code
qr_code_url = response_data['code_url']
print(f"Order created successfully. QR Code URL: {qr_code_url}")
return qr_code_url
else:
print(f"Error creating order: {response_data}")
return None
# Example usage:
# create_wechatpay_order(
# total_fee=100,
# description="Test Product from Python SDK",
# notify_url="https://your-domain.com/api/wechatpay/notify"
# )
Summary and Recommendations
| Use Case | Recommended Python Library | Key Responsibilities |
|---|---|---|
| WeChat Official Account | wechatpy |
Message parsing/replying, signature verification, API calls for user management, sending messages. |
| WeChat Mini Program | requests |
Backend server logic. Handles Code2Session, processes user data, and calls other WeChat APIs on behalf of the Mini Program. |
| WeChat Pay | wechatpay-v3 |
Creating payment orders, generating QR codes, and verifying signatures on payment callbacks. This is critical for security. |
Final Advice:
- Read the Official WeChat Docs: Always refer to the official WeChat documentation for the latest API versions and parameters. The libraries are helpers, but the source of truth is the docs.
- Use HTTPS: All interactions with WeChat servers must be over HTTPS.
- Security First: Especially with WeChat Pay, never skip signature verification on the callback. It's how you know the payment notification is genuinely from WeChat.
- Local Development: Use tools like ngrok to expose your local development server to the internet for testing with WeChat's servers.
