reply.py
import timeclass Msg(object): def __init__(self): pass def send(self): return "success"class TextMsg(Msg): def __init__(self, toUserName, fromUserName, content): self.__dict = dict() self.__dict['ToUserName'] = toUserName self.__dict['FromUserName'] = fromUserName self.__dict['CreateTime'] = int(time.time()) self.__dict['Content'] = content def send(self): XmlForm = """ <xml> <ToUserName><![CDATA[{ToUserName}]]></ToUserName> <FromUserName><![CDATA[{FromUserName}]]></FromUserName> <CreateTime>{CreateTime}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{Content}]]></Content> </xml> """ return XmlForm.format(**self.__dict)class ImageMsg(Msg): def __init__(self, toUserName, fromUserName, mediaId): self.__dict = dict() self.__dict['ToUserName'] = toUserName self.__dict['FromUserName'] = fromUserName self.__dict['CreateTime'] = int(time.time()) self.__dict['MediaId'] = mediaId def send(self): XmlForm = """ <xml> <ToUserName><![CDATA[{ToUserName}]]></ToUserName> <FromUserName><![CDATA[{FromUserName}]]></FromUserName> <CreateTime>{CreateTime}</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Image> <MediaId><![CDATA[{MediaId}]]></MediaId> </Image> </xml> """ return XmlForm.format(**self.__dict)main.py
from flask import Flaskfrom flask import requestimport hashlibimport receiveimport replyapp = Flask(__name__)@app.route("/")def index(): return "Hello World!"# 公众号后台消息路由入口@app.route("/wechat", methods=["GET", "POST"])def wechat(): # 验证使用的GET方法 if request.method == "GET": signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') echostr = request.args.get('echostr') token = "公众号后台填写的token" # 进行排序 dataList = [token, timestamp, nonce] dataList.sort() result = "".join(dataList) #哈希加密算法得到hashcode sha1 = hashlib.sha1() sha1.update(result.encode("utf-8")) hashcode = sha1.hexdigest() if hashcode == signature: return echostr else: return "" else: recMsg = receive.parse_xml(request.data) if isinstance(recMsg, receive.Msg): toUser = recMsg.FromUserName fromUser = recMsg.ToUserName if recMsg.MsgType == 'text': content = recMsg.Content replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() elif recMsg.MsgType == 'image': mediaId = recMsg.MediaId replyMsg = reply.ImageMsg(toUser, fromUser, mediaId) return replyMsg.send() else: return reply.Msg().send() else: return reply.Msg().send()if __name__ == "__main__": app.run(host='0.0.0.0', port=80) #公众号后台只开放了80端口
推荐阅读
- Python爬虫案例:爬取微信公众号文章
- 小程序云开发支持公众号网页开发了
- 机器学习概念和经典算法,我用大白话给你讲清楚了!入门必看
- 一行代码让你的python运行速度提高100倍
- 新手如何快速推广微信公众号
- 道光为什么不传位给恭亲王 恭亲王奕欣和光绪什么关系
- 西汉东方朔 东方朔给汉武帝写了一篇文章
- 教你学会网易云JS逆向,爬来的歌打包发给女友邮箱可好?
- 详解Hbase底层的数据结构——LSMT
- 在30分钟内创建你的深度学习服务器
