WeChat Mini Program Server API

1.8.18 · active · verified Sun Mar 01

Server-side Python SDK for WeChat (Weixin) Mini Programs. Handles the backend half of Mini Program interactions: login verification (jscode2session), access token management, template messages, and encrypted data decryption. The dominant community SDK is wechatpy — no official Tencent Python SDK exists. Mini Program frontend runs in WeChat's JavaScript runtime (WXML/WXSS); Python handles server-side API calls only.

Warnings

Install

Imports

Quickstart

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

view raw JSON →