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(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) 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 else: # 接收消息 try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': # 文本消息 # reply = create_reply('点击下面的按钮进行操作!', msg).render() reply = text_action(msg) elif msg.type == 'event': # 按钮事件 reply = click_action(msg) else: reply = create_reply('暂时不支持的消息类型!', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) 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 else: try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def app_main(request): #获取要设置的微信 wx_name = request.args.get('wx') TOKEN = wx_conf[wx_name]['TOKEN'] EncodingAESKey = wx_conf[wx_name]['EncodingAESKey'] AppId = wx_conf[wx_name]['AppId'] signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, 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 else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': res = msg.content reply = create_reply(res, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def receive_msg(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) print(echo_str) print('Success') except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res except (InvalidSignatureException, InvalidCorpIdException): abort(403)
def do_POST(self): logging.info('POST request from %s', str(self.client_address)) self._set_response() params = parse_qs(urlparse(self.path).query) content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) try: msg_signature = params['msg_signature'][0] timestamp = params['timestamp'][0] nonce = params['nonce'][0] decrypted_xml = crypto.decrypt_message(post_data, msg_signature, timestamp, nonce) message = parse_message(decrypted_xml) reply_xml = None if message.type != 'text' and message.type != 'event': reply_xml = create_reply('不支持的消息类型', message).render() elif message.type == 'event' and message.event == 'click': if message.key == 'login_jd': if message.source not in qrcode_pending: reply_xml = create_reply('使用京东App扫描下方二维码登录(有效期3分钟)', message).render() if reply_xml: encrypted_xml = crypto.encrypt_message(reply_xml, nonce, timestamp) self.wfile.write(encrypted_xml.encode()) if message.type == 'event' and message.event == 'click': if message.key == 'login_jd': if message.source not in qrcode_pending: qrcode_pending.add(message.source) send_jd_qrcode(message.source) elif message.key == 'invite_link': send_invite_link(message.source) except InvalidSignatureException as e: logging.exception('Failed to process the POST request')
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) 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 else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = make_response(crypto.encrypt_message(reply, nonce, timestamp)) res.headers['Content-Type'] = 'application/xml' return res
def wechat(self, **args): signature = args.get('msg_signature', '') timestamp = args.get('timestamp', '') nonce = args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.httprequest.method == 'GET': echo_str = args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: reply = u'抱歉,签名解析失败' return echo_str else: try: msg = crypto.decrypt_message(request.httprequest.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): reply = u'抱歉,请求解析失败' msg = parse_message(msg) if msg.type == 'text': return_val = msg.content if re.match(r'^[D](\d){6}', msg.content, re.I): return_val = self.atuo_log_in(msg) reply = create_reply(return_val, msg).render() elif msg.type == 'event' and msg.event == 'scancode_waitmsg' and msg.scan_type == 'qrcode': reply = create_reply(self._login(msg)).render() elif msg.type == 'event' and msg.event == 'view': reply = create_reply(u'成功').render() else: reply = create_reply(u'不可以支持当前类型', msg).render() return crypto.encrypt_message(reply, nonce, timestamp)
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(Token, EncodingAESKey, corpid) 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) print(echo_str) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) user_name = msg.source if msg.type == 'text': message = msg.content rep = process_message(message) reply = create_reply(rep, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) print(res) return res
def process(self, request, code, msg_signature, timestamp, nonce, echostr=None): _logger.debug( 'WeChat Enterprise connected: code=%s, msg_signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, msg_signature, timestamp, nonce, echostr) request.uid = 1 application_obj = request.registry['wechat.enterprise.application'] application = application_obj.search(request.cr, request.uid, [('code', '=', code)], context=request.context) if not application: _logger.warning('Cant not find application.') abort(403) else: application = application_obj.browse(request.cr, request.uid, application[0], context=request.context) wechat_crypto = WeChatCrypto(application.token, application.ase_key, application.account.corp_id) if request.httprequest.method == 'GET': echo_str = '' try: echo_str = wechat_crypto.check_signature( msg_signature, timestamp, nonce, echostr) except InvalidSignatureException: _logger.warning('check_signature fail.') abort(403) return echo_str else: try: msg = wechat_crypto.decrypt_message(request.httprequest.data, msg_signature, timestamp, nonce) msg = parse_message(msg) reply_msg = application.process_request(msg)[0] if reply_msg: # if isinstance(reply_msg, list): # reply_msg = reply_msg[0] reply = create_reply(reply_msg, msg).render() return wechat_crypto.encrypt_message( reply, nonce, timestamp) else: _logger.info('reply None! msg= %s, reply_msg= %s', msg, reply_msg) return '' except (InvalidSignatureException, InvalidCorpIdException), e: _logger.warning('decrypt_message fail. %s', e) abort(403) except Exception, e: _logger.error('process_request error: %s', e) abort(403)
def process(self, request, code, msg_signature, timestamp, nonce, echostr=None): _logger.debug('WeChat Enterprise connected: code=%s, msg_signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, msg_signature, timestamp, nonce, echostr) request.uid = 1 application_obj = request.registry['odoosoft.wechat.enterprise.application'] application = application_obj.search(request.cr, request.uid, [('code', '=', code)], context=request.context) if not application: _logger.warning('Cant not find application.') abort(403) else: application = application_obj.browse(request.cr, request.uid, application[0], context=request.context) wechat_crypto = WeChatCrypto(application.token, application.ase_key, application.account.corp_id) if request.httprequest.method == 'GET': echo_str = '' try: echo_str = wechat_crypto.check_signature( msg_signature, timestamp, nonce, echostr ) except InvalidSignatureException: _logger.warning('check_signature fail.') abort(403) return echo_str else: try: msg = wechat_crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) msg = parse_message(msg) reply_msg = application.process_request(msg) if reply_msg: # if isinstance(reply_msg, list): # reply_msg = reply_msg[0] return wechat_crypto.encrypt_message(reply_msg.render(), nonce, timestamp) else: _logger.info('reply None! msg= %s', msg) return '' except (InvalidSignatureException, InvalidCorpIdException), e: _logger.warning('decrypt_message fail. %s', e) request.registry['odoosoft.wechat.enterprise.log'].log_info(request.cr, 1, u'过滤器', 'decrypt_message fail. %s' % e, context=request.context) return '' except Exception, e: _logger.error('process_request error: %s', e) request.registry['odoosoft.wechat.enterprise.log'].log_info(request.cr, 1, u'过滤器', 'process_request error: %s' % e, context=request.context) return ''
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = self.crypto.decrypt_message( {'Encrypt': echo_str}, msg_signature, timestamp, nonce ) except InvalidSignatureException: abort(403) return echo_str # POST msg = None try: msg = self.crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '>>> handle msg: %s %s %s'%(msg.type, msg.id, msg) _logger.info(ss) ret = '' if msg.type in ['text', 'image', 'voice', 'location']: #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) elif msg.type == 'unknown': data = msg._data if data.get('Event')=='open_approval_change': from .handlers.approval_handler import approval_handler approval_handler(request, msg) reply = create_reply(ret, msg).render() res = self.crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def test_parse_video_message(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[video]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('video', msg.type)
def test_parse_image_message(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[image]]></MsgType> <PicUrl><![CDATA[this is a url]]></PicUrl> <MediaId><![CDATA[media_id]]></MediaId> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('image', msg.type)
def test_parse_subscribe_event(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('event', msg.type) self.assertEqual('subscribe', msg.event)
def test_parse_text_message(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('text', msg.type) self.assertEqual(1, msg.agent)
def test_parse_unknown_message(self): from wechatpy.messages import UnknownMessage xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[notsure]]></MsgType> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertTrue(isinstance(msg, UnknownMessage))
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = self.crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str # POST msg = None try: msg = self.crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '------------------%s %s'%(msg.type, msg) _logger.info(ss) ret = '' if msg.type == 'text': #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg.content, msg.source) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) reply = create_reply(ret, msg).render() res = self.crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str # POST try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '------------------%s %s'%(msg.type, msg) _logger.info(ss) ret = '' if msg.type == 'text': #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg.content, msg.source) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) reply = create_reply(ret, msg).render() res = crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def test_parse_view_event(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[VIEW]]></Event> <EventKey><![CDATA[www.qq.com]]></EventKey> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('event', msg.type) self.assertEqual('view', msg.event) self.assertEqual('www.qq.com', msg.url)
def test_parse_click_event(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[CLICK]]></Event> <EventKey><![CDATA[EVENTKEY]]></EventKey> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('event', msg.type) self.assertEqual('click', msg.event) self.assertEqual('EVENTKEY', msg.key)
def test_parse_location_message(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[location]]></MsgType> <Location_X>23.134521</Location_X> <Location_Y>113.358803</Location_Y> <Scale>20</Scale> <Label><![CDATA[位置信息]]></Label> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('location', msg.type)
def test_parse_link_message(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[link]]></MsgType> <Title><![CDATA[公众平台官网链接]]></Title> <Description><![CDATA[公众平台官网链接]]></Description> <Url><![CDATA[url]]></Url> <PicUrl><![CDATA[picurl]]></PicUrl> <MsgId>1234567890123456</MsgId> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('link', msg.type)
def response_message(xml, request=None): msg = parse_message(xml) log.debug('>>> source:{},target:{}, msg.type:{}'.format( msg.source, msg.target, msg.type)) client = WeChatClient(APPID, SECRET) user_dict = client.user.get(msg.source) userpk = user_dict.get('email') or user_dict.get('userid') user = User.objects.filter(email=userpk).first() # client.message.send_text( msg.agent ,msg.source, 'user:{}'.format(user)) # log.debug('>>> user:{}'.format(user)) if msg.type == 'text': if re.match(r'.*(想)|(建议)', msg.content): Requirement.objects.get_or_create(email=userpk, content=msg.content) req_counts = Requirement.objects.filter(email=userpk).count() reply = TextReply(content='您的想法和建议我们已经收到({})'.format(req_counts), message=msg) return reply.render() content = '''现在我还不会聊天 但我会记录您提出的想法和建议 试着输入“...想...”或“...建议...” ''' reply = TextReply(content=content, message=msg) return reply.render() # log.debug('>>> response:{}'.format(response)) elif msg.type == 'event': log.debug('>>> msg.event:{}'.format(msg.event)) if msg.event == 'subscribe': return login_url(request, user_dict, client, userpk) if msg.event == 'location': log.debug('>>> msg:{}'.format(msg)) return add_location(user, msg.id, msg.latitude, msg.longitude, msg.precision) if msg.event == 'click': log.debug('>>> msg.key:{}'.format(msg.key)) if msg.key == 'login': return login_url(request, user_dict, client, userpk) elif msg.key == 'get_available_cars': return get_available_cars(user) elif msg.key == 'my_location_his': return get_location_his(user) elif msg.type == 'location': return add_location(user, msg.id, msg.location_x, msg.location_y, msg.scale, msg.label) reply = create_reply('') return reply.render()
def test_parse_location_event(self): xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[LOCATION]]></Event> <Latitude>23.137466</Latitude> <Longitude>113.352425</Longitude> <Precision>119.385040</Precision> <AgentID>1</AgentID> </xml>""" msg = parse_message(xml) self.assertEqual('event', msg.type) self.assertEqual('location', msg.event) self.assertEqual(23.137466, msg.latitude) self.assertEqual(113.352425, msg.longitude) self.assertEqual(119.385040, msg.precision)
def post(self, request, *args, **kwargs): reply = None print(request.body, 'post_request') msg = self.crypto.decrypt_message(request.body, **self.wx_data) # 判断消息类型,文本消息则调用reply_text进行处理 msg = parse_message(msg) self.orign_msg = msg print(msg, 'post_msg') if msg.type == 'text': # reply = self.reply_text.do_reply(msg) reply = self.reply_text() elif msg.type == 'event': reply = self.reply_event() # pass else: pass # if not reply or not isinstance(reply, BaseReply): # reply = create_reply('暂不支持您所发送的消息类型哟~ 回复“帮助”查看使用说明。', msg) response = self.crypto.encrypt_message(reply, self.wx_data['nonce'], self.wx_data['timestamp']) return HttpResponse(response)
def __app_weixin(request): from wechatpy.enterprise.crypto import WeChatCrypto from wechatpy.exceptions import InvalidSignatureException from wechatpy.enterprise.exceptions import InvalidCorpIdException from wechatpy.enterprise import parse_message, create_reply TOKEN=wx_conf[wx_name]['TOKEN'] EncodingAESKey=wx_conf[wx_name]['EncodingAESKey'] AppId=wx_conf[wx_name]['AppId'] signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, 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 else: try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) reply = create_reply(func(msg), msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.method == 'GET': try: echo_str = crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) # POST try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def api(request): # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('msg_signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') # 解析本次请求的 XML 数据 crypto = WeChatCrypto(settings.TOKEN, settings.ENCODINGAESKEY, settings.CORPID) if request.method == 'GET': # 检验合法性 echo_str = request.GET.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: # 处理异常情况或忽略 return HttpResponseBadRequest('Verify Failed') return HttpResponse(echo_str, content_type="text/plain") try: decrypted_xml = crypto.decrypt_message( request.body, signature, timestamp, nonce ) except (InvalidCorpIdException, InvalidSignatureException): # 处理异常或忽略 return HttpResponseBadRequest('Failed') msg = parse_message(decrypted_xml) response = EmptyReply() if msg.type == 'text': text = msg.content if text == 'info': userinfo = wechat_client.user.get(msg.source) response = TextReply(content=str(userinfo), message=msg) else: reply = Wechatkeyword.objects.extra(where=['%s SIMILAR TO keyword'], params=[text]).first() if reply: response = TextReply(content=u'%s' % reply.data, message=msg) elif msg.type == 'event': if msg.event == 'subscribe': # 关注事件 response = EmptyReply() elif msg.event == 'unsubscribe': logger.info('wechat user %s unsubscribe' % msg.source) user = User.objects.get(openid=msg.source) user.checkinaccountabnormal = True user.save() elif msg.event == 'location': nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) try: user = User.objects.get(openid=msg.source) except User.DoesNotExist: pass else: user.latitude = msg.latitude user.longitude = msg.longitude user.accuracy = msg.precision user.lastpositiontime = nowtime user.save() elif msg.event == 'click': if msg.key == '1200': response = TextReply(content=u'地址:%s\n学生默认帐号:学号/身份证号\n教师默认帐号:职工号/职工号' % settings.DOMAIN, message=msg) xml = response.render() encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp) return HttpResponse(encrypted_xml, content_type="application/xml")
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) 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 else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) user_name = msg.source help_message = """ 未识别的命令.目前已支持的命令为: !问题 : 获取当前存在的问题列表 !监控信息,[获取主机名]/[获取监控项]/ !监控信息,主机名(datanode01),监控项 ... """ if msg.type == 'text': message = msg.content if message == 'help': reply = create_reply(help_message, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res if message.find('!') == 0: #这里进入到命令匹配模式 if "!问题" in message or "!获取问题" in message: import time zabbix = ZabbixGraph() events = zabbix.get_cur_problems() evt_str = "\n".join([ "{:<20}{:<25}{}".format( e['eventid'], str( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int( e['clock'])))), e['name']) for e in events ]) reply = create_reply(evt_str, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res else: if "!监控信息" in message: zabbix = ZabbixGraph() message_list = message.split(',') if len(message_list) == 2: message_c = message_list[1] if "获取主机名" == message_c: hosts = zabbix.get_hosts() message = "\n".join(hosts) if "获取监控项" == message_c: hosts = zabbix.get_graphs(10257) message = "\n".join(hosts) elif len(message_list) == 3: hostname = message_list[1] item = message_list[2] hostids = zabbix.get_host_id(hostname) for h in hostids: gids = zabbix.get_graph_id(h, item) for gid in gids: values = {"graphid": gid} fpath = zabbix.GetGraph( values, config.TMP_DIR) print(fpath) with open(fpath, 'rb') as ff: resp = WeChatMedia( client=client).upload("image", ff) media_id = resp["media_id"] reply = ImageReply( media_id=media_id).render() res = crypto.encrypt_message( reply, nonce, timestamp) return res else: message = help_message reply = create_reply(message, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res else: rep = talks_robot(msg) reply = create_reply(rep, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res return ''