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 # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.data) replies.EmptyReply().render() reply = handler.handle_msg(msg, AppId, Secret) return reply.render() else: # encryption mode crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) reply = handler.handle_msg(msg, AppId, Secret) 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 echo_str # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.data) reply = msg_handler(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) reply = msg_handler(msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
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 wechatView(): TOKEN = current_app.config['TOKEN'] EncodingAESKey = current_app.config['EA'] AppId = current_app.config['APPID'] Raw = current_app.config['RAW'] 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: if Raw: 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) else: msg = request.data msg = parse_message(msg) print('request data:\n%s' % msg) if msg.type == 'text': if msg.content == 'ip': reply = create_reply(redis_store.get('pi_ip'), msg) else: reply = create_reply(msg.content, msg) elif msg.type == 'voice': reply = create_reply('voice msg', msg) else: reply = create_reply('Sorry, can not handle this for now', msg) if Raw: return crypto.encrypt_message(reply.render(), nonce, timestamp) else: return reply.render()
def wechat_check(): """微信服务器校验专用""" logger.debug('request values: %s' % request.values) logger.debug("request method: %s" % request.method) logger.debug(request.args) 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', '') logger.debug('signature: %s' % signature) logger.debug('timestamp: %s' % timestamp) logger.debug('nonce: %s' % nonce) logger.debug('echo_str: %s' % echo_str) logger.debug('encrypt_type: %s' % encrypt_type) logger.debug('msg_signature: %s' % msg_signature) try: check_signature(Config.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: logger.debug("check_signature FAILED!!!") abort(403) if request.method == 'GET': return echo_str else: openid = request.args.get('openid') logger.debug('openid: %s' % openid) if openid is None: logger.warn('wechat check NOT found openid!') return render_template('403.html') # print('Raw message: \n%s' % request.data) msg = None crypto = WeChatCrypto(Config.WECHAT_TOKEN, Config.WECHAT_AES_KEY, Config.WECHAT_APP_ID) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) # print('Decrypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(bot_reply(msg.content), msg) logger.debug('==msg.content: %s', msg.content) else: reply = create_reply('对不起,懵逼了,我该说啥???', msg) logger.debug("return wechat.") return crypto.encrypt_message(reply.render(), nonce, timestamp)
def _enterprise_wechat_required(method, *args, **kwargs): from wechatpy.enterprise import parse_message from wechatpy.enterprise.crypto import WeChatCrypto from wechatpy.enterprise.exceptions import InvalidCorpIdException signature = request.args.get('msg_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") crypto = WeChatCrypto( current_app.config['WECHAT_TOKEN'], current_app['WECHAT_AES_KEY'], current_app.config['WECHAT_APPID'] ) if request.method == 'GET': echo_str = request.args.get('echostr') try: echo_str = crypto.check_signature( signature, timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce, ) except (InvalidSignatureException, InvalidCorpIdException): return abort(403) else: request.wechat_msg = parse_message(msg) res = method(*args, **kwargs) xml = '' if isinstance(res, BaseReply): xml = res.render() 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 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 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 # POST request if encrypt_type == "raw": # plaintext mode msg = parse_message(request.data) if msg.type == "text": # reply = create_reply(msg.content, msg) str0 = msg.content; if str0[0] == '6': str0 += ".XSHG" else: str0 += ".XSHE" myq = query(jqdatasdk.valuation).filter(jqdatasdk.valuation.code == str0) df = jqdatasdk.get_fundamentals(myq, '2020-9-28') str1 = df['pe_ratio'] str2 = df['pb_ratio'] str4 = '%s ' % str1 str5 = '%s' % str2 str6 = str4 + str5 reply = create_reply(str6, 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(club_name): logger.debug(club_name) query = request.args logger.debug(query) signature = query.get("signature", "") timestamp = query.get("timestamp", "") nonce = query.get("nonce", "") logger.debug(request.args) try: check_signature(TOKEN, signature, timestamp, nonce) except Exception as e: logger.debug("invalid request!") abort(403) if request.method == "GET": return make_response(request.args.get("echostr", "")) else: logger.debug("start make response") encrypt_type = request.args.get("encrypt_type", "raw") xml = request.data msg = None if encrypt_type == "raw": # plain mode logger.debug("plain mode") msg = parse_message(xml) else: try: # encrypt mode crypto = WeChatCrypto(TOKEN, AES_KEY, APP_ID) msg = parse_message( crypto.decrypt_message(xml, signature, timestamp, nonce)) except Exception as e: abort(403) reply_xml = None if msg.type == "text": key_words = [item.strip() for item in str(msg.content).split(" ")] articles = app_controller.search_club_service_article( club_name, key_words) for article in articles: article["image"] = "{}{}".format(get_host(), article["image"]) article["url"] = "{}{}".format(get_host(), article["url"]) reply = ArticlesReply(articles=articles, message=msg) reply_xml = reply.render() else: reply = TextReply(content="Not supported!", message=msg) reply_xml = reply.render() logger.debug("xml:" + reply_xml) if encrypt_type == "raw": return reply_xml else: return crypto.encrypt_message(reply_xml, nonce, timestamp)
def wechat(): print(request.args) 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", "") is_test = request.args.get("test", False) try: if not is_test: check_signature(TOKEN, signature, timestamp, nonce) pass except InvalidSignatureException: abort(403) if request.method == "GET": print("got a get request") 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 == "text": # if "你是谁" in msg.content: # reply = create_reply("我是月光如水的夏夜,融化冰雪的深情", msg) # elif "我是鸣夏" in msg.content: # reply = create_reply("说啥都是爱你", msg) # else: # relpy_text = tuning_reply(msg.content) print(msg.content) relpy_text = task_controller(msg.content) reply = create_reply(relpy_text, msg) else: reply = create_reply(introduction, 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(introduction, msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
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 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', '') app.logger.debug( 'signature: %s\ntimestamp: %s\nnonce: %s\necho_str: %s\nencrypt_type: %s\nmsg_signature: %s\n' % (signature, timestamp, nonce, echo_str, encrypt_type, msg_signature)) try: check_signature(app.config["TOKEN"], signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: app.logger.debug('Raw message: \n%s' % request.data) crypto = WeChatCrypto(app.config["TOKEN"], app.config["ENCODINGAESKEY"], app.config["APPID"]) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) msg = msg.encode('UTF-8') app.logger.debug('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': if msg.source == app.config["ADMIN"]: msg.content = handle_admin_opt( msg.content, admin=True) # exec option and return result else: msg.content = handle_admin_opt( msg.content, wechatUser=msg.source, admin=False) # exec option and return result if msg.content is ALIPAY or msg.content is WECHATPAY: msg.content = IMAGE_URL[msg.content] reply = create_reply(msg.content, message=msg) elif msg.type == 'event' and msg.event == "subscribe": msg.content = user_help reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, I can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat(): try: 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(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST if encrypt_type != 'raw': crypto = WeChatCrypto(WECHAT_TOKEN, WECHAT_AES_KEY, WECHAT_APPID) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = request.data # BIZ msg = parse_message(msg) if msg.type == 'image': problem = process_image(msg.image) result_arthur, reverse = RANKER.do_rank_answers(problem) message = ' | '.join( ['%d-%s' % (r['count'], r['ans']) for r in result_arthur]) logging.info(message) reply = create_reply(message, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) # Render if encrypt_type != 'raw': return crypto.encrypt_message(reply.render(), nonce, timestamp) else: return reply.render() except Exception as e: import traceback traceback.print_exc()
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 # POST request if encrypt_type == 'raw': # plaintext mode 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() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(TOKEN, ENCODING_AES_KEY, APPID) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) app.logger.info(msg) if msg.type == 'text': result = fetchone_by_name(msg.content) if result: reply_msg = category.get(result, "知不道") else: reply_msg = "抱歉, Feed还小,不知道“{0}”是什么垃圾".format(msg.content) reply = create_reply(reply_msg, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) app.logger.info("test") return crypto.encrypt_message("".join(reply.render().split()), nonce, timestamp)
def wxdecrypt(request, appid, aescode, token): encrypt_type = request.GET.get('encrypt_type', None) xml = request.body if encrypt_type == 'aes': try: crypto = WeChatCrypto(token, aescode, appid) nonce = request.GET.get("nonce", None) timestamp = request.GET.get("timestamp", None) msgsignature = request.GET.get("msg_signature", None) return crypto.decrypt_message(xml, msgsignature, timestamp, nonce) except (InvalidAppIdException, InvalidSignatureException): error_msg = '亲,消息太复杂,解密我搞不定!' return error_msg else: return xml
def _enterprise_wechat_required(method, *args, **kwargs): from wechatpy.enterprise import parse_message from wechatpy.enterprise.crypto import WeChatCrypto from wechatpy.enterprise.exceptions import InvalidCorpIdException signature = request.args.get('msg_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") crypto = WeChatCrypto(current_app.config['WECHAT_TOKEN'], current_app['WECHAT_AES_KEY'], current_app.config['WECHAT_APPID']) if request.method == 'GET': echo_str = request.args.get('echostr') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce, ) except (InvalidSignatureException, InvalidCorpIdException): return abort(403) else: request.wechat_msg = parse_message(msg) res = method(*args, **kwargs) xml = '' if isinstance(res, BaseReply): xml = res.render() 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 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_http_message(self): ''' 或许WeChat响应体对象 :return: msg ''' crypto = WeChatCrypto(self.server_token, self.server_encoding_aes_key, self.app_id) try: decrypted_xml = crypto.decrypt_message(self.wei_xml, self.wei_msg_signature, self.wei_timestamp, self.wei_nonce) except (InvalidAppIdException, InvalidSignatureException): # 处理异常或忽略 return '' return parse_message(decrypted_xml)
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 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 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', '') 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 # POST request if encrypt_type == 'raw': # plaintext mode 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() 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)
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 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 wechat(): print('----------------start-----------------') 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', 'tttttttttttt') return echo_str # POST request if encrypt_type == 'raw': # plaintext mode 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() 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 parse(self, stream, content_type, content_length, context=None): data = stream.read() request = context['request'] encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') # In encryption mode if encrypt_type != 'raw': crypto = WeChatCrypto(config.TOKEN, config.ENCODING_AES_KEY, config.APP_ID) try: data = crypto.decrypt_message(data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): raise BadRequest() msg = parse_message(data) return msg
def post(self): # if self.encrypt_type == 'raw': # # plaintext mode # 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() # else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(self.TOKEN, self.AES_KEY, self.APPID) try: msg = crypto.decrypt_message(request.data, self.msg_signature, self.timestamp, self.nonce) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.content == "help": message = "help \t 帮助信息\t\n " \ + "hit \t 一言\t\n " \ + "bing \t 每日壁纸\t\n " \ + "? \t 有道翻译\t\n " reply = create_reply(message, msg) elif msg.content == "壁纸": pass elif msg.type == 'text': message = Tuling(current_app.config['TULING_APIKEY'], msg.content).create_reply() reply = create_reply(message, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), self.nonce, self.timestamp)
async def wechat_server(request: Request, msg_signature: str, timestamp: int, nonce: int, db: Session = Depends(get_db)): xml = await request.body() crypto = WeChatCrypto(wechat.token, wechat.encoding_aes_key, wechat.app_id) try: crypto_xml = crypto.decrypt_message(xml, msg_signature, timestamp, nonce) data = parse_message(crypto_xml) message = data.__dict__['_data'] if message["MsgType"] == 'event': res = type_event(db, message) elif message["MsgType"] == 'text': res = type_text() else: res = '' return responses.HTMLResponse(res) except (InvalidAppIdException, InvalidSignatureException): # 处理异常或忽略 pass return responses.HTMLResponse("")
def qrcode_process(content, TOKEN, signature, timestamp, nonce, encrypt_type, 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 # POST request if encrypt_type == 'raw': # plaintext mode 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() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(TOKEN, Config.wechat_mp_encodingaes_key, Config.wechat_appid_mp) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): return "" else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply(content, 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', '') 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: abort(403) if request.method == 'GET': return echo_str else: crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) reply = create_reply(rpl.reply(msg), msg) return crypto.encrypt_message( reply.render(), nonce, timestamp )
async def post(self, *args, **kwargs): signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') encrypt_type = self.get_argument('encrypt_type', 'raw') msg_signature = self.get_argument('msg_signature', '') try: check_signature(options.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: self.write_error(status_code=403) if encrypt_type == 'raw': msg = parse_message(self.request.body) if msg.type == 'text': reply_content = await handle_wechat_message(msg) reply = create_reply(reply_content, msg, render=True) else: reply = create_reply('暂时不支持该消息类型', msg, render=True) self.finish(reply) else: crypto = WeChatCrypto(options.TOKEN, options.AES_KEY, options.APPID) try: msg = crypto.decrypt_message( self.request.body, msg_signature, timestamp, nonce ) if msg.type == 'text': reply_content = await handle_wechat_message(msg) reply = create_reply(reply_content, msg, render=True) else: reply = create_reply('暂时不支持该消息类型', msg, render=True) self.finish(crypto.encrypt_message(reply, nonce, timestamp)) except (InvalidSignatureException, InvalidAppIdException): self.write_error(status_code=403)
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(f"Raw message: \n{request.data}") crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) print(f"Descypted message: \n{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 check_message(self, xml, data, is_encrypt=True): if is_encrypt: crypto = WeChatCrypto(self.token, self.aes_key, self.app_id) try: decrypted_xml = crypto.decrypt_message( xml, data.get("msg_signature"), data.get("timestamp"), data.get("nonce")) except (InvalidAppIdException, InvalidSignatureException): return None msg = parse_message(decrypted_xml) else: msg = parse_message(xml) re_xml = self.parse_msg(msg) if is_encrypt: return_xml = crypto.encrypt_message( re_xml, data.get("nonce"), data.get("timestamp")) else: return_xml = re_xml return return_xml
class WeChatComponent(BaseWeChatComponent): def create_preauthcode(self): """ 获取预授权码 """ return self.post( '/component/api_create_preauthcode', data={ 'component_appid': self.component_appid } ) def query_auth(self, authorization_code): """ 使用授权码换取公众号的授权信息 :params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明 """ return self.post( '/component/api_query_auth', data={ 'component_appid': self.component_appid, 'authorization_code': authorization_code } ) def refresh_authorizer_token( self, authorizer_appid, authorizer_refresh_token): """ 获取(刷新)授权公众号的令牌 :params authorizer_appid: 授权方appid :params authorizer_refresh_token: 授权方的刷新令牌 """ return self.post( '/component/api_authorizer_token', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'authorizer_refresh_token': authorizer_refresh_token } ) def get_authorizer_info(self, authorizer_appid): """ 获取授权方的账户信息 :params authorizer_appid: 授权方appid """ return self.post( '/component/api_get_authorizer_info', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, } ) def get_authorizer_option(self, authorizer_appid, option_name): """ 获取授权方的选项设置信息 :params authorizer_appid: 授权公众号appid :params option_name: 选项名称 """ return self.post( '/component/api_get_authorizer_option', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'option_name': option_name } ) def set_authorizer_option( self, authorizer_appid, option_name, option_value): """ 设置授权方的选项信息 :params authorizer_appid: 授权公众号appid :params option_name: 选项名称 :params option_value: 设置的选项值 """ return self.post( '/component/api_set_authorizer_option', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'option_name': option_name, 'option_value': option_value } ) def get_client_by(self, authorization_code): """ 通过授权码直接获取 Client 对象 :params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明 """ result = self.query_auth(authorization_code) access_token = result['authorization_info']['authorizer_access_token'] refresh_token = result['authorization_info']['authorizer_refresh_token'] # NOQA authorizer_appid = result['authorization_info']['authorizer_appid'] # noqa return WeChatComponentClient( authorizer_appid, self, access_token, refresh_token, session=self.session ) def get_client(self, authorizer_appid): """ 通过 authorizer_appid获取 Client 对象 :params authorizer_appid: 授权公众号appid """ access_token_key = '{0}_access_token'.format(authorizer_appid) refresh_token_key = '{0}_refresh_token'.format(authorizer_appid) access_token = self.session.get(access_token_key) refresh_token = self.session.get(refresh_token_key) if not access_token: ret = self.refresh_authorizer_token( authorizer_appid, refresh_token ) access_token = ret['authorizer_access_token'] refresh_token = ret['authorizer_refresh_token'] return WeChatComponentClient( authorizer_appid, self, access_token, refresh_token, session=self.session ) def set(self, token, encoding_aes_key): self.crypto = WeChatCrypto( token, encoding_aes_key, self.component_appid) def get_component_verify_ticket(self, msg, signature, timestamp, nonce): """ 处理 wechat server 推送的 component_verify_ticket消息 :params msg: 加密内容 :params signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数 """ content = self.crypto.decrypt_message(msg, signature, timestamp, nonce) message = xmltodict.parse(to_text(content))['xml'] return ComponentVerifyTicketMessage(message) def get_unauthorized(self, msg, signature, timestamp, nonce): """ 处理取消授权通知 :params msg: 加密内容 :params signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数 """ content = self.crypto.decrypt_message(msg, signature, timestamp, nonce) message = xmltodict.parse(to_text(content))['xml'] return ComponentUnauthorizedMessage(message)
class WeChatComponent(BaseWeChatComponent): def create_preauthcode(self): """ 获取预授权码 """ return self.post('/component/api_create_preauthcode', data={'component_appid': self.component_appid}) def query_auth(self, authorization_code): """ 使用授权码换取公众号的授权信息 :params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明 """ return self.post('/component/api_query_auth', data={ 'component_appid': self.component_appid, 'authorization_code': authorization_code }) def refresh_authorizer_token(self, authorizer_appid, authorizer_refresh_token): """ 获取(刷新)授权公众号的令牌 :params authorizer_appid: 授权方appid :params authorizer_refresh_token: 授权方的刷新令牌 """ return self.post('/component/api_authorizer_token', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'authorizer_refresh_token': authorizer_refresh_token }) def get_authorizer_info(self, authorizer_appid): """ 获取授权方的账户信息 :params authorizer_appid: 授权方appid """ return self.post('/component/api_get_authorizer_info', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, }) def get_authorizer_option(self, authorizer_appid, option_name): """ 获取授权方的选项设置信息 :params authorizer_appid: 授权公众号appid :params option_name: 选项名称 """ return self.post('/component/api_get_authorizer_option', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'option_name': option_name }) def set_authorizer_option(self, authorizer_appid, option_name, option_value): """ 设置授权方的选项信息 :params authorizer_appid: 授权公众号appid :params option_name: 选项名称 :params option_value: 设置的选项值 """ return self.post('/component/api_set_authorizer_option', data={ 'component_appid': self.component_appid, 'authorizer_appid': authorizer_appid, 'option_name': option_name, 'option_value': option_value }) def get_client_by(self, authorization_code): """ 通过授权码直接获取 Client 对象 :params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明 """ result = self.query_auth(authorization_code) access_token = result['authorization_info']['authorizer_access_token'] refresh_token = result['authorization_info'][ 'authorizer_refresh_token'] # NOQA authorizer_appid = result['authorization_info'][ 'authorizer_appid'] # noqa return WeChatComponentClient(authorizer_appid, self, access_token, refresh_token, session=self.session) def get_client(self, authorizer_appid): """ 通过 authorizer_appid获取 Client 对象 :params authorizer_appid: 授权公众号appid """ access_token_key = '{0}_access_token'.format(authorizer_appid) refresh_token_key = '{0}_refresh_token'.format(authorizer_appid) access_token = self.session.get(access_token_key) refresh_token = self.session.get(refresh_token_key) if not access_token: ret = self.refresh_authorizer_token(authorizer_appid, refresh_token) access_token = ret['authorizer_access_token'] refresh_token = ret['authorizer_refresh_token'] return WeChatComponentClient(authorizer_appid, self, access_token, refresh_token, session=self.session) def set(self, token, encoding_aes_key): self.crypto = WeChatCrypto(token, encoding_aes_key, self.component_appid) def get_component_verify_ticket(self, msg, signature, timestamp, nonce): """ 处理 wechat server 推送的 component_verify_ticket消息 :params msg: 加密内容 :params signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数 """ content = self.crypto.decrypt_message(msg, signature, timestamp, nonce) message = xmltodict.parse(to_text(content))['xml'] return ComponentVerifyTicketMessage(message) def get_unauthorized(self, msg, signature, timestamp, nonce): """ 处理取消授权通知 :params msg: 加密内容 :params signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数 """ content = self.crypto.decrypt_message(msg, signature, timestamp, nonce) message = xmltodict.parse(to_text(content))['xml'] return ComponentUnauthorizedMessage(message)
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)
msg = parse_message(data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply( _('Welcome to follow our WeChat Official Accounts'), msg) return fire_raw_content(reply.render(), 200, 'text/xml') else: # encryption mode from wechatpy.crypto import WeChatCrypto AES_KEY = frappe.get_value('Wechat App', app, 'aes_key') APP_ID = frappe.get_value('Wechat App', app, 'app_id') crypto = WeChatCrypto(TOKEN, AES_KEY, APP_ID) try: msg = crypto.decrypt_message(data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException), e: return fire_raw_content(e, 403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply( _('Welcome to follow our WeChat Official Accounts'), msg) #frappe.enqueue('wechat.api.create_wechat_menu', app_name=app) return fire_raw_content( crypto.encrypt_message(reply.render(), nonce, timestamp), 200, 'text/xml')
reload(sys) sys.setdefaultencoding( "utf-8" ) import requests import time from flask import Flask,request, make_response,render_template,jsonify,redirect import hashlib from wechatpy import parse_message from wechatpy.crypto import WeChatCrypto from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException crypto = WeChatCrypto(token, encoding_aes_key, appid) try: decrypted_xml = crypto.decrypt_message( xml, msg_signature, timestamp, nonce ) except (InvalidAppIdException, InvalidSignatureException): # 处理异常或忽略 pass msg = parse_message(decrypted_xml)
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)