echostr,原樣返回驗證 URL 有效性。
# -*- coding: utf-8 -*-
from bottle import route, run, request, response, default_app
import time
import libxml2dom # 或 lxml, xml.etree.ElementTree
@route('/')
def verify():
"""GET 請求:驗證服務器"""
return request.GET.get('echostr', '')
@route('/', method='POST')
def handle_message():
"""POST 請求:處理用戶消息"""
# Bottle 將原始 XML 放在 request.body 或 request.POST 的鍵中
# 這裡假設直接獲取原始 XML 字串
xml_data = request.body.read().decode('utf-8')
# 或遍歷 request.POST (舊版行為)
# for key, value in request.POST.allitems(): xml_data = key
doc = libxml2dom.parseString(xml_data)
# 解析必要欄位
to_user = doc.xpath('//ToUserName')[0].textContent
from_user = doc.xpath('//FromUserName')[0].textContent
msg_type = doc.xpath('//MsgType')[0].textContent
content = doc.xpath('//Content')[0].textContent if doc.xpath('//Content') else ''
msg_id = doc.xpath('//MsgId')[0].textContent if doc.xpath('//MsgId') else ''
# 業務邏輯:簡單回聲
reply_content = f"收到: {content}"
# 構造回覆 XML
reply_xml = f"""
{int(time.time())}
0
"""
response.content_type = 'application/xml'
return reply_xml
if __name__ == '__main__':
import sys
# 開發模式
run(host='0.0.0.0', port=int(sys.argv[1]) if len(sys.argv)>1 else 8888, reloader=True, debug=True)
else:
# 生產部署 (uWSGI/Gunicorn)
import os
os.chdir(os.path.dirname(__file__))
application = default_app()
libxml2dom:舊專案常用,需安裝 libxml2-python。lxml.etree:效能最好,pip install lxml。xml.etree.ElementTree:標準庫,無依賴。
# lxml 版本
from lxml import etree
root = etree.fromstring(xml_data)
to_user = root.find('ToUserName').text
if msg_type == 'text':
reply_content = process_text(content)
elif msg_type == 'image':
media_id = doc.xpath('//MediaId')[0].textContent
reply_content = process_image(media_id)
elif msg_type == 'voice':
# 語音識別結果在 Recognition 欄位
pass
elif msg_type == 'event':
event = doc.xpath('//Event')[0].textContent
if event == 'subscribe':
reply_content = "歡迎關注!"
elif event == 'CLICK':
# 菜單點擊事件
pass
生產環境**必須啟用**加密模式 (AES + SHA1)。需實現:
Encrypt 欄位。msg_signature。建議使用現成庫:wechatpy、werobot。
import requests
import json
def send_customer_message(access_token, openid, content):
url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}"
payload = {
"touser": openid,
"msgtype": "text",
"text": {"content": content}
}
resp = requests.post(url, json=payload)
return resp.json()