0%

Flask微信公众号开发

微信服务器认证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@app.route('/wx_flask',methods=['GET','POST'])
def wechat():
# 第一次接入服务器的验证
if request.method == 'GET':
#这里改写你在微信公众平台里输入的token
token = 'ctgu'
#获取输入参数
data = request.args
signature = data.get('signature','')
timestamp = data.get('timestamp','')
nonce = data.get('nonce','')
echostr = data.get('echostr','')
#字典排序
list = [token, timestamp, nonce]
list.sort()

s = list[0] + list[1] + list[2]
#sha1加密算法
hascode = hashlib.sha1(s.encode('utf-8')).hexdigest()
#如果是来自微信的请求,则回复echostr
if hascode == signature:
return echostr
else:
return "非微信官方请求"
#回复用户消息
elif request.method == "POST":
# 表示微信服务器转发消息过来
xml_str = request.data
if not xml_str:
return "不支持此此类型消息处理!"
# 对xml字符串进行解析
xml_dict = xmltodict.parse(xml_str)
xml_dict = xml_dict.get("xml")
return resp_by_msg_type(xml_dict)

自动回复用户消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def resp_by_msg_type(xml_dict):

# 提取消息类型

​ msg_type = xml_dict.get("MsgType")
​ if msg_type == "text":

# 表示发送的是文本消息

# 构造返回值,经由微信服务器回复给用户的消息内容

​ resp_dict = {
​ "xml": {
​ "ToUserName": xml_dict.get("FromUserName"),
​ "FromUserName": xml_dict.get("ToUserName"),
​ "CreateTime": int(time.time()),
​ "MsgType": "text",
​ "Content": "you say:" + xml_dict.get("Content")
​ }
​ }

# 将字典转换为xml字符串

​ resp_xml_str = xmltodict.unparse(resp_dict)

# 返回消息数据给微信服务器

​ return resp_xml_str

# 收到图片消息

​ if msg_type == "image":

# 表示发送的是文本消息

# 构造返回值,经由微信服务器回复给用户的消息内容

​ resp_dict = {
​ "xml": {
​ "ToUserName": xml_dict.get("FromUserName"),
​ "FromUserName": xml_dict.get("ToUserName"),
​ "CreateTime": int(time.time()),
​ "MsgType": "text",
​ "PicUrl": xml_dict.get("PicUrl"),
​ "MediaId": xml_dict.get("MediaId"),

# "MsgId" : xml_dict.get("MsgId")

​ "MsgId": "1234567890123456"
​ }
​ }

# 将字典转换为xml字符串

​ resp_xml_str = xmltodict.unparse(resp_dict)

# 返回消息数据给微信服务器

​ return resp_xml_str
​ else:
​ resp_dict = {
​ "xml": {
​ "ToUserName": xml_dict.get("FromUserName"),
​ "FromUserName": xml_dict.get("ToUserName"),
​ "CreateTime": int(time.time()),
​ "MsgType": "text",
​ "Content": "欢迎关注iBoy博客!"
​ }
​ }
​ resp_xml_str = xmltodict.unparse(resp_dict)

# 返回消息数据给微信服务器

​ return resp_xml_str
iBoy wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!