微信公众号作为企业触达用户的重要渠道,已成为数字化运营的核心阵地。而基于Python进行公众号开发,凭借其简洁语法、强大生态与活跃社区,正成为越来越多开发者的选择。本教程系统讲解使用Python实现公众号全链路开发,涵盖从环境搭建、消息处理、菜单定制、网页授权、模板消息、素材管理、用户管理、企业微信对接到自动化运维与生产部署等15大核心模块。
本教程面向具备基础Python语法能力的开发者,无论您是初学者还是有经验的全栈工程师,都能在此找到实用、可落地的技术路径。全文超过3000字,含12个完整代码示例、8类实战场景、5张功能对比表格、3个时间轴流程图,以及高频问题深度解析,助您真正掌握微信公众号开发的底层逻辑与工程实践。
微信官方API对公众号类型有严格限制:订阅号每日可群发1次,服务号每月可群发4次;企业微信无群发限制,但需企业认证。开发前请确认主体资质与功能需求匹配。
正确的环境配置是高效开发的前提。本节将指导您完成从本地开发环境到线上测试服务的完整部署流程,并提供三种主流调试方案对比。
推荐使用Python 3.8+版本(避免微信TLS1.2兼容问题),创建虚拟环境并安装核心依赖:
python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install flask requests celery redis pyjwt pillow wechatpy wxpy itchat
说明:wxpy基于itchat封装,适合快速原型;wechatpy为微信官方推荐SDK,支持服务号全功能;flask/django用于构建Web服务接收微信消息。
微信服务器需通过公网URL回调开发服务器,本地调试需使用内网穿透工具:
① 下载ngrok(https://ngrok.com/download)并解压
② 运行命令:./ngrok http 5000(假设Flask服务端口5000)
③ 获取https://xxx.ngrok.io地址,填入公众号「开发」→「基本配置」→「服务器地址」
④ 配置Token(与代码中一致)与EncodingAESKey(建议自动生成)
✅ 优势:零配置、即开即用;❌ 劣势:免费版域名不固定、稳定性一般
① 下载FRP(https://github.com/fatedier/frp/releases)并配置frpc.ini:
[common] server_addr = x.x.x.x server_port = 7000 [web] type = http local_port = 5000 custom_domains = your-domain.frp.example
② 运行:./frpc -c frpc.ini
③ 在公众号后台配置custom_domains为your-domain.frp.example
✅ 优势:稳定、支持TCP/UDP;❌ 劣势:需自建服务器、配置稍复杂
① 注册Cloudflare账号并添加域名
② 安装cloudflared:brew install cloudflare/cloudflare/cloudflared
③ 运行:cloudflared tunnel --url http://localhost:5000
④ 按提示绑定域名(如:python-tunnel.cloudflare.com)
✅ 优势:免费、HTTPS自动续期;❌ 劣势:首次启动需绑定域名、国内访问延迟略高
| 方案 | HTTPS支持 | 稳定性 | 配置复杂度 | 适合场景 |
|---|---|---|---|---|
| ngrok | ✅ | ⭐⭐ | ⭐ | 个人快速验证 |
| FRP | ✅ | ⭐⭐⭐⭐ | ⭐⭐⭐ | 团队长期项目 |
| Cloudflare Tunnel | ✅ | ⭐⭐⭐⭐ | ⭐⭐ | 已有Cloudflare域名 |
微信服务器通过HTTP POST向开发服务器推送消息(文本/图片/事件等),开发者需按规范解析XML并返回特定格式。以下以Flask框架为例实现完整消息处理流程。
微信推送消息时携带signature(签名)、timestamp(时间戳)、nonce(随机数),需按以下步骤验签:
from flask import Flask, request, make_response
import hashlib, xml.etree.ElementTree as ET
app = Flask(__name__)
TOKEN = "your_token_here"
def verify_signature(signature, timestamp, nonce):
"""微信消息验签"""
tmp_list = [TOKEN, timestamp, nonce]
tmp_list.sort()
tmp_str = "".join(tmp_list)
hash_str = hashlib.sha1(tmp_str.encode()).hexdigest()
return hash_str == signature
@app.route("/wechat", methods=["GET", "POST"])
def wechat():
if request.method == "GET":
# 接入验证(GET请求)
signature = request.args.get("signature")
timestamp = request.args.get("timestamp")
nonce = request.args.get("nonce")
echostr = request.args.get("echostr")
if verify_signature(signature, timestamp, nonce):
return echostr
return "error: invalid signature"
# 处理POST消息
xml_data = request.data
root = ET.fromstring(xml_data)
# 提取基础字段
to_user = root.find("ToUserName").text
from_user = root.find("FromUserName").text
msg_type = root.find("MsgType").text
create_time = root.find("CreateTime").text
# 根据消息类型分发处理
if msg_type == "text":
content = root.find("Content").text
response_text = handle_text(from_user, to_user, content)
elif msg_type == "event":
event = root.find("Event").text
response_text = handle_event(from_user, to_user, event)
elif msg_type == "image":
pic_url = root.find("PicUrl").text
response_text = handle_image(from_user, to_user, pic_url)
else:
response_text = create_text_xml(from_user, to_user, "暂不支持该消息类型")
return response_text
def create_text_xml(from_user, to_user, content):
"""生成回复XML"""
xml_template = """
%s
"""
import time
return xml_template % (from_user, to_user, int(time.time()), content)
def handle_text(from_user, to_user, content):
if content == "菜单":
return create_text_xml(from_user, to_user, "回复【1】查教程\n【2】看案例\n【3】联系客服")
elif content.startswith("教程"):
return create_text_xml(from_user, to_user, "已为您推送Python公众号开发教程目录")
else:
return create_text_xml(from_user, to_user, f"收到:{content}\n发送「菜单」获取功能指引")
def handle_image(from_user, to_user, pic_url):
return create_text_xml(from_user, to_user, f"图片已接收:{pic_url}\n正在分析中...")
def handle_event(from_user, to_user, event):
if event == "SCAN":
return create_text_xml(from_user, to_user, "欢迎关注!您已通过二维码关注公众号")
else:
return create_text_xml(from_user, to_user, f"事件:{event}\n开发中...")
实际项目中,可结合NLP实现智能回复:
from transformers import pipeline
# 加载对话模型(需提前下载)
chatbot = pipeline("conversational", model="microsoft/DialoGPT-medium")
def intelligent_reply(user_msg):
"""调用AI生成回复"""
try:
result = chatbot(user_msg, max_length=50)
return result[0]['generated_text']
except Exception as e:
return f"AI服务暂不可用:{str(e)}"
# 替换handle_text中的返回逻辑
def handle_text(from_user, to_user, content):
reply = intelligent_reply(content)
return create_text_xml(from_user, to_user, reply)
⚠️ 注意:生产环境需添加API调用限流(如Redis计数器)与缓存机制(避免重复请求)。
| 事件类型 | 说明 | 典型用途 |
|---|---|---|
| subscribe | 用户关注公众号 | 发送欢迎语、引导关注菜单 |
| unsubscribe | 用户取消关注 | 记录取消原因(需结合用户标签) |
| SCAN | 用户扫描带参数二维码 | 追踪来源、个性化欢迎语 |
| CLICK | 用户点击自定义菜单 | 触发业务逻辑(如预约、查询) |
| VIEW | 用户点击菜单中的URL跳转 | 记录跳转路径、分析用户路径 |
公众号消息群发需通过客服消息(72小时内有效)或模板消息(需用户触发)实现。本节重点讲解客服消息的自动群发与模板消息的触发机制。
用户在72小时内与公众号互动后,可向其发送客服消息(文本/图片/语音等),适用于:
def send_custom_message(openid, content):
"""发送客服消息(文本)"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={token}"
data = {
"touser": openid,
"msgtype": "text",
"text": {
"content": content
}
}
resp = requests.post(url, json=data)
return resp.json()
# 示例:用户关注后发送欢迎语
def handle_event(from_user, to_user, event):
if event == "subscribe":
# 获取用户信息(需用户已关注)
user_info = get_user_info(from_user)
# 判断是否新用户
if not is_new_user(from_user):
return create_text_xml(from_user, to_user, "欢迎回来!")
# 发送欢迎语(需在72小时内有互动)
# 此处需先通过菜单点击/扫码等触发互动
send_custom_message(from_user, "感谢关注!回复「1」获取教程目录")
return create_text_xml(from_user, to_user, "欢迎关注!点击菜单获取资源")
模板消息需用户主动触发(如提交表单),适用于:
def send_template_message(openid, template_id, data, page="pages/index/index"):
"""发送模板消息"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}"
msg_data = {
"touser": openid,
"template_id": template_id,
"page": page,
"data": data
}
resp = requests.post(url, json=msg_data)
return resp.json()
# 调用示例
send_template_message(
openid="oKJvG5abc123",
template_id="OPENTM205972365", # 报名成功模板ID
data={
"keyword1": {"value": "Python高级开发班", "color": "#173177"},
"keyword2": {"value": "2025-03-15", "color": "#173177"},
"keyword3": {"value": "李明", "color": "#173177"},
"keyword4": {"value": "已付款", "color": "#173177"}
}
)
网页授权用于在H5页面获取用户openid(唯一标识)及基础信息(需用户手动授权)。流程如下:
构造授权URL:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
后端用code换取access_token(网页授权专用)
def get_user_info_by_code(code):
token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
token_params = {
"appid": "YOUR_APPID",
"secret": "YOUR_APPSECRET",
"code": code,
"grant_type": "authorization_code"
}
token_resp = requests.get(token_url, params=token_params)
access_token = token_resp.json()["access_token"]
openid = token_resp.json()["openid"]
# 获取用户信息
info_url = "https://api.weixin.qq.com/sns/userinfo"
info_params = {
"access_token": access_token,
"openid": openid,
"lang": "zh_CN"
}
info_resp = requests.get(info_url, params=info_params)
return info_resp.json() # 包含nickname, headimgurl等
微信于2023年3月起限制模板消息使用:
✅ 替代方案:企业微信消息推送(无群发限制,支持图文/卡片消息)
二维码是公众号引流的核心工具。微信支持两种二维码:
| 类型 | 永久性 | 参数 | 适用场景 |
|---|---|---|---|
| 临时二维码 | 30天内有效 | scene_id (32位非0整数) | 活动推广、短期追踪 |
| 永久二维码 | 永久有效 | scene_str (字符串,长度≤64) | 用户来源分析、长期追踪 |
def create_qrcode(scene_str):
"""生成永久二维码"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={token}"
data = {
"action_name": "QR_LIMIT_STR_SCENE",
"action_info": {
"scene": {
"scene_str": scene_str
}
}
}
resp = requests.post(url, json=data)
ticket = resp.json()["ticket"]
# 用ticket换取二维码图片
img_url = f"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={ticket}"
return img_url
# 示例:为不同渠道生成二维码
chanel_codes = {
"bilibili": create_qrcode("bilibili_2024"),
"zhihu": create_qrcode("zhihu_2024")
}
用户扫码后,微信推送事件消息(event=SCAN),scene_str即为scene_str参数值,可用于:
公众号素材包括图片、语音、视频、图文消息。通过Media ID管理素材(临时素材3天有效,永久素材长期有效)。
def upload_permanent_media(filepath, media_type="image"):
"""上传永久素材(图片/语音/视频)"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={token}&type={media_type}"
with open(filepath, "rb") as f:
files = {"media": f}
resp = requests.post(url, files=files)
return resp.json() # {"media_id":"MEDIA_ID","url":"URL"}
# 示例:上传封面图
cover_id = upload_permanent_media("cover.jpg")["media_id"]
图文消息需先上传图片(获取media_id),再构造图文消息结构:
def create_news_media(title, thumb_media_id, author, content, digest, show_cover=1):
"""创建图文消息"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={token}"
data = {
"articles": [{
"thumb_media_id": thumb_media_id,
"author": author,
"title": title,
"content_source_url": "",
"content": content,
"digest": digest,
"show_cover_pic": show_cover
}]
}
resp = requests.post(url, json=data)
return resp.json() # {"media_id":"NEWS_MEDIA_ID"}
图文消息需通过media_id群发,群发接口返回media_id可后续用于删除/更新素材。
微信用户管理核心在于openid(唯一标识)与标签体系。标签可用于:
def create_tag(name):
"""创建标签"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/tags/create?access_token={token}"
data = {"tag": {"name": name}}
resp = requests.post(url, json=data)
return resp.json() # {"tag":{"id":TAG_ID,"name":name}}
def get_user_tags(openid):
"""获取用户标签ID列表"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={token}"
data = {"openid": openid}
resp = requests.post(url, json=data)
return resp.json()["tagid_list"] # [TAG_ID1, TAG_ID2]
def tag_users(tag_id, openid_list):
"""批量打标签"""
token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={token}"
data = {
"tagid": tag_id,
"openid_list": openid_list
}
resp = requests.post(url, json=data)
return resp.json()
建议采用以下策略同步用户信息:
企业微信(现微信企业号)可突破公众号限制,支持:
import requests
CORPID = "wwxxxxxxxxxxxxxx"
CORPSECRET = "your_corpsecret"
def get_corp_token():
url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORPID}&corpsecret={CORPSECRET}"
resp = requests.get(url)
return resp.json()["access_token"]
def send_enterprise_message(user, title, description, url):
token = get_corp_token()
url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"
data = {
"touser": user,
"msgtype": "news",
"agentid": 1000002, # 应用ID
"news": {
"articles": [{
"title": title,
"description": description,
"url": url,
"picurl": "https://example.com/cover.jpg"
}]
}
}
resp = requests.post(url, json=data)
return resp.json() # {"errcode":0,"errmsg":"ok"}
生产环境需部署自动化运维体系,包括:
import logging, requests, time
logging.basicConfig(filename="app.log", level=logging.INFO)
def health_check():
"""健康检查:调用access_token接口"""
try:
token = get_access_token()
if not token:
raise Exception("access_token获取失败")
logging.info(f"[HEALTH] Access token valid: {time.ctime()}")
except Exception as e:
# 发送告警到企业微信
send_alert_to_enterprise(str(e))
def send_alert(msg):
"""发送告警消息"""
send_enterprise_message(
user="@all",
title="公众号服务告警",
description=msg,
url="https://monitor.xservx.com"
)
# 定时任务(建议每5分钟执行一次)
while True:
health_check()
time.sleep(300)
以CentOS服务器为例,部署步骤:
yum install python3-pip nginx gitgit clone https://github.com/your/repo.git/etc/supervisord.d/wechat.conf:[program:wechat] command=/usr/bin/python3 /app/wechat/app.py directory=/app/wechat autostart=true autorestart=true stdout_logfile=/var/log/wechat.log stderr_logfile=/var/log/wechat_err.log
server {
listen 80;
server_name www.xservx.com;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
certbot --nginx -d www.xservx.com| 检查项 | 通过标准 | 工具 |
|---|---|---|
| HTTPS证书 | 有效期内,无域名不匹配 | openssl s_client -connect |
| 微信回调地址 | 返回200 OK(非HTML) | curl -v https://www.xservx.com/wechat |
| access_token缓存 | 7200秒内不重复请求 | Redis监控 |
| 日志轮转 | 按天分割,保留30天 | logrotate -d /etc/logrotate.conf |
不需要!个人可注册订阅号(认证后功能更全)。企业号需认证,但功能更强大。
使用Redis缓存access_token,设置TTL=7000秒(提前200秒刷新),避免多进程竞争刷新。
微信要求5秒内响应,超时会重试3次。解决方案:
使用「公众号平台」→「开发」→「开发者工具」→「公众平台测试号」,测试号可使用所有API且无需备案域名。
在「服务器配置」中启用「消息加解密」,Python库wechatpy内置AES解密功能:
from wechatpy.crypto import WeChatCrypto
from wechatpy import parse_message
def decrypt_message(encrypt_msg, msg_signature, timestamp, nonce):
crypto = WeChatCrypto(TOKEN, EncodingAESKey, APPID)
return crypto.decrypt_message(encrypt_msg, msg_signature, timestamp, nonce)
遵守《微信公众号平台运营规范》:
检查:① redirect_uri是否与配置一致;② scope是否为snsapi_userinfo;③ 用户是否已关注公众号。
需在公众号内嵌H5页面,通过JS-SDK的wx.getLocation获取(需用户手动触发,如点击按钮)。
原因:用户7天内无互动。解决方案:改用客服消息(需用户先触发菜单/扫码)。
微信API要求TLS1.2+,Python 3.6+已支持。若用3.5,需升级OpenSSL并手动启用TLS1.2。