def prepare(self): self.appid = options.wx_appid self.appsecret = options.wx_appsecret self.token = options.wx_token self.wechat = WxBasic(appid=self.appid, appsecret=self.appsecret, token=self.token)
class WechatHandler(tornado.web.RequestHandler): def prepare(self): self.wechat = WxBasic(appid='YOUR APPID', appsecret='YOUR APPSECRET', token='YOUR TOKEN') def get(self): #首次接入验证,传入url上的query字符串键值对 if self.wechat.check_signature(self.query_arguments): echo_str = self.get_query_argument('echostr', '') self.write(echo_str) else: self.write('wrong, request not from wechat!') def post(self): self.wechat.parse_data(self.request.body) message = self.wechat.message #收到消息后针对不同消息类型进行处理 if message.msgType == 'text': content = message.content print u'收到文本消息:%s' % content self.write(self.wechat.pack_text(content)) return elif message.msgType == 'image': pass elif message.msgType == 'event': pass @property def query_arguments(self): """获取url中的查询字符串dict""" query = {} for k in self.request.arguments.keys(): query[k] = self.get_query_argument(k) return query
class WechatHandler(BaseHandler): def prepare(self): self.appid = options.wx_appid self.appsecret = options.wx_appsecret self.token = options.wx_token self.wechat = WxBasic(appid=self.appid, appsecret=self.appsecret, token=self.token) def get(self): if self.wechat.check_signature(self.query_arguments): echo_str = self.get_query_argument('echostr', '') self.write(echo_str) else: self.write('wrong, request not from wechat!') def post(self): if not self.wechat.check_signature(self.query_arguments): return self.write('signature error!') self.wechat.parse_data(self.request.body, query=self.query_arguments) message = self.wechat.message if message.msgType != 'event' and self._check_repeat(message.msgId): return self.write('') pp(message) if message.msgType == 'text': if message.content == u'菜单': results = WxApi(self.wx_access_token).create_menu(_menu_dict()) self.write(self.wechat.pack_text(results.get('errmsg', ''))) return self.test(message) reply = self.wechat.pack_text('hi') self.write(reply) def test(self, message): pass @property def query_arguments(self): query = {} for k in self.request.arguments.keys(): query[k] = self.get_query_argument(k) return query def _check_repeat(self, msg_id): old_msg_id = self.cache.get("wechat_message_id") if old_msg_id and old_msg_id == msg_id: return True self.cache.set('wechat_message_id', msg_id) return False
def prepare(self): self.wechat = WxBasic(appid='YOUR APPID', appsecret='YOUR APPSECRET', token='YOUR TOKEN')