def check_wechat(self, signature, timestamp, nonce): try: check_signature(self.token, signature, timestamp, nonce) except InvalidSignatureException: return False return True
def handle_msg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source if msg.type == 'event': if msg.event == 'click': print(msg.key) if msg.key == 'sports_advice': rep.content = recommend_plan(msg.source) elif msg.key == 'view_info': rep.content = get_info(msg.source) elif msg.key == 'add_test': rep.content = add_test(msg.source) elif msg.key == 'show_today': rep.content = get_datatoday(msg.source) elif msg.event == 'subscribe': rep.content = create_newuser(msg.source) else: rep.content = '!!!' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">你好</a>' repxml = rep.render() return HttpResponse(repxml)
def wechat_handler(): try: token = current_app.config['WECHAT_TOEKN'] signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') check_signature(token, signature, timestamp, nonce) current_app.logger.info('wechat_handler begin') body = request.get_data() current_app.logger.info('wechat_handler body %s' % body) msg = parse_message(body) if msg.type == 'text': return reply_msg(msg) elif msg.type == 'event' and msg.event == 'click' and msg.key == 'V2003_SignIn': return sign_in(msg) elif msg.type == 'event' and msg.event in ['subscribe_scan', 'scan'] and msg.scene_id == '123': binding(msg) if msg.event == 'subscribe_scan': return welcome_article(msg) elif msg.type == 'event' and msg.event == 'unsubscribe': unsubscribe_unbinding(msg) elif msg.type == 'event' and msg.event == 'subscribe': return welcome_article(msg) reply = EmptyReply() return reply.render() except InvalidSignatureException: abort(404) except Exception as e: current_app.logger.exception('wechat_handler %s' % e) reply = EmptyReply() return reply.render()
def _wechat_required(method, *args, **kwargs): from wechatpy.crypto import WeChatCrypto from wechatpy import parse_message signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') if not current_app.config.get('WECHAT_TOKEN'): return abort(500, "Token is None") token = current_app.config['WECHAT_TOKEN'] try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: current_app.logger.warning('check signature failed.') return abort(403) if request.method == 'GET': return request.args.get('echostr', '') raw_msg = request.data current_app.logger.debug(raw_msg) if current_app.config.get('WECHAT_AES_KEY'): crypto = WeChatCrypto( current_app.config['WECHAT_TOKEN'], current_app['WECHAT_AES_KEY'], current_app.config['WECHAT_APPID'] ) try: raw_msg = crypto.decrypt_message( raw_msg, signature, timestamp, nonce ) except (InvalidAppIdException, InvalidSignatureException): current_app.logger.warning('decode message failed.') return abort(403) request.wechat_msg = parse_message(raw_msg) res = method(*args, **kwargs) xml = '' if isinstance(res, BaseReply): xml = res.render() if current_app.config.get('WECHAT_AES_KEY'): crypto = WeChatCrypto( current_app.config['WECHAT_TOKEN'], current_app.config['WECHAT_AES_KEY'], current_app.config['WECHAT_APPID'] ) xml = crypto.encrypt_message(xml, nonce, timestamp) return xml
def index(): # print request.args # print json.dumps(request.args) if request.method == 'GET': data = request.args signature = data.get('signature') timestamp = data.get('timestamp') nonce = data.get('nonce') echostr = data.get('echostr') token = current_app.config.get('TOKEN') try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: return 'invalid signature' return echostr else: xml = request.data print xml msg = parse_message(xml) if msg.type == 'text': print msg.content reply = TextReply(message=msg) reply.content = u'reply 测试' xml_reply = reply.render() return xml_reply elif msg.type == 'image': reply = ImageReply(message=msg) reply.media_id = msg.media_id xml_reply = reply.render() return xml_reply elif msg.type == 'voice': # reply = VoiceReply(message=msg) # reply.media_id = msg.media_id reply = TextReply(message=msg) reply.content = msg.recognition xml_reply = reply.render() return xml_reply elif msg.type == 'video': reply = VideoReply(message=msg) reply.media_id = msg.media_id reply.title = u'你的video' reply.description = u'wo 爱倪呀' xml_reply = reply.render() return xml_reply pass elif msg.type == 'location': pass elif msg.type == 'link': pass elif msg.type == 'shortvideo': reply = VideoReply(message=msg) reply.media_id = msg.thumb_media_id reply.title = u'你的video' reply.description = u'wo 爱倪呀' xml_reply = reply.render() return xml_reply else: return ''
def process_request(self, request): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') try: check_signature(config.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: raise Forbidden()
def dispatch(self, request, *args, **kwargs): signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') try: check_signature(settings.WX_SIGN_TOKEN, signature, timestamp, nonce) return super(WeiXinHook, self).dispatch(request, *args, **kwargs) except InvalidSignatureException: logger.warning('Illegal Access!') return HttpResponse('Welcome to WeCron')
def message_entries(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') try: check_signature(Config.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) # 微信验证 if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.data) # 事件处理 if msg.type == 'event': # 关注事件 if msg.event == 'subscribe': mfc = MenuFunc(msg.source) mfc.subscribecreatemenu() reply = create_reply(msg.event, msg) elif msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'image': reply = create_reply('对不起,暂时不支持图片消息', msg) else: reply = create_reply(msg.type, msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(Config.TOKEN, Config.AES_KEY, Config.APPID) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def get(self): echostr = self.get_argument('echostr', '') signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') try: check_signature(options.token, signature, timestamp, nonce) except InvalidSignatureException: logging.warning("Signature check failed.") else: logging.info("Signature check success.") self.write(echostr)
def on_get(self, req, resp): query_string = req.query_string query_list = query_string.split('&') b = {} for i in query_list: b[i.split('=')[0]] = i.split('=')[1] try: check_signature(token='lengxiao', signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce']) resp.body = (b['echostr']) except InvalidSignatureException: pass resp.status = falcon.HTTP_200
def handle_msg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source if msg.type == 'event': if msg.event == 'click': if msg.key == 'sports_advice': rep.content = recommend_plan(msg.source) elif msg.key == 'view_info': rep.content = get_info(msg.source) elif msg.key == 'add_bong': rep.content = add_bong(msg.source) elif msg.key == 'add_test': rep.content = add_test(msg.source) elif msg.key == 'add_test_new': rep.content = add_test_new(msg.source) elif msg.key == 'show_today': rep.content = get_datatoday(msg.source) elif msg.key == 'change_remind': rep.content = set_remind(msg.source) elif msg.key == 'build_match': article_rep = ArticlesReply() article_rep.source = msg.target article_rep.target = msg.source article_rep.add_article({ 'title': '创建比赛', 'description': '点此链接以创建比赛', 'image': serverIP+'static/img/run02.jpg', 'url': build_match(msg.source) }) repxml = article_rep.render() return HttpResponse(repxml) elif msg.event == 'subscribe': rep.content = create_newuser(msg.source) else: rep.content = '!!!' else: rep.content = '你好' repxml = rep.render() return HttpResponse(repxml)
def handle_encrypt(self, **kwargs): msg_signature = request.params.get('msg_signature', '') signature = request.params.get('signature', '') timestamp = request.params.get('timestamp', '') nonce = request.params.get('nonce', '') encrypt_type = request.params.get('encrypt_type', 'raw') echo_str = request.args.get('echostr', '') try: check_signature(self.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str # POST if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.httprequest.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() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(self.TOKEN, self.AES_KEY, self.APPID) # 公众号 try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat_auth(): """ 微信授权验证 """ token = app.config['TOKEN'] signature = request.args.get('signature', None) timestamp = request.args.get('timestamp', None) echostr = request.args.get('echostr', None) nonce = request.args.get('nonce', None) try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: return 'failure' return str(echostr)
def wechat(): sign = request.args.get('signature', '') ts = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') try: check_signature(setting.WECHAT_TOKEN, sign, ts, nonce) except InvalidSignatureException: return abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request. if encrypt_type != 'raw': return 'Sorry, I Don\'t Understand' return bot.response(request)
def on_get(self, req, resp): # print("get_req:{}".format(req)) query_string = req.query_string query_list = query_string.split('&') b = {} for i in query_list: b[i.split('=')[0]] = i.split('=')[1] try: check_signature(token=config.Token, signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce']) resp.body = (b['echostr']) except InvalidSignatureException: pass resp.status = falcon.HTTP_200
def reply_test(url, request): self.assertEqual(url.scheme, scheme) self.assertEqual(url.netloc, netloc) self.assertEqual(url.path, path) query = dict(parse_qsl(url.query)) self.assertEqual(query["timestamp"], timestamp) self.assertEqual(query["nonce"], nonce) self.assertEqual(query["signature"], signature) check_signature(self.app.token, query["signature"], timestamp, nonce) msg = parse_message(request.body) self.assertIsInstance(msg, messages.TextMessage) self.assertEqual(msg.source, sender) self.assertEqual(msg.content, content) reply = replies.create_reply(reply_text, msg) return response(content=reply.render())
def decorated_function(*args, **kwargs): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: if request.method == 'POST': return "signature failed" else: return redirect(app.config['MAIN_URL']) return func(*args, **kwargs)
def _verify(self, request): """检验请求""" try: timestamp = int(request.GET["timestamp"]) except ValueError: raise BadMessageRequest("invalid timestamp") sign = request.GET["signature"] nonce = request.GET["nonce"] time_diff = int(timestamp) - time.time() # 检查timestamp if abs(time_diff) > settings.MESSAGETIMEOFFSET: raise BadMessageRequest("invalid time") # 防重放检查及签名检查 with self._no_repeat_nonces(sign, nonce, time_diff): check_signature(request.wechat.app.token, sign, timestamp, nonce)
def echo(request): if request.method == "GET": signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) echostr = request.GET.get('echostr', None) try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: return HttpResponse('failed') return HttpResponse(echostr) else: signature = request.GET.get('signature', None) msg_signature = request.GET.get('msg_signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) encrypt_type = request.GET.get('encrypt_type', None) xml = request.body #print signature, timestamp, nonce, encrypt_type, msg_signature crypto = WeChatCrypto(token, encoding_aes_key, app_id) try: # print 'encryped xml: %s' % xml decrypted_xml = crypto.decrypt_message(xml, msg_signature, timestamp, nonce) # print 'decryped xml: %s' % decrypted_xml except (InvalidAppIdException, InvalidSignatureException): # 处理异常或忽略 pass msg = parse_message(decrypted_xml) if msg.type == 'text': print 'message arrived[%s]: %s' % (msg.type, msg.content) reply = create_reply(msg.content, msg) else: print 'message arrived[%s]: %s' % (msg.type, 'not support') reply = create_reply('Sorry, can not handle this for now', msg) encrypted_msg = crypto.encrypt_message(reply.render(), nonce, timestamp) return HttpResponse(encrypted_msg)
def get(self): # get var from request args, 微信接入 signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echostr = request.args.get('echostr', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: # 处理异常情况或忽略 print('>>> {},{}'.format(request.args, '验证异常')) # return '验证异常' return 'Shutting down...' else: print('>>> {},{}'.format(request.args, '验证ok')) return echostr
def handle_encrypt(self, **kwargs): msg_signature = request.params.get('msg_signature', '') signature = request.params.get('signature', '') timestamp = request.params.get('timestamp', '') nonce = request.params.get('nonce', '') encrypt_type = request.params.get('encrypt_type', 'raw') echo_str = request.args.get('echostr', '') try: check_signature(self.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.httprequest.method == 'GET': return echo_str # POST if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.httprequest.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() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(self.TOKEN, self.AES_KEY, self.APPID) # 公众号 try: msg = crypto.decrypt_message(request.httprequest.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat(request): if request.method == 'GET': signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) echostr = request.GET.get('echostr', None) try: check_signature(settings.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' return HttpResponse(echostr) elif request.method == 'POST': msg = parse_message(request.body) if msg.type == 'text': reply = TransferCustomerServiceReply(message=msg) elif msg.type == 'image': reply = ImageReply(message=msg) reply.media_id = msg.media_id elif msg.type == 'voice': reply = VoiceReply(message=msg) reply.media_id = msg.media_id reply.content = '语音信息' elif msg.type == 'event': print('eventkey=', msg.event) if msg.event == 'subscribe': saveUserinfo(msg.source) reply = create_reply('你好,欢迎关注亚电新能源', msg) elif msg.event == 'unsubscribe': reply = create_reply('取消关注公众号', msg) unSubUserinfo(msg.source) elif msg.event == 'subscribe_scan': reply = create_reply('你好,欢迎关注亚电新能源', msg) saveUserinfo(msg.source, msg.scene_id) elif msg.event == 'scan': reply = create_reply('', msg) else: reply = create_reply('view', msg) else: reply = create_reply('', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response
def wechat(): 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()
def on_get(self, req, resp): query_string = req.query_string # 调试时查看一下返回的内容 print(query_string) query_list = query_string.split('&') b = {} for i in query_list: b[i.split('=')[0]] = i.split('=')[1] try: check_signature(token='Anastasia', signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce']) resp.body = (b['echostr']) except InvalidSignatureException: pass resp.status = falcon.HTTP_200
def wechatCheckLogin(): if request.method == 'GET': # pass signature = request.args.get('signature') echostr = request.args.get('echostr') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') try: check_signature(token=sysConfig.TOKEN, signature=signature, timestamp=timestamp, nonce=nonce) print(echostr) return echostr except InvalidSignatureException: return 'failed' else: # print(request.form) message = Reply(request) # message.text(message.Content) return message.reply()
def weixin_handler(): token = "zhouzhiyong" signature = flask.request.args.get("signature") timestamp = flask.request.args.get("timestamp") nonce = flask.request.args.get("nonce") echostr = flask.request.args.get("echostr") try: # 校验token check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: # 处理异常情况或忽略 flask.abort(403) # 校验token失败,证明这条消息不是微信服务器发送过来的 if flask.request.method == "GET": return echostr elif flask.request.method == "POST": print(flask.request.data)
def echo(request): signature = request.GET.get('signature', '') + request.POST.get( 'signature', '') timestamp = request.GET.get('timestamp', '') + request.POST.get( 'timestamp', '') nonce = request.GET.get('nonce', '') + request.POST.get('nonce', '') echo_str = request.GET.get('echostr', '') + request.POST.get('echostr', '') encrypt_type = request.GET.get('encrypt_type', '') + request.POST.get( 'encrypt_type', '') msg_signature = request.GET.get('msg_signature', '') + request.POST.get( 'msg_signature', '') print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echo_str) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: raise PermissionDenied if request.method == 'GET': return HttpResponse(echo_str) else: # use request.data in flask # print('Raw message: \n%s' % request.data) # use request.body in django print('Raw message: \n%s' % request.body) crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message(request.body, msg_signature, timestamp, nonce) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): raise PermissionDenied msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return HttpResponse( crypto.encrypt_message(reply.render(), nonce, timestamp))
def wx(request): if request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echostr = request.GET.get('echostr', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' return HttpResponse(echostr, content_type="text/plain") if request.method == 'POST': msg = parse_message(request.body) if msg.type == 'text' or msg.type == 'image' or msg.type == 'voice': reply_template = "<xml><ToUserName><![CDATA[{}]]></ToUserName>" \ "<FromUserName><![CDATA[{}]]></FromUserName>" \ "<CreateTime>{}</CreateTime>" \ "<MsgType><![CDATA[text]]></MsgType>" \ "<Content><![CDATA[{}]]></Content></xml>" content = '公众号首页暂不支持自动回复客服消息,请转到-我的->建议与反馈中留言,给您带来的不便,敬请谅解' reply = reply_template.format(msg.source, msg.target, str(create_timestamp()), content) return HttpResponse(reply, content_type="application/xml") elif msg.type == 'event': subcribe_event = SubscribeEvent(msg) if msg.event == subcribe_event.event: reply_msg = '欢迎来到,健康水机代理销售平台,我们终于等到你了' reply = create_reply(reply_msg, msg) log.info('create reply successfully') openid = msg.source subcribe_save_openid(openid) else: return 'success' else: return 'success' response = HttpResponse(reply.render(), content_type="application/xml") return response else: log.info('error') return 'error'
def wechat(request): if request.method == 'GET': print('GET请求来了--------') signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = 'error' response = HttpResponse(echo_str, content_type="text/plain") return response elif request.method == 'POST': print("POST请求来了--------") msg = parse_message(request.body) if msg.type == 'text': analysisObj = Analysis(smart_str(request.body)) print('smart_str',smart_str(request.body)) toWxData = analysisObj.prase(smart_str(request.body)) print(toWxData) return HttpResponse(smart_str(toWxData)) elif msg.type == 'image': reply = create_reply('这是条图片消息,图片信息我可看不懂/:P-(/:P-(/:P-(', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response elif msg.type == 'voice': reply = create_reply('这是条语音消息,语音信息我也听不懂/:P-(/:P-(/:P-(', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response else: reply = create_reply('这是条其他类型消息,暂时不处理', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response else: print('--------------------------------')
def wechat_auth(): # print(request.args) if request.method == 'GET': if len(request.args) > 3: token = 'lizhiwodage' query = request.args signature = query['signature'] timestamp = query['timestamp'] nonce = query['nonce'] echostr = query['echostr'] try: check_signature(token, signature, timestamp, nonce) make_response(echostr) except InvalidSignatureException: print("sinature认证失败") return make_response("sinature认证失败") else: print("args认证失败") return make_response("args认证失败") elif request.method == 'POST': rec = request.stream.read() msg = parse_message(rec) print("id=%s,source=%s,target=%s,type=%s" % (msg.id, msg.source, msg.target, msg.type)) content = "empty" if msg.type == "event": if msg.event == "pic_photo_or_album": if msg.key == "sign": content = "sign" process_sign(msg.count, msg.pictures) if msg.event == "click": if msg.key == "items": content = "items" process_items() if msg.type == "image": get_user_uploadpics(msg.source, msg.image) reply = TextReply(content=content, message=msg) xml = reply.render() response = make_response(xml) response.content_type = 'application/xml' return response
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echo_str) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: print('Raw message: \n%s' % request.data) crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message( reply.render(), nonce, timestamp )
def wechat(): signature = request.args.get("signature", "") timestamp = request.args.get("timestamp", "") nonce = request.args.get("nonce", "") encrypt_type = request.args.get("encrypt_type", "raw") msg_signature = request.args.get("msg_signature", "") try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == "GET": echo_str = request.args.get("echostr", "") return escape(echo_str) # POST request if encrypt_type == "raw": # plaintext mode msg = parse_message(request.data) if msg.type == "text": reply_text = MAIN_LOGIC.handle_msg(msg) reply = create_reply(reply_text, msg) elif msg.type == "event": reply_text = MAIN_LOGIC.handle_event(msg) reply = create_reply(reply_text, msg) else: reply = create_reply("Sorry, can not handle this for now", msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(TOKEN, AES_KEY, APPID) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == "text": reply = create_reply(msg.content, msg) else: reply = create_reply("Sorry, can not handle this for now", msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str else: push = parse_message(request.data) reply = create_reply('', message=push) ''' if not conn_user.exists(push.source): conn_user.set(push.source, '') if push.type == 'event' and push.event == 'click': conn_user.set(push.source, push.key) conn_user.expire(push.source, 15) # 30s to delete automatically if push.key == 'repeat': reply = create_reply('说话呀', message=push) elif push.key == 'emotion': reply = create_reply('说句话让俺瞧瞧', message=push) elif push.type == 'text': conn_text.rpush(push.source, push.content) if conn_user.get(push.source) == b"": reply = create_reply('闭嘴', message=push) else: conn_user.expire(push.source, 10) # 30s to delete automatically if conn_user.get(push.source) == b"repeat": reply = create_reply(push.content, message=push) elif conn_user.get(push.source) == b"emotion": rec = Emotion(push.content) # 语料情感分析 recognized = rec.recognize() reply = create_reply(recognized, message=push) ''' return reply.render()
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str _help = """1. 查询沪深股市股票价格,sh 开头表示沪股,sz 开头表示深股\n2. 输入'历史',查看历史查询记录\n3. 输入:'帮助',查看帮助文档\n""" # plaintext mode msg = parse_message(request.data) if msg.type == 'text': # 微信用户的 openid openid = msg.source # 历史 if msg.content in ['历史']: histories = query_all_wxuser_history(openid) histories_str = "".join([ '{} 查询 {}: {}\n'.format(item[3], item[1], item[2]) for item in histories ]) if histories_str: reply = create_reply(histories_str, msg) else: reply = create_reply('未有查询记录', msg) # 帮助 elif msg.content in ['帮助']: reply = create_reply(_help, msg) # 股价查询 else: result = get_hs_stock(msg.content) add_wxuser_history(openid, msg.content, result) reply = create_reply(result, msg) else: reply = create_reply('对不起,无法识别!!', msg) return reply.render()
async def interface(request): # get var from request args signature = request.raw_args.get('signature', '') timestamp = request.raw_args.get('timestamp', '') nonce = request.raw_args.get('nonce', '') echostr = request.raw_args.get('echostr', '') msg_signature = request.raw_args.get('msg_signature', '') encrypt_type = request.raw_args.get('encrypt_type', '') try: check_signature(config.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: # 处理异常情况或忽略 netlog.error('>>> {},{}'.format(request.raw_args, '验证异常')) return response.text('验证异常') else: if request.method == 'GET': # 服务器配置 log.info('>>> {},{}'.format(request.raw_args, '验证ok')) return response.text(echostr) else: # 公众号被动接受消息 if len(request.body) == 0: return response.text('') # 加密方式 if encrypt_type == 'aes': crypto = WeChatCrypto(config.WECHAT_TOKEN, config.WECHAT_ENCODING_AES_KEY, config.WECHAT_APPID) try: decrypted_xml = crypto.decrypt_message( request.body, msg_signature, timestamp, nonce) except (InvalidAppIdException, InvalidSignatureException): # to-do: 处理异常或忽略 log.error('>>> 加密处理异常') return response.text('') else: return response.text( get_resp_message(request, decrypted_xml, mode='aes')) else: # 纯文本方式 return response.text(get_resp_message(request, request.body))
def wechat(request): signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') encrypt_type = request.GET.get('encrypt_type', '') msg_signature = request.GET.get('msg_signature', '') # print('signature:', signature) # print('timestamp: ', timestamp) # print('nonce:', nonce) # print('echo_str:', echo_str) # print('encrypt_type:', encrypt_type) # print('msg_signature:', msg_signature) try: check_signature(CONFIG['token'], signature, timestamp, nonce) except InvalidSignatureException: raise RuntimeError('Signature Validate Failed.') if request.method == 'GET': return HttpResponse(echo_str) else: msg = _decrypt_and_parse_msg(request.body, msg_signature, timestamp, nonce) if msg.type == 'text': saved_snippet = _save_snippet(msg) if saved_snippet: reply = create_reply("定期总结和及时沟通内容已收到", msg) else: reply = create_reply("用户信息已保存", msg) elif msg.type == 'event': if msg.event == 'masssendjobfinish': # This silly piece of code is for handling the reply of mass messages return elif msg.key == 'query_state': reply = create_reply(_query_last_snippet_state(msg), msg) else: reply = create_reply(_get_template(), msg) else: reply = create_reply('对不起,现在尚不能支持此消息类型', msg) return HttpResponse( crypto.encrypt_message(reply.render(), nonce, timestamp))
def post(self): """被动接受消息""" signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') msg_signature = request.args.get('msg_signature', '') encrypt_type = request.args.get('encrypt_type', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: # 处理异常情况或忽略 print('>>> {},{}'.format(request.args, '验证异常')) # return '验证异常' return 'Shutting down...' # 公众号被动接受消息 if len(request.data) == 0: print('>>>', '接收到空字节') return '' print('>>> [{}]'.format(request.data)) # 加密方式 if encrypt_type == 'aes': crypto = WeChatCrypto(WECHAT_TOKEN, WECHAT_ENCODING_AES_KEY, WECHAT_APPID) try: decrypted_xml = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidAppIdException, InvalidSignatureException): # to-do: 处理异常或忽略 print('>>> 加密处理异常') return '' else: xml = get_resp_message(decrypted_xml) crypto = WeChatCrypto(WECHAT_TOKEN, WECHAT_ENCODING_AES_KEY, WECHAT_APPID) encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp) return encrypted_xml else: # 纯文本方式 return get_resp_message(request.data)
def on_get(self, req, resp): query_string = req.query_string print(query_string) query_list = query_string.split('&') b = {} for i in query_list: b[i.split('=')[0]] = i.split('=')[1] try: check_signature(token='123456', signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce']) resp.body = (b['echostr']) except InvalidSignatureException: with open("./debug.log", 'a') as f: f.write("text handler:" + str(e)) f.close() pass resp.status = falcon.HTTP_200
def wechat_core(): if request.method == 'GET': """verifying""" data = request.args.to_dict() signature = data.get('signature') timestamp = data.get('timestamp') nonce = data.get('nonce') echostr = data.get('echostr') token = os.environ.get('WEBOX_TOKEN') try: check_signature(token, signature, timestamp, nonce) get_logger().info('check signature successfully') return echostr except InvalidSignatureException: get_logger().warning('invalid signature from wechat') return 'Invalid request from wechat!' else: msg = parse_message(request.data) r = dispose_message(msg) return r.render()
def Check_token(): """ 用来验证微信公众号后台链接 :return: """ rq_dict = request.args if len(rq_dict) == 0: return "" signature = request.args.get('signature') # 提取请求参数 timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') echostr = request.args.get('echostr') try: check_signature(token='验证token', signature=signature, timestamp=timestamp, nonce=nonce) # 使用wechat库验证 except InvalidSignatureException as e: print(e) return '' else: print(111111) return echostr # 返回数据
def check_signature(self): signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') try: if not check_signature(self.settings['wechat_token'], signature, timestamp, nonce): return True except InvalidSignatureException: # 处理异常情况或忽略 pass
def hello_world(): try: signature = request.args.get('signature', None) timestamp = request.args.get('timestamp', None) nonce = request.args.get('nonce') check_signature(TOKEN, signature, timestamp, nonce) wechat_logger.info('request.args is %s' % request.args) crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str except: return 'error'
def test1(request): print('!!!!!!') if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) print('!!!') return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) print(msg.content) print(msg.source) print(msg.target) rep = TextReply() rep.source = msg.target rep.target = msg.source rep.content = '<a href="http://www.baidu.com">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def post(self): signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') try: check_signature(options.token, signature, timestamp, nonce) except InvalidSignatureException: logging.warning("Signature check failed.") return self.set_header("Content-Type", "application/xml;charset=utf-8") body = self.request.body msg = parse_message(body) if not msg: logging.info('Empty message, ignored') return # new bot bot = AI(msg) if msg.type == 'text': if options.debug: logging.info('message type text from %s', msg.source) response = bot.respond(msg.content, msg) reply = create_reply(response, msg, render=True) self.write(reply) if options.debug: logging.info('Replied to %s with "%s"', msg.source, response) elif msg.type == 'location': if options.debug: logging.info('message type location from %s', msg.source) elif msg.type == 'image': if options.debug: logging.info('message type image from %s', msg.source) else: logging.info('message type unknown')
def handleMsg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source print(msg.type) if msg.type == 'event': if msg.event == 'click': if msg.key == 'change_info': rep.content = '请点击下面的链接修改信息\n<a href="http://59.66.139.224/showinfo?openID= '+ msg.source + '">修改信息</a>' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def wechat_auth(): if request.method == 'GET': token = 'zzl.foo' query = request.args signature = query.get('signature', '') timestamp = query.get('timestamp', '') nonce = query.get('nonce', '') echostr = query.get('echostr', '') print(signature) try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: abort(403) return make_response(echostr) else: rec = request.stream.read() xml_rec = ET.fromstring(rec) msgtype = xml_rec.find('MsgType').text tou = xml_rec.find('ToUserName').text fromu = xml_rec.find('FromUserName').text xml_rep_img = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl></item></Articles><FuncFlag>1</FuncFlag></xml>" xml_rep_mutiimg = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>6</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><PicUrl><![CDATA[%s]]></PicUrl></item><item><Title><![CDATA[我的冰箱]]></Title><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[定制早餐]]></Title><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[定制午餐]]></Title><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[定制晚餐]]></Title><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[结伴购物]]></Title><Url><![CDATA[%s]]></Url></item></Articles></xml>" #用户一旦关注改公众账号,自动回复以下图文消息 if msgtype == "event": msgcontent = xml_rec.find('Event').text if msgcontent == "subscribe": msgcontent = 'Welcome!' else: msgcontent = 'error' msg_title = u"美食助手,您的私人定制" msg_imag_url = "http://gourmetmaster.sinaapp.com/static/main_meitu_3.jpg" response = make_response(xml_rep_img % (fromu,tou,str(int(time.time())),msg_title,msgcontent,msg_imag_url)) response.content_type='application/xml' return response
def test_check_signature_should_ok(self): token = 'test' signature = 'f21891de399b4e33a1a93c9a7b8a8fffb5a443ff' timestamp = '1410685589' nonce = 'test' check_signature(token, signature, timestamp, nonce)
def weixin(): if request.method == 'GET': _g = lambda k: request.args.get(k) try: print(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) check_signature(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) return _g('echostr') except InvalidSignatureException: pass elif request.method == 'POST': msg = parse_message(request.data) if isinstance(msg, ClickEvent): ev = msg if ev.key == WX_BTN_BIND_BX: reply = TextReply() reply.source = ev.target reply.target = ev.source reply.content = '请访问以下链接登陆到BX邮箱\n%s' % ( '%s?%s' % (urljoin(DOMAIN, 'mslogin'), urlencode({'wx': ev.source})) ) return reply.render() elif ev.key == WX_BTN_BEGIN_CHECKIN: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '哦' return reply.render() elif isinstance(msg, TextMessage): if msg.content.lower().startswith('e'): reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: return '哦' elif isinstance(msg, ScanEvent) or isinstance(msg, SubscribeScanEvent): openid = msg.source meetingid = msg.scene_id meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) checkin_time, ps = emit_checked_in(openid=openid, meeting=meeting) r = check_in(openid=openid, meetingid=meetingid, punish_str=ps, checkin_time=checkin_time) meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) print(meeting) if all_attendees_checked(meeting['attendee']): s = '签到汇总\n%s' ra = [] for u in meeting['attendee']: print(u) full_u = mongo.db.users.find_one({'openid': u['openid']}) ra.append([full_u['outlook']['name'], u['punish_str']]) s %= '\n'.join(map(lambda ss: ': '.join(ss), ra)) tmp = list(map(lambda u: u['openid'], meeting['attendee'])) tmp.append(meeting['organizer']['openid']) if len(tmp) > 1: wx.message.send_mass_text(tmp, s, is_to_all=True) else: wx.message.send_text(tmp[0], s) # return r wx.message.send_text(openid, r) reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择查看签到状况\n%s' % ( '%s/check-in-members?meetingid=%s' % (DOMAIN, meetingid) ) return reply.render()
def test_check_signature_should_fail(self): token = 'test' signature = 'f21891de399b4e33a1a93c9a7b8a8fffb5a443fe' timestamp = '1410685589' nonce = 'test' self.assertFalse(check_signature(token, signature, timestamp, nonce))
def wechat(request): """ 此地址为响应微信发送的Token验证,验证服务器配置是否正确 :param request: :return: """ signature = request.GET.get('signature', 'c58469c4151fac046efe180b277c51b1e5b563d3') timestamp = request.GET.get('timestamp', '1451138472') nonce = request.GET.get('nonce', '1432579014') echo_str = request.GET.get('echostr', '2691756735856574460') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echo_str) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) try: check_signature(settings.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: return HttpResponseForbidden() if request.method == 'GET': return echo_str else: print('Raw message: \n%s' % request.data) crypto = WeChatCrypto(settings.WECHAT_TOKEN, settings.EncodingAESKey, settings.WECHAT_APPID) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): return HttpResponseForbidden() msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'image': reply = ArticlesReply(message=msg) # simply use dict as article reply.add_article({ 'title': 'test', 'description': 'test', 'image': 'image url', 'url': 'url' }) # or you can use ObjectDict article = ObjectDict() article.title = 'test' article.description = 'test' article.image = 'image url' article.url = 'url' reply.add_article(article) # reply = create_reply([article], msg) else: reply = create_reply('Sorry, can not handle this for now', msg) msg= crypto.encrypt_message( reply.render(), nonce, timestamp) print(msg) return HttpResponse(msg)
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') xml = request.data # 验证 try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request if encrypt_type != 'aes': # plaintext mode msg = parse_message(xml) # id 消息 id, 64 位整型。 # source 消息的来源用户,即发送消息的用户。 # target 消息的目标用户。 # create_time 消息的发送时间,UNIX 时间戳 # type 消息的类型 if msg.type == 'text': if msg.content.startswith('#'): if msg.content[1:] == 'send': rt = requests.get('http://api.wowapi.org/faduanxin/') text = rt.text else: text = 'input error' elif msg.content in ['help', u'帮助']: text = default_text else: content = msg.content # 对应于 XML 中的 Content try: tmp = keyword_cache[msg.source] except: tmp = keyword_cache[msg.source] = {} chicken_flag = tmp.get('xiaohuangji', False) if u'小黄鸡' in content: text = '已进入小黄鸡聊天模式' tmp['xiaohuangji'] = True elif u'退出' in content: if chicken_flag: text = '已退出小黄鸡聊天模式...' tmp['xiaohuangji'] = False else: text = '发送“小黄鸡”来和TA对话!' elif content.startswith(u'查'): keywords = content[1:].encode('utf-8') if '附近' in keywords or '周边' in keywords or '周围' in keywords: tmp['keywords'] = keywords tmp['ktime'] = time.time() try: tmp = keyword_cache[msg.source] text0 = '已根据您历史位置通过高德地图API找到如下信息:\n\n' if time.time() - tmp['ltime'] < 60 * 15: addr_street = tmp['street'] addr_city = tmp['city'] text = amap_text_query(addr_street + keywords, text0, addr_city) else: text = '请重新发送您的地理位置!' except: text = '请发送您的地理位置!' else: text0 = '已通过高德地图API为您查找到 深圳 市内所有相关信息:\n\n' text = amap_text_query(keywords, text0) elif chicken_flag: text = chat_xhj(content) else: # text = robot(content, msg.source[:10]) #取消息来源前10位,因为不允许特殊符号 tl = robot(content, msg.source[:10], raw=True) # 判断消息类型 if tl['code']==100000: #文字 text = tl['text'] elif tl['code']==200000: #链接 text = tl['text']+'\n'+tl['url'] elif tl['code']==302000: #新闻 text = tl['text']+'\n\n' li = [] for i in tl['list']: di = { 'title': i['article'], 'image': request.url_root + 'static/netease_news.gif', 'url': i['detailurl'], } li.append(di) reply = ArticlesReply(message=msg, articles=li) return reply.render() elif tl['code']==308000: #菜谱 text = tl['text']+'\n\n' max_item = 5 for index,i in enumerate(tl['list']): if index < max_item: text = text + i['name'] + ':\n' + i['info'] + '\n' + i['detailurl'] if index < max_item-1: text += '\n\n' elif tl['code']==305000: #列车 text = tl['text']+'\n\n' lenth = len(tl['list']) for index,i in enumerate(tl['list']): text = text + i['trainnum'] + ':\n' + i['start'] + '-->' + i['terminal'] + '\n' + i['starttime'] + '--' + i['endtime'] if i['detailurl']: text += '\n' + i['detailurl'] if index < lenth-1: text += '\n\n' else: text = 'error' text = text.strip() reply = TextReply(content=text, message=msg) elif msg.type == 'event': if msg.event == 'subscribe': text0 = '小Q等您很久了,快来调戏我吧!回复【帮助】获取使用指南!' reply = create_reply(text0, msg) elif msg.type == 'location': locate = [msg.location_y, msg.location_x, msg.scale] # 经度,纬度,缩放 amap_regeo_api = 'http://restapi.amap.com/v3/geocode/regeo?' data = urllib.urlencode({ 'key': AMAP_KEY, 'location': ','.join(locate[:2]), 'radius': 2000, 'homeorcorp': 1, }) url = amap_regeo_api + data rt = requests.get(url) if rt.status_code == 200: rt_text = rt.text.encode('utf-8') js = json.loads(rt_text) addr_full = js['regeocode']['formatted_address'].encode('utf-8') addr_street = js['regeocode']['addressComponent']['streetNumber']['street'].encode('utf-8') addr_number = js['regeocode']['addressComponent']['streetNumber']['number'].encode('utf-8') addr_city = js['regeocode']['addressComponent']['city'].encode('utf-8') try: tmp = keyword_cache[msg.source] tmp['street'] = addr_street tmp['city'] = addr_city tmp['ltime'] = time.time() except: tmp = None if tmp and time.time() - tmp['ktime'] < 60 * 60: text0 = '已根据您位置通过高德地图API找到如下信息:\n\n' text = amap_text_query(addr_street + keyword_cache[msg.source]['keywords'], text0, addr_city) else: text = ','.join([addr_full, addr_street, addr_number]) else: text = ', '.join(locate) text = text.strip() reply = TextReply(content=text, message=msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render() else: # encryption mode crypto = WeChatCrypto(TOKEN, AES_KEY, APPID) try: decrypted_xml = crypto.decrypt_message(xml, msg_signature, timestamp, nonce) except (InvalidAppIdException, InvalidSignatureException): abort(403) msg = parse_message(decrypted_xml) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def check_signature(self, signature, timestamp, nonce): try: check_signature(self._wechat_conf.get("token", ""), signature, timestamp, nonce) except InvalidSignatureException: raise IVRError("Invalid signature", 400)