Install & Compatibility
Where this runs
tested against v1.8.18 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 0.526s · 40.8MB
glibcpy 3.10–3.910 runs
installs and imports cleanly · install 3.6s · import 0.462s · 41MB
39MB installed
● package 39MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
WeChatClient
✓ from wechatpy import WeChatClient
✗ from wechatpy.miniprogram import WeChatMiniProgram
Use WeChatMiniProgram (not WeChatClient) for Mini Programs. Cache access_token in Redis across server instances — it has a 2hr TTL and a 2000 calls/day refresh limit. Never send session_key to the frontend.
from wechatpy.miniprogram import WeChatMiniProgram
import requests
APPID = 'your_appid'
SECRET = 'your_appsecret'
# Initialize client
client = WeChatMiniProgram(APPID, SECRET)
# Step 1: Exchange wx.login() code for openid + session_key
# Frontend calls wx.login() and sends the code to your server
def login(js_code):
result = client.code_to_session(js_code)
# result = {'openid': '...', 'session_key': '...', 'unionid': '...' (if linked)}
openid = result['openid']
session_key = result['session_key']
# NEVER send session_key to frontend — generate your own custom token
return openid, session_key
# Step 2: Get phone number (NEW method, base library >= 2.21.2)
# Frontend button fires bindgetphonenumber event, returns e.detail.code
# Send that code to your server:
def get_phone_number(phone_code):
# phone_code is different from wx.login() code — do NOT mix them
resp = requests.post(
'https://api.weixin.qq.com/wxa/business/getuserphonenumber',
params={'access_token': client.access_token},
json={'code': phone_code}
)
data = resp.json()
return data['phone_info']['phoneNumber'] # e.g. '+8613800138000'
# Step 3: Global access_token (cache this — 2hr TTL, shared across all users)
print(client.access_token) # auto-fetched and cached by wechatpy
Debug
Known issues
breakingPhone number retrieval API changed in base library 2.21.2. Old pattern (encryptedData + iv AES decrypt using session_key) still works but is deprecated. New pattern: frontend button callback returns a `code`, server exchanges it via POST /wxa/business/getuserphonenumber. The two codes (wx.login code vs phone code) are NOT interchangeable.fixUse the code-exchange pattern. Never mix wx.login() code with getPhoneNumber code. Old AES decrypt pattern is in 90% of tutorials but deprecated.
affects: all
breakinggetPhoneNumber and getRealtimePhoneNumber components are paid since August 28, 2023. Standard price: ¥0.03/call (quick verification) and ¥0.04/call (real-time verification). Each Mini Program account gets 1000 free calls for development. Production usage requires prepaid balance on WeChat Open Platform.fixPre-purchase call quota at mp.weixin.qq.com → Payment Management before going live.
affects: all
breaking`unionid` is NOT always returned by jscode2session. It only appears if the Mini Program is bound to a WeChat Open Platform account AND the user has authorized it. Many tutorials assume unionid is always present, causing KeyError in production.fixAlways use .get('unionid') not ['unionid']. Bind your Mini Program to an Open Platform account if cross-app user identity is needed. affects: all
breakingaccess_token is a global credential with a 2-hour TTL and a 2000 calls/day refresh limit. Calling getAccessToken on every request will exhaust the daily quota and lock out all users. wechatpy caches it in-process but does NOT share across multiple server instances.fixStore access_token in Redis or a shared cache and check expiry before refreshing. Use wechatpy's session storage: WeChatMiniProgram(appid, secret, session=RedisStorage(redis_client)).
affects: all
gotchasession_key must NEVER be sent to the frontend or logged. It is used server-side to decrypt sensitive user data. If session_key leaks, attackers can decrypt all encrypted user data. WeChat will invalidate session_key on wx.login() re-call.fixGenerate your own opaque session token (e.g. UUID) and map it to openid + session_key server-side.
affects: all
gotchaPhone number API requires Mini Program registered as non-individual entity with WeChat verification. Individual developer accounts (个人开发者) cannot access getPhoneNumber even with balance. Overseas entities (non-China business registration) are also blocked.fixRequires Chinese business entity + WeChat verification. Overseas businesses must use a Chinese registered subsidiary or partner.
affects: all
gotchawechatpy v1.8.18 is the last PyPI release and the package is effectively in maintenance mode (Snyk flags it as inactive). Core APIs remain functional but new WeChat features may not be supported.fixFor newer APIs not in wechatpy, call the WeChat API directly via requests using client.access_token.
affects: wechatpy==1.8.18
gotchaWeChatClient (for Official Accounts/MP) and WeChatMiniProgram (for Mini Programs) are different classes with different API surfaces. Official Account tutorials are the majority online — importing the wrong client causes silent failures or wrong endpoint calls.fixfrom wechatpy.miniprogram import WeChatMiniProgram — not WeChatClient.
affects: all
breakingThe `wechatpy.miniprogram` module, which contains `WeChatMiniProgram`, is fundamental for Mini Program development. A `ModuleNotFoundError` for this module, despite `wechatpy` (e.g., version 1.8.18) being reported as successfully installed, indicates a problem with the Python environment where the package was installed versus where the script is executed, or a corrupted installation.fixEnsure the Python interpreter running the script has `wechatpy` installed and is properly configured to access it (e.g., using a virtual environment). Try reinstalling `wechatpy` in a clean virtual environment. Verify the contents of the installed `wechatpy` package to confirm `wechatpy/miniprogram/__init__.py` exists.
affects: wechatpy==1.8.18
breakingwechatpy-1.8.18, despite installing successfully, fails to import 'wechatpy.miniprogram' on Python 3.13 environments (e.g., python:3.13-alpine). This indicates a potential incompatibility or packaging issue with newer Python versions, as wechatpy is in maintenance mode and may not support Python 3.13.fixUse an officially supported Python version (e.g., Python 3.8-3.11) with wechatpy-1.8.18, or consider migrating to a more actively maintained WeChat SDK for Python 3.13.
affects: wechatpy==1.8.18
Upgrade
Version history
1.8.18latest on PyPI · released Nov 11, 2021
Audit
Dependencies
cryptographyoptionalAES-128-CBC decryption for encrypted user data (phone, userInfo)
requestsrequiredHTTP client for WeChat API calls
xmltodictrequiredXML parsing for WeChat message payloads