豆瓣搜索—微信公共平台接入(wechatpy)
上篇文章介绍了如何对接微信公共平台,但是里面的校验代码是我们自己实现的。但是目前我们有了更好的选择----wechatpy。微信(WeChat) 公众平台第三方 Python SDK,实现了普通公众平台和企业号公众平台的解析消息、生成回复和主动调用等 API。详情请看http://wechatpy.readthedocs.org/en/latest/里面的介绍。
wechatpy里面已经封装好了校验模块,直接调用check_signature就可以完成校验工作,修改后的代码如下:
#!/bin/env python # -*- coding: utf-8 -*- import hashlib, urllib, urllib2, re, time, json import xml.etree.ElementTree as ET from flask import Flask, request, render_template from config import APP_SECRET_KEY from lib.wechatpy import parse_message, create_reply from lib.wechatpy.utils import check_signature from lib.wechatpy.exceptions import InvalidSignatureException app = Flask(__name__) app.debug = True app.secret_key = APP_SECRET_KEY TOKEN = 'douban_book' #注意要与微信公众帐号平台上填写一致 @app.route('/') def home(): return render_template('index.html') #公众号消息服务器网址接入验证 #需要在公众帐号管理台手动提交, 验证后方可接收微信服务器的消息推送 @app.route('/weixin', methods=['GET', 'POST']) def weixin(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: msg = parse_message(request.data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render() if __name__ == '__main__': app.run()