python flask四步配置微信公众号自动回复
第一步
注册微信公众号、实名
然后
URL:是你的服务器地址
Token可以随便填写,但是要记住这个你写的东西
消息加解密方式:明文
提示:在提交的时候,会发送一个验证,只用验证通过才能提交通过
详情参考https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html#_1-4-%E5%BC%80%E5%8F%91%E8%80%85%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
第二步
创建main.py
import time
from flask import Flask,make_response,request
import xml.etree.cElementTree as ET
import hashlib
app= Flask(__name__)
@app.route('/wx',methods=['GET','POST'])
def wechat():#1、 获取携带的 signature、timestamp、nonce、echostr
if request.method == 'GET':
signature = request.args.get("signature", "")
timestamp= request.args.get("timestamp", "")
nonce= request.args.get("nonce", "")
echostr= request.args.get("echostr", "")
print(signature, timestamp, nonce, echostr)
token="wxtokenone" #这里是你写的那个token值
data =[token, timestamp, nonce]
data.sort()#3、三个参数拼接成一个字符串并进行sha1加密
temp = ''.join(data)
sha1= hashlib.sha1(temp.encode('utf-8'))
hashcode=sha1.hexdigest()
print(hashcode)#4、对比获取到的signature与根据上面token生成的hashcode,如果一致,则返回echostr,对接成功
if hashcode == signature:
return echostr
else:
return "error"
else:
xmlData = ET.fromstring(request.stream.read())
msg_type = xmlData.find('MsgType').text
if msg_type == 'text':
if xmlData.find('Content').text == '暗号':
ToUserName = xmlData.find('ToUserName').text
FromUserName = xmlData.find('FromUserName').text
# Content = xmlData.find('Content').text
Content = '对应暗号:<a style="color:red;" src="http://d-dlpay.top">0000</a>\n百度链接:<a src="http://www.baidu.com">喂</a>'
reply = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
'''
response = make_response(reply % (FromUserName, ToUserName, str(int(time.time())), Content))
response.content_type = 'application/xml'
return response
else:
t = '正在输入....'
return gettext(xmlData,t)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)#这里开放8080端口
第三步
若是本地调试,则使用内网穿透工具,使用8080端口
这里使用cpolar
工具24小时后会自动更换网址或关闭了该工具也会自动更换
第四步
查看是否成功