Flask实现微信公众号后台原来如此简单
Posted 软件开发学习历程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask实现微信公众号后台原来如此简单相关的知识,希望对你有一定的参考价值。
前 言
对于flask学习感觉官网就是很好很标准的教材,感觉这个文档写的特别清晰和清楚,参考如下:
https://dormousehole.readthedocs.io/en/latest/
创建虚拟环境
# cd py-wechat #py-weckat是我们创建的开发目录
# python -m venv venv
# .venvScriptsactivate #激活虚拟环境
# 安装依赖
# pip install Flask
# pip install requests
开始编码
导入依赖包
from flask import Flask, request, make_response
import hashlib
import xml.etree.ElementTree as ET
from uiai import get_response
import time
初始化flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5050)
编写微信验证接口
在这里我们要编写一个接口,微信通过get方法调用该接口,本接口通过校验微信传过来的参数,来判断是否是来自微信服务器的请求
@app.route("/wechat/security", methods=['GET', 'POST'])
def wechat():
if request.method == 'GET':
token = WX_TOKEN
data = request.args
signature = data.get('signature', '')
timestamp = data.get('timestamp', '')
nonce = data.get('nonce', '')
echostr = data.get('echostr', '')
s = sorted([timestamp, nonce, token])
s = ''.join(s)
if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:
response = make_response(echostr)
return response
else:
pass
在这里呢,我就接收到用户的文本消息后,调用公司的一个接口,获取相应文本,用于响应用户,达到与用户聊天的效果,网上看到很多都是调用图灵接口的。
由于我们公司有这样的接口调用,因此,就直接调用公司接口了。
@app.route("/wechat/security", methods=['GET', 'POST'])
def wechat():
if request.method == 'GET':
token = WX_TOKEN
data = request.args
signature = data.get('signature', '')
timestamp = data.get('timestamp', '')
nonce = data.get('nonce', '')
echostr = data.get('echostr', '')
s = sorted([timestamp, nonce, token])
s = ''.join(s)
if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:
response = make_response(echostr)
return response
else:
xml = ET.fromstring(request.data)
toUser = xml.find('ToUserName').text
fromUser = xml.find('FromUserName').text
msgType = xml.find('MsgType').text
if msgType == 'text':
content = xml.find('Content').text
return reply_text(fromUser, toUser, get_response(fromUser, content))
else:
return reply_text(fromUser, toUser, "嗯?我听不太懂")
# 生成响应微信公众号的xml
def reply_text(to_user, from_user, content):
reply = """
<xml><ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag></xml>
"""
response = make_response(reply % (to_user, from_user,
str(int(time.time())), content))
response.content_type = 'application/xml'
return response
新建uiai.py实现调用文本接口
import os
import requests
def get_response(userId, text):
api = 'http://fx.hekouxin.com/5g/chatbox/text'
payload = {}
payload['userId'] = userId
payload['text'] = text
resp = requests.post(api, payload).json()
print(userId, '闲聊返回', resp)
mesage = resp['data']
if mesage is None:
mesage = '嗯?我好像不太懂'
return mesage
完整代码
app.py
from flask import Flask, request, make_response
import hashlib
import xml.etree.ElementTree as ET
from uiai import get_response
import time
app = Flask(__name__)
WX_TOKEN = '***'
# 这里填写下面公众号配置的token
@app.route("/")
def chat():
data = request.args
userId = data.get('userId')
text = data.get('text')
print(userId + text)
return get_response(userId, text)
@app.route("/wechat/security", methods=['GET', 'POST'])
def wechat():
if request.method == 'GET':
token = WX_TOKEN
data = request.args
signature = data.get('signature', '')
timestamp = data.get('timestamp', '')
nonce = data.get('nonce', '')
echostr = data.get('echostr', '')
s = sorted([timestamp, nonce, token])
s = ''.join(s)
if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:
response = make_response(echostr)
return response
else:
xml = ET.fromstring(request.data)
toUser = xml.find('ToUserName').text
fromUser = xml.find('FromUserName').text
msgType = xml.find('MsgType').text
if msgType == 'text':
content = xml.find('Content').text
return reply_text(fromUser, toUser, get_response(fromUser, content))
else:
return reply_text(fromUser, toUser, "嗯?我听不太懂")
def reply_text(to_user, from_user, content):
reply = """
<xml><ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag></xml>
"""
response = make_response(reply % (to_user, from_user,
str(int(time.time())), content))
response.content_type = 'application/xml'
return response
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5050)
uiai.py
import os
import requests
def get_response(userId, text):
api = 'http://***/text'
payload = {}
payload['userId'] = userId
payload['text'] = text
resp = requests.post(api, payload).json()
print(userId, '闲聊返回', resp)
mesage = resp['data']
if mesage is None:
mesage = '嗯?我好像不太懂'
return mesage
进入左下角 开发-》基本配置,就可以打开如下页面,填写自己的token和网址就可以点击启用了。如果能够出现在这个页面就是成功了。
结 果
最终我们可以实现与用户简单的交流功能。
使用flask开发后台,还是比较简洁的,不用多少行的代码就可以实现。
以上是关于Flask实现微信公众号后台原来如此简单的主要内容,如果未能解决你的问题,请参考以下文章