def handler_event(self, jsonStr, cr, uid): #content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] #AgentID=jsonStr['AgentID'] eventType = jsonStr['Event'] create_time = jsonStr['CreateTime'] key = fromUser + create_time msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() env = Environment(http.request.cr, SUPERUSER_ID, http.request.context) if msgvalue == None: logging.info(u"服务号ID" + toUser) cache.redis.set(key, key, 5000) if eventType == "click": #点击事件; eventkey = jsonStr['EventKey'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] return env['receive_message'].process_clickkey( eventkey, jsonStr) #return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"Click") # elif eventType=="submit_membercard_user_info": #激活会员卡信息 # return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"submit_membercard_user_info") elif eventType == "subscribe": return env['receive_message'].process_clickkey( "default", jsonStr) else: return "" pass
def handler_location(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] locationX = jsonStr["Location_X"] locationY = jsonStr["Location_Y"] scale = jsonStr["Scale"] label = jsonStr["Label"] key = jsonStr['MsgId'] locationInfo = u"你发送的是位置,纬度为:" + locationX + u";经度为:" + locationY + u";缩放级别为:" + scale + u";位置为:" + label env = Environment(cr, uid, http.request.context) msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.location_message_record', jsonStr) return "" return ""
def handler_image(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() imageId = jsonStr["MediaId"] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) # env['ycloud.wx.message'].create_message('ycloud.wx.message_image', jsonStr) env['receive_message'].accept_message('wx.image_message_record', jsonStr) return "" return ""
def handler_shortvideo(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] thumbMediaId = jsonStr["ThumbMediaId"] mediaId = jsonStr["MediaId"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.video_message_record', jsonStr) return "" return ""
def handler_link(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] linktitle = jsonStr["Title"] linkdescription = jsonStr["Description"] linkurl = jsonStr["Url"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.link_message_record', jsonStr) return "" return ""
def handler_voice(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] recognitionInfo = "" if 'Recognition' in jsonStr: recognitionInfo = jsonStr["Recognition"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.voice_message_record', jsonStr) return "" return ""
def handler_text(self, jsonStr, cr, uid): fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] create_time = jsonStr['CreateTime'] msgId = jsonStr['MsgId'] key = msgId msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: _logger.debug(u"服务号ID" + toUser) context = http.request.context context.update({"openid": fromUser}) env = Environment(cr, uid, context) cache.redis.set(key, key, 5000) return env['receive_message'].accept_message( 'wx.message_text', jsonStr) else: return ""
def handler_text(self, jsonStr, wXBizMsgCrypt): content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] AgentID = jsonStr['AgentID'] msgId = jsonStr['MsgId'] key = msgId msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 5000) print content env = Environment(http.request.cr, SUPERUSER_ID, http.request.context) return env['receive_message'].accept_qy_message( 'wx.message_text', jsonStr, AgentID) else: return ""
def handler_text(self, jsonStr, cr, uid, wXBizMsgCrypt): content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] AgentID = jsonStr['AgentID'] msgId = jsonStr['MsgId'] key = msgId # mc=wx_public_sdk.getClient() msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 5000) print content env = Environment(cr, uid, http.request.context) # content=u"测试中心,测试教师" # result= messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), content) # return result return env['receive_message'].accept_qy_message( 'wx.message_text', jsonStr, AgentID) else: return ""
def handler_event(self, jsonStr, wXBizMsgCrypt, nonce, cr, context): eventType = jsonStr['Event'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] create_time = jsonStr['CreateTime'] key = fromUser + create_time msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: logging.info(u"服务号ID" + toUser) cache.redis.set(key, key, 5000) if eventType == "CLICK": #点击事件; env = Environment(cr, SUPERUSER_ID, http.request.context) eventkey = jsonStr['EventKey'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] if eventkey == "service": env['receive_message'].process_clickkey(eventkey, jsonStr) return env['send_message'].reply_service_message( fromUser, toUser) return env['receive_message'].process_clickkey( eventkey, jsonStr) #return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"Click") # elif eventType=="submit_membercard_user_info": #激活会员卡信息 # return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"submit_membercard_user_info") elif eventType == "subscribe": env = Environment(cr, SUPERUSER_ID, http.request.context) eventKey = jsonStr['EventKey'] eventKey = eventKey.replace('qrscene_', '') values = {} #必须传递的 values['openid'] = fromUser values['officialaccount_id'] = toUser #非必须 values['subscribe'] = True #不传则按False处理(True:关注;False:取消关注) values['key'] = eventKey #通过key值查找门店 wx_customer = env['wx.customer'].search([('openid', '=', fromUser)]) wx_userid = 0 if wx_customer: pass else: wx_customer_4subscribe = customer.wx_customer_4subscribe( cr, SUPERUSER_ID, http.request.context) wx_customer_4subscribe.create_wx_customer(values) cr.commit() return env['receive_message'].process_clickkey( "default", jsonStr) elif eventType == "card_merchant_auth_check_result": SubMerchantAppId = jsonStr['SubMerchantAppId'] IsPass = jsonStr['IsPass'] Reason = jsonStr['Reason'] result = "" if IsPass: result = "子商户:" + SubMerchantAppId + "审核通过" else: result = "子商户:" + SubMerchantAppId + "审核失败,原因为:" + Reason text = messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), result) text = wXBizMsgCrypt.EncryptMsg(text, nonce) return text[1] else: content = eventType + "from_callback" result = messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), content) text = wXBizMsgCrypt.EncryptMsg(result, nonce) print text return text[1] else: return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "")
def recevice_auth(self, **kw): env = Environment(request.cr, SUPERUSER_ID, request.context) data = http.request.httprequest.url # web.input() print "URL:" + data print http.request.httprequest.host if http.request.httprequest.method == 'GET': return str(1) timestamp = "" signature = "" nonce = "" echostr = "" result = data.split('?')[-1] for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "msg_signature": signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] data = http.request.httprequest.data print data xmldata = {} for el in etree.fromstring(data): xmldata[el.tag] = el.text appid = xmldata['AppId'] print "appid" + appid third_platform = env['wx.third_platform'].search([ ('auth_component_appid', '=', appid), ('auth_component_platfromtype', '=', 'openplatform') ]) auth_component_id = 0 if len(third_platform) == 0: symmetric_key = "essFuyMNenzJptkXq4MjZ6OTjnA4on7vdMaMrDmqy0I" appsercret = "d4624c36b6795d1d99dcf0547af5443d" token = "token" else: auth_component_id = third_platform[0]['id'] symmetric_key = third_platform[0][ 'auth_component_encodingasekey'] #"essFuyMNenzJptkXq4MjZ6OTjnA4on7vdMaMrDmqy0I" appsercret = third_platform[0][ 'auth_component_appsecret'] #"d4624c36b6795d1d99dcf0547af5443d" token = third_platform[0]['auth_component_token'] #"token" redirect_url = http.request.httprequest.host_url + "ycloud_base/authorize_complete/" + appid wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key, appid) decrypt_data = wXBizMsgCrypt.DecryptMsg(data, signature, timestamp, nonce) if decrypt_data[0] == 0: postdata = {} for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text print postdata if 'InfoType' in decrypt_data[1]: if postdata['InfoType'] == "unauthorized": appId = postdata['AppId'] print appId authorizerAppid = postdata['AuthorizerAppid'] print authorizerAppid createtime = postdata['CreateTime'] print u"公众号:" + authorizerAppid + u"取消授权" print createtime encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] elif postdata['InfoType'] == "authorized": appId = postdata['AppId'] print appId authorizerAppid = postdata['AuthorizerAppid'] createtime = postdata['CreateTime'] AuthorizationCode = postdata['AuthorizationCode'] publicsdk = public_sdk.public_sdk(appId, appsercret) key = appId + "ticket" ticket = cache.redis.get(key) print u'公众号' + authorizerAppid + "时间" + createtime + ",授权码" + AuthorizationCode + ",授权成功" authorizer_info = publicsdk.api_get_authorizer_info( authorizerAppid, ticket) print authorizer_info nick_name = authorizer_info['authorizer_info'][ 'nick_name'] #微信SDK Demo Special 服务号名称 user_name = authorizer_info['authorizer_info'][ 'user_name'] #gh_eb5e3a772040 print nick_name print user_name officialaccount = env['wx.officialaccount'].search([ ('wx_id', '=', user_name), ('is_auth_officialaccount', '=', True) ]) if len(officialaccount) == 0: data = {} data.update({ 'wx_id': user_name, 'wx_name': nick_name, 'wx_appid': authorizerAppid, 'is_auth_officialaccount': True, 'auth_component': auth_component_id }) print data try: create_result = env['wx.officialaccount'].create( data) _logger.debug(create_result) except Exception as e: _logger.error('创建服务号授权应用出错:' + str(e)) print e encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] elif postdata['InfoType'] == "updateauthorized": authorizerAppid = postdata['AuthorizerAppid'] createtime = postdata['CreateTime'] AuthorizationCode = postdata['AuthorizationCode'] print u'公众号' + authorizerAppid + "时间" + createtime + ",授权码" + AuthorizationCode + ",更新授权成功" #return 'success' encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] elif postdata['InfoType'] == "component_verify_ticket": ticket = postdata['ComponentVerifyTicket'] print ticket key = appid + "ticket" cache.redis.set(key, ticket, 600) publicsdk = public_sdk.public_sdk(appid, appsercret) token = publicsdk.get_api_component_token(ticket) print token authcode = publicsdk.get_api_create_preauthcode(ticket) print authcode url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" + appid + "&pre_auth_code=" + authcode + "&redirect_uri=" + redirect_url print url cache.redis.set("url", url, 600) encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] else: messageinfo = reply_information.reply_information() text = wXBizMsgCrypt.EncryptMsg( messageinfo.text_reply_xml(postdata['FromUserName'], postdata['ToUserName'], int(time.time()), u'test'), nonce) return text[1] else: print decrypt_data[0]
def message(self, **kw): env = Environment(request.cr, SUPERUSER_ID, request.context) print kw appid = kw['key'] print appid data = http.request.httprequest.data result = http.request.httprequest.url.split('?')[-1] msg_signature = "" timestamp = "" nonce = "" postdata = {} for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "msg_signature": msg_signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] print data token = "token" officialaccount = env['wx.officialaccount'].search([ ('wx_id', '=', appid), ('is_auth_officialaccount', '=', True) ]) if not officialaccount: symmetric_key = "essFuyMNenzJptkXq4MjZ6OTjnA4on7vdMaMrDmqy0I" component_appid = "wx8a79b1dd516ef8d7" component_sercret = "d4624c36b6795d1d99dcf0547af5443d" token = "token" else: symmetric_key = officialaccount[0]['auth_component'][ 'auth_component_encodingasekey'] #"essFuyMNenzJptkXq4MjZ6OTjnA4on7vdMaMrDmqy0I" component_appid = officialaccount[0]['auth_component'][ 'auth_component_appid'] #"wx8a79b1dd516ef8d7" component_sercret = officialaccount[0]['auth_component'][ 'auth_component_appsecret'] #d4624c36b6795d1d99dcf0547af5443d token = officialaccount[0]['auth_component'][ 'auth_component_token'] token = unquote(token) timestamp = unquote(timestamp) msg_signature = unquote(msg_signature) wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key, component_appid) decrypt_data = wXBizMsgCrypt.DecryptMsg(data, msg_signature, timestamp, nonce) print decrypt_data postdata = {} if decrypt_data[0] == 0: for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text msgType = postdata['MsgType'] fromUser = postdata['FromUserName'] toUser = postdata['ToUserName'] if msgType == "event": print '事件' return self.handler_event(postdata, wXBizMsgCrypt, nonce, request.cr, http.request.context) elif msgType == "text": msgId = postdata['MsgId'] key = msgId msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 5000) content = postdata['Content'] if content == "TESTCOMPONENT_MSG_TYPE_TEXT": messageinfo = reply_information.reply_information() text = messageinfo.text_reply_xml( postdata['FromUserName'], postdata['ToUserName'], int(time.time()), u'TESTCOMPONENT_MSG_TYPE_TEXT_callback') print text result = wXBizMsgCrypt.EncryptMsg(text, (nonce)) print result return result[1] elif content == "测试": messageinfo = reply_information.reply_information() reply_info = u"测试部门" print reply_info text = messageinfo.text_reply_xml(postdata['FromUserName'], postdata['ToUserName'], int(time.time()), reply_info) print text result = wXBizMsgCrypt.EncryptMsg(text.encode('utf-8'), (nonce)) print result return result[1] threaded_run = threading.Thread( target=self.handler_text, args=(postdata, request.cr, http.request.context, component_appid, appid, component_sercret, wXBizMsgCrypt, nonce)) threaded_run.start() return "" else: return "" elif msgType == "image": return self.handler_image(postdata, request.cr, http.request.context) elif msgType == "voice": return self.handler_voice(postdata, request.cr, http.request.context) elif msgType == "video": return self.handler_video(postdata, request.cr, http.request.context) elif msgType == "link": return self.handler_link(postdata, request.cr, http.request.context) elif msgType == "LOCATION": return self.handler_location(postdata, request.cr, http.request.context) elif msgType == "shortvideo": return self.handler_shortvideo(postdata, request.cr, http.request.context) else: messageinfo = reply_information.reply_information() return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), u"默认未实现")
def message(self, **kw): print http.request.httprequest.data print kw data = http.request.httprequest.data corpid = kw['key'] env = Environment(http.request.cr, SUPERUSER_ID, http.request.context) third_platform = env['wx.third_platform'].search([ ('auth_component_appid', '=', corpid), ('auth_component_platfromtype', '!=', 'openplatform') ]) if len(third_platform) == 0: symmetric_key = "qspRg9bhytjI28Jb1gpAj8YDg9JGWHq4LFfqfNumla6" appsercret = "UwUtt8En-jqhX-gd5tOrCC3Ym8_p0f54_vdIJ03H4tpn7gB7dEXGl2KXRCIVvwsc" token = "64XiwF2VE8OA9oJiTGwr9YcrKPIRef" if corpid == 'tjeaae807dcefd96c8': appsercret = "lok8-TQ1d3n1pUZW86nKiG-b3DUYHdAwGwnDPQj23U15I_iOxHhOi5HATn8GJvem" elif corpid == "tj0072de65cebdab77": appsercret = "SoJ4APxNnhpSlqcQ5u-lpnE_fUP0t2t_XfbMMr_eL-kEl-1v0sDfhn4kkdBDBF0D" else: symmetric_key = third_platform[0]['auth_component_encodingasekey'] appsercret = third_platform[0]['auth_component_appsecret'] token = third_platform[0]['auth_component_token'] print data print corpid result = http.request.httprequest.url.split('?')[-1] msg_signature = "" timestamp = "" nonce = "" postdata = {} for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "msg_signature": msg_signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] # token=unquote(token) # timestamp=unquote(timestamp) # msg_signature=unquote(msg_signature) # wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key,appid) # symmetric_key = "qspRg9bhytjI28Jb1gpAj8YDg9JGWHq4LFfqfNumla6" # appsercret = "UwUtt8En-jqhX-gd5tOrCC3Ym8_p0f54_vdIJ03H4tpn7gB7dEXGl2KXRCIVvwsc" # token = "64XiwF2VE8OA9oJiTGwr9YcrKPIRef" data = http.request.httprequest.data print data xmldata = {} for el in etree.fromstring(data): xmldata[el.tag] = el.text appid = xmldata['ToUserName'] # print "appid"+appid wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key, appid) decrypt_data = wXBizMsgCrypt.DecryptMsg(data, msg_signature, timestamp, nonce) print decrypt_data if decrypt_data[0] == 0: for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text print postdata msgType = postdata['MsgType'] fromUser = postdata['FromUserName'] toUser = postdata['ToUserName'] result = "" if msgType == "event": result = self.handler_event(postdata, wXBizMsgCrypt) elif msgType == "text": result = self.handler_text(postdata, wXBizMsgCrypt) # elif msgType == "image": # result= self.handler_image(postdata) # elif msgType == "voice": # result= self.handler_voice(postdata) # elif msgType == "video": # result= self.handler_video(postdata, cr, uid) # elif msgType == "link": # result= self.handler_link(postdata, cr, uid) # elif msgType == "location": # result= self.handler_location(postdata, cr, uid) # elif msgType == "shortvideo": # result= self.handler_shortvideo(postdata, cr, uid) else: messageinfo = reply_information.reply_information() content = u"默认未实现" result = messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), content) print result result = wXBizMsgCrypt.EncryptMsg(result.encode('utf-8'), (nonce)) print result return result[1] else: errcode = str(decrypt_data[0]) encrypt_data = wXBizMsgCrypt.EncryptMsg(errcode, nonce) print encrypt_data[1] return encrypt_data[1]
def execute_wx(self, cr, uid, data, cfg_apppartner): postdata = {} for el in etree.fromstring(data): postdata[el.tag] = el.text print http.request.httprequest.url print postdata is_encrypt = False msg_signature = "" timestamp = "" nonce = "" _logger.debug(json.dumps(postdata)) if 'encrypt_type' in http.request.httprequest.url: result = http.request.httprequest.url.split('?')[-1] encrypt_type = "" for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "encrypt_type": encrypt_type = keyvalues[1] elif keyvalues[0] == "msg_signature": msg_signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] if encrypt_type == "aes": env = Environment(cr, uid, http.request.context) is_encrypt = True token = cfg_apppartner['officalaccount']['wx_apptoken'] symmetric_key = cfg_apppartner['officalaccount'][ 'wx_encodingasekey'] wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt( token, symmetric_key, cfg_apppartner['officalaccount']['wx_appid']) decrypt_data = wXBizMsgCrypt.DecryptMsg( data, msg_signature, timestamp, nonce) print decrypt_data if decrypt_data[0] == 0: for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text else: errcode = str(decrypt_data[0]) messageinfo = reply_information.reply_information() messageinfo.text_reply_xml("", postdata['ToUserName'], int(time.time()), errcode) encrypt_data = wXBizMsgCrypt.EncryptMsg(errcode, nonce) print encrypt_data[1] return encrypt_data[1] msgType = postdata['MsgType'] fromUser = postdata['FromUserName'] toUser = postdata['ToUserName'] if msgType == "event": return self.handler_event(postdata, cr, uid) elif msgType == "text": return self.handler_text(postdata, cr, uid) elif msgType == "image": return self.handler_image(postdata, cr, uid) elif msgType == "voice": return self.handler_voice(postdata, cr, uid) elif msgType == "video": return self.handler_video(postdata, cr, uid) elif msgType == "link": return self.handler_link(postdata, cr, uid) elif msgType == "location": return self.handler_location(postdata, cr, uid) elif msgType == "shortvideo": return self.handler_shortvideo(postdata, cr, uid) else: messageinfo = reply_information.reply_information() return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), u"默认未实现")
def handler_event(self, jsonStr, cr, uid): eventType = jsonStr['Event'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] create_time = jsonStr['CreateTime'] key = fromUser + create_time # mc=wx_public_sdk.getClient() msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: logging.debug(u"服务号ID" + toUser) env = Environment(cr, uid, http.request.context) wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) # print "appid:" + wxOfficeAccountInfo["wx_appid"] # print "appsecret" + wxOfficeAccountInfo["wx_appsecret"] cache.redis.set(key, key, 50000) # mc.set(key,key,50) if eventType == "CLICK": # 点击事件; context = http.request.context context.update({"openid": fromUser}) env = Environment(cr, uid, context) eventkey = jsonStr['EventKey'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] if eventkey == "service": env['receive_message'].process_clickkey(eventkey, jsonStr) return env['send_message'].reply_service_message( fromUser, toUser) return env['receive_message'].process_clickkey( eventkey, jsonStr) # elif eventType == "submit_membercard_user_info": # 激活会员卡信息 # submitcard = ycloud_wx_submitusercard.ycloud_wx_submit_card_userinfo() # return submitcard.submit_membercard_user_info(cr, uid, jsonStr, wxOfficeAccountInfo) elif eventType == "subscribe": eventKey = jsonStr['EventKey'] eventKey = eventKey.replace('qrscene_', '') values = {} #必须传递的 values['openid'] = fromUser values['officialaccount_id'] = toUser #非必须 values['subscribe'] = True #不传则按False处理(True:关注;False:取消关注) values['key'] = eventKey #通过key值查找门店 #values['subscribe_time']='2015-12-22 20:35:20' #不传则按当前时间处理 # scanvalues={} # scanvalues['scene']="subscribe" # if eventKey=="": # values['subscribe_source']='manual' #(scan扫码关注;manual:手工关注) # else: # values['subscribe_source']='scan' # scanvalues['scancode_key']=eventKey # env = Environment(cr, uid, http.request.context) # qr_management = env['ycloud.qr.management'].search( # ['|', ('scene_str', '=', eventKey), ('scene_id', '=', int(eventKey) if eventKey.isdigit() else -1)]) # qr_models_values=[] # qr_key="" # if len(qr_management) > 0: # scanvalues['scene']=qr_management[0]['qr_scene'] # qr_key=qr_management[0]['qr_key'] # else: # qr_key=eventKey # scanvalues['openid']=fromUser # scanvalues['officialaccount_appid']=wxOfficeAccountInfo['wx_appid'] wx_customer = env['wx.customer'].search([('openid', '=', fromUser)]) wx_userid = 0 if wx_customer: pass else: wx_customer_4subscribe = customer.wx_customer_4subscribe( cr, uid, http.request.context) wx_customer_4subscribe.create_wx_customer(values) cr.commit() # def create_wx_customer(qr_key,eventKey,scanvalues,cr,uid,context,fromUser,toUser,wxOfficeAccountInfo): # dbname = cr.dbname # uid = uid # context = context.copy() # with api.Environment.manage(): # with registry(dbname).cursor() as new_cr: # context.update({ # "openid":fromUser # }) # new_env = Environment(new_cr, uid, context) # qr_management = new_env['ycloud.qr.management'].search(['|', ('scene_str', '=', eventKey), ('scene_id', '=', int(eventKey) if eventKey.isdigit() else -1)]) # qr_models_values=[] # if len(qr_management) > 0: # qr_models = qr_management[0]['qr_models'] # for qr_model in qr_models: # model_info=qr_model['model_id']['model'] # model_id_value=qr_model['model_id_value'] # model_column=qr_model['model_column']['name'] # orderinfo=new_env[model_info].search([(model_column,'=',model_id_value)])[0] # value={} # value.update({ # 'id':qr_model['model_id']['id'], # 'model_value':orderinfo # }) # qr_models_values.append(value) # if qr_key<>"": # if len(qr_models_values)==0: # _logger.info("无参考模型数据") # new_env['receive_message'].process_clickkey(qr_key,jsonStr) # else: # _logger.info("有参考模型数据") # new_env['ycloud.wx.message.send_event'].sendmessage_TriggeredbyCommand(qr_key,qr_models_values) # scancode_help=scancode.scancode(new_cr,uid,context) # scancode_help.create_scancode(scanvalues) # threaded_run = threading.Thread(target=create_wx_customer,args=(qr_key,eventKey,scanvalues,cr,uid,http.request.context,fromUser,toUser,wxOfficeAccountInfo)) # threaded_run.start() return env['receive_message'].process_clickkey( "default", jsonStr) # elif eventType == "WifiConnected": # WIFI链接成功 # mac = jsonStr['DeviceNo']#联网设备MAC # shop_id = jsonStr['ShopId'] # connectTime = jsonStr['ConnectTime'] # message = "用户:" + fromUser + "在门店ID:" + shop_id + "时间" + connectTime + "连网成功" # opendid=jsonStr['FromUserName'] # _logger.info("WIFI:"+message) # if self.userisadd(opendid): # #找到MAC对应的门店负责人: # qr=env['ycloud.qr.management'].search([('qr_mac','=',mac)]) # print qr # if qr: # store_open_id=qr[0]['o2o_store']['store_owner']['oauth_open_id'] # print store_open_id # if store_open_id: # eventKey="wifiConnected" # jsonStr.update({ # 'FromUserName':store_open_id # }) # env['receive_message'].process_clickkey(eventKey,jsonStr) # pass # return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "") # elif eventType == "card_pass_check": # 会员卡审核通过 # cardid = jsonStr['CardId'] # try: # env = Environment(cr, uid, http.request.context) # env['ycloud.wx.membership.line'].modify_wx_membership_line(cardid, 1) # except Exception as e: # _logger.error(e) # return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "") # elif eventType == "card_not_pass_check": # 会员卡审核失败 # cardid = jsonStr['CardId'] # try: # env = Environment(cr, uid, http.request.context) # env['ycloud.wx.membership.line'].modify_wx_membership_line(cardid, 0) # except Exception as e: # _logger.error(e) # return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "") # elif eventType == "user_get_card": # 用户领用卡劵时; # CardId = jsonStr["CardId"] # UserCardCode = jsonStr["UserCardCode"] # data = {} # data["openid"] = fromUser # data["officialaccount"] = wxOfficeAccountInfo['wx_official_account_id'] # data['cardid'] = CardId # data['cardcode'] = UserCardCode # try: # env = Environment(cr, uid, http.request.context) # create_result = env['ycloud.wx.membership'].create_wx_membership(data) # except Exception as e: # _logger.debug("创建会员卡记录失败:" + str(e)) # print e # return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "") elif eventType == "TEMPLATESENDJOBFINISH": time.sleep(10) MsgID = jsonStr['MsgID'] Status = jsonStr['Status'] messageStatus = "" if Status == "success": messageStatus = "use_sucess" elif Status == "failed:user block": messageStatus = "use_block" elif Status == "failed: system failed": messageStatus = "system_fail" try: cr.commit() env = Environment(cr, uid, http.request.context) messages = env['wx.notify_message_record'].search([ ('message_msgid', '=', MsgID) ]) data = {} data.update({'message_status': messageStatus}) print data messages[0].write(data) except Exception as e: _logger.debug("更新消息状态失败:" + str(e)) print e return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "") elif eventType == "SCAN": eventKey = jsonStr['EventKey'] print eventKey def scanbarcode(eventKey, cr, uid, context, fromUser, wxOfficeAccountInfo): dbname = cr.dbname uid = uid context = context.copy() with api.Environment.manage(): with registry(dbname).cursor() as new_cr: context.update({"openid": fromUser}) new_env = Environment(new_cr, uid, context) # scanvalues={} # scanvalues['scene']="subscribe" # scanvalues['scancode_key']=eventKey # qr_management = new_env['ycloud.qr.management'].search(['|', ('scene_str', '=', eventKey), ('scene_id', '=', int(eventKey) if eventKey.isdigit() else -1)]) # if len(qr_management) > 0: # scanvalues['scene']=qr_management[0]['qr_scene'] # print scanvalues['scene'] # scanvalues['openid']=fromUser # scanvalues['officialaccount_appid']=wxOfficeAccountInfo['wx_appid'] # scancode_help=scancode.scancode(new_cr,uid,context) # scancode_help.create_scancode(scanvalues) # qr_key=qr_management[0]['qr_key'] # qr_models = qr_management[0]['qr_models'] qr_key = eventKey qr_models_values = [] # for qr_model in qr_models: # model_info=qr_model['model_id']['model'] # model_id_value=qr_model['model_id_value'] # model_column=qr_model['model_column']['name'] # orderinfo=new_env[model_info].search([(model_column,'=',model_id_value)])[0] # value={} # value.update({ # 'id':qr_model['model_id']['id'], # 'model_value':orderinfo # }) # qr_models_values.append(value) #currentContext={} if len(qr_models_values) == 0: new_env['receive_message'].process_clickkey( qr_key, jsonStr) else: new_env[ 'wx.message.send_event'].sendmessage_TriggeredbyCommand( qr_key, qr_models_values) threaded_run = threading.Thread( target=scanbarcode, args=(eventKey, cr, uid, http.request.context, fromUser, wxOfficeAccountInfo)) threaded_run.start() return "" # elif eventType=="user_pay_from_pay_cell":#用户使用会员卡买单功能 # CardId=jsonStr['CardId'] # UserCardCode=jsonStr['UserCardCode'] # TransId=jsonStr['TransId'] # LocationId="" # if 'LocationId' in jsonStr: # LocationId=jsonStr['LocationId'] # LocationName="" # if 'LocationName' in jsonStr: # LocationName=jsonStr['LocationName'] # Fee=jsonStr['Fee'] # OriginalFee=jsonStr['OriginalFee'] # add_bonus=((int)(Fee)*100) # record_bonus="消费"+Fee+"元,获得"+str(add_bonus)+"积分" # add_balance=0 # record_balance=0 # message = "用户:" + fromUser + "在门店ID:" + LocationId + ",门店名称:" + LocationName + "使用卡劵"+UserCardCode+",实付金额:"+Fee # print message # cardManager = card_manager.card_manager(wxOfficeAccountInfo['wx_appid'], # wxOfficeAccountInfo['wx_appsecret']) # cardManager.update_member_card_bonus_info(UserCardCode,CardId,add_bonus,record_bonus,add_balance,record_balance) # return "" elif eventType == "unsubscribe": wx_customer_4subscribe = customer.wx_customer_4subscribe( cr, uid, http.request.context) values = {} #必须传递的 values['openid'] = fromUser values['officialaccount_id'] = toUser #非必须 values['subscribe'] = False #不传则按False处理(True:关注;False:取消关注) wx_customer_4subscribe.create_wx_customer(values) return "" # elif eventType == "merchant_order": # OrderId = jsonStr['OrderId'] # ProductId = jsonStr['ProductId'] # try: # context=http.request.context # openid = jsonStr['FromUserName'] # #currentContext={} # context.update({ # "openid":openid # }) # env = Environment(cr, uid, context) # oe_order = env['ycloud.wx.syncrecord'].create_record(OrderId, ProductId, wxOfficeAccountInfo) # if oe_order <> False: # print oe_order['name'] # message_key = "merchant_order" # model_instances=[] # model_instance={} # model = env['ir.model'].search([('model', '=', 'sale.order')])[0] # model_instance.update({ # "id":model['id'], # "model_value":oe_order # }) # # model_instances.append(model_instance) # env['ycloud.wx.message.send_event'].sendmessage_TriggeredbyCommand(message_key,model_instances) # except Exception as e: # _logger.debug("小店下单事件出错:" + str(e)) # print e # return "" else: return "" else: return messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), "")
def access_qy_auth(self, **kw): env = Environment(request.cr, SUPERUSER_ID, request.context) data = http.request.httprequest.url # web.input() print "URL:" + data print http.request.httprequest.host if http.request.httprequest.method == 'GET': return str(1) timestamp = "" signature = "" nonce = "" echostr = "" result = data.split('?')[-1] for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "msg_signature": signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] # appid="" data = http.request.httprequest.data print data xmldata = {} for el in etree.fromstring(data): xmldata[el.tag] = el.text appid = xmldata['ToUserName'] third_platform = env['wx.third_platform'].search([ ('auth_component_appid', '=', appid), ('auth_component_platfromtype', '!=', 'openplatform') ]) if len(third_platform) == 0: symmetric_key = "qspRg9bhytjI28Jb1gpAj8YDg9JGWHq4LFfqfNumla6" appsercret = "UwUtt8En-jqhX-gd5tOrCC3Ym8_p0f54_vdIJ03H4tpn7gB7dEXGl2KXRCIVvwsc" token = "64XiwF2VE8OA9oJiTGwr9YcrKPIRef" if appid == 'tjeaae807dcefd96c8': appsercret = "lok8-TQ1d3n1pUZW86nKiG-b3DUYHdAwGwnDPQj23U15I_iOxHhOi5HATn8GJvem" elif appid == "tj0072de65cebdab77": appsercret = "SoJ4APxNnhpSlqcQ5u-lpnE_fUP0t2t_XfbMMr_eL-kEl-1v0sDfhn4kkdBDBF0D" else: symmetric_key = third_platform[0]['auth_component_encodingasekey'] appsercret = third_platform[0]['auth_component_appsecret'] token = third_platform[0]['auth_component_token'] # symmetric_key = "qspRg9bhytjI28Jb1gpAj8YDg9JGWHq4LFfqfNumla6" # # appsercret = "UwUtt8En-jqhX-gd5tOrCC3Ym8_p0f54_vdIJ03H4tpn7gB7dEXGl2KXRCIVvwsc" # token = "64XiwF2VE8OA9oJiTGwr9YcrKPIRef" # # if appid == 'tjeaae807dcefd96c8': # appsercret = "lok8-TQ1d3n1pUZW86nKiG-b3DUYHdAwGwnDPQj23U15I_iOxHhOi5HATn8GJvem" # elif appid=="tj0072de65cebdab77": # appsercret="SoJ4APxNnhpSlqcQ5u-lpnE_fUP0t2t_XfbMMr_eL-kEl-1v0sDfhn4kkdBDBF0D" # print "appid"+appid redirect_url = http.request.httprequest.host_url + "ycloud_base/qy_auth/" + appid wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key, appid) decrypt_data = wXBizMsgCrypt.DecryptMsg(data, signature, timestamp, nonce) if decrypt_data[0] == 0: postdata = {} for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text print postdata if 'InfoType' in decrypt_data[1]: if postdata['InfoType'] == "cancel_auth": appId = postdata['SuiteId'] print appId authorizerAppid = postdata['AuthCorpId'] print authorizerAppid createtime = postdata['TimeStamp'] print u"企业号:" + authorizerAppid + u"取消授权" print createtime # return 'sucess' encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] elif postdata['InfoType'] == "change_auth": authorizerAppid = postdata['AuthCorpId'] createtime = postdata['TimeStamp'] SuiteId = postdata['SuiteId'] print u'企业号号' + authorizerAppid + "时间" + createtime + ",在套件" + SuiteId + ",变更授权" # return 'success' encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] elif postdata['InfoType'] == "suite_ticket": ticket = postdata['SuiteTicket'] SuiteId = postdata['SuiteId'] print ticket key = appid + "ticket" print appid cache.redis.set(key, ticket, 600) suite_access_token = qy_open_public_sdk.get_suite_token( SuiteId, appsercret, ticket) pre_auth_code = qy_open_public_sdk.get_pre_auth_code( SuiteId, suite_access_token) print pre_auth_code baseurl = "https://qy.weixin.qq.com/cgi-bin/loginpage?suite_id=" + SuiteId + "&pre_auth_code=" + pre_auth_code + "&redirect_uri=" + redirect_url + "&state=state" print baseurl timestamp = int(time.time()) redirect_login_url = http.request.httprequest.host_url + "ycloud_base/auth_login" authurl = "https://qy.weixin.qq.com/cgi-bin/loginpage?corp_id=" + appid + "&redirect_uri=" + redirect_login_url + "&state=" + str( timestamp) + "&usertype=admin" cache.redis.set("baseurl" + SuiteId, baseurl, 600) cache.redis.set('authurl', authurl, 600) encrypt_data = wXBizMsgCrypt.EncryptMsg('success', nonce) return encrypt_data[1] else: messageinfo = reply_information.reply_information() text = wXBizMsgCrypt.EncryptMsg( messageinfo.text_reply_xml(postdata['FromUserName'], postdata['ToUserName'], int(time.time()), u'test'), nonce) return text[1] else: print decrypt_data[0]
def execute_wx_qy(self, cr, uid, data, cfg_apppartner): print data print cfg_apppartner result = http.request.httprequest.url.split('?')[-1] msg_signature = "" timestamp = "" nonce = "" postdata = {} for key_value in result.split('&'): keyvalues = key_value.split('=') if keyvalues[0] == "msg_signature": msg_signature = keyvalues[1] elif keyvalues[0] == "timestamp": timestamp = keyvalues[1] elif keyvalues[0] == "nonce": nonce = keyvalues[1] elif keyvalues[0] == "echostr": echostr = keyvalues[1] token = cfg_apppartner['enterpriseaccount']['wx_apptoken'] symmetric_key = cfg_apppartner['enterpriseaccount'][ 'wx_encodingasekey'] appid = cfg_apppartner['enterpriseaccount']['wx_appid'] token = unquote(token) timestamp = unquote(timestamp) msg_signature = unquote(msg_signature) wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key, appid) decrypt_data = wXBizMsgCrypt.DecryptMsg(data, msg_signature, timestamp, nonce) if decrypt_data[0] == 0: for el in etree.fromstring(decrypt_data[1]): postdata[el.tag] = el.text print postdata msgType = postdata['MsgType'] fromUser = postdata['FromUserName'] toUser = postdata['ToUserName'] result = "" if msgType == "event": result = self.handler_event(postdata, cr, uid) elif msgType == "text": result = self.handler_text(postdata, cr, uid, wXBizMsgCrypt) elif msgType == "image": result = self.handler_image(postdata, cr, uid) elif msgType == "voice": result = self.handler_voice(postdata, cr, uid) elif msgType == "video": result = self.handler_video(postdata, cr, uid) elif msgType == "link": result = self.handler_link(postdata, cr, uid) elif msgType == "location": result = self.handler_location(postdata, cr, uid) elif msgType == "shortvideo": result = self.handler_shortvideo(postdata, cr, uid) else: messageinfo = reply_information.reply_information() content = u"默认未实现" result = messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), content) result = wXBizMsgCrypt.EncryptMsg(result.encode('utf-8'), (nonce)) print result return result[1] else: errcode = str(decrypt_data[0]) encrypt_data = wXBizMsgCrypt.EncryptMsg(errcode, nonce) print encrypt_data[1] return encrypt_data[1] pass
def send_text_message(self): text_message_record = self if text_message_record['message_event'] == "receive": raise except_osv(_('Error!'), _("请创建消息事件类型为发的消息进行发送")) print text_message_record['officialaccount'] if text_message_record['message_status'] <> "approved": raise except_osv(_('Error!'), _("未审核通过记录不允许发送")) if text_message_record['officialaccount']['id'] == False: raise except_osv(_('Error!'), _("请维护对应的服务号或企业号应用信息")) if text_message_record['officialaccount']['is_qyhapp'] == False: if text_message_record['toUserName']['openid'] == False: raise except_osv(_('Error!'), _("请维护接收方信息")) print '服务号' openid = text_message_record['toUserName']['openid'] template_code = text_message_record['message_template'][ 'template_code'] wxOfficeAccountInfo = text_message_record['officialaccount'] order = text_message_record['association_order'] model_entity_name = text_message_record['message_template'][ 'model_id']['model'] if order == False: messageinfo = reply_information.reply_information() print wxOfficeAccountInfo['wx_official_account_id'] messagelist = messageinfo.text_reply_xml( openid, wxOfficeAccountInfo['wx_official_account_id'], int(time.time()), text_message_record['message_template']['message_content']) self.env['send_message'].sendcustommessage(messagelist) self.env['send_message'].insert_text_record( openid, wxOfficeAccountInfo, self.env, text_message_record['message_template']['message_content'], text_message_record['message_template'], "", False, "", "sending", "send") return order_jsons = json.loads(order) model_values = [] for orderinfo in order_jsons: value = self.env[model_entity_name].search([ ('id', '=', orderinfo['id']) ])[0] model_value = {} model_value.update({ "id": text_message_record['message_template']['model_id']['id'], "model_value": value }) model_values.append(model_value) self.env['send_message'].send_text_message(template_code, model_values, openid, wxOfficeAccountInfo) else: print '企业号' userid = text_message_record['qy_toUserName']['user_id']['login'] if userid == False: raise except_osv(_('Error!'), _("请维护企业应用接收方信息")) template_code = text_message_record['message_template'][ 'template_code'] wxOfficeAccountInfo = text_message_record['officialaccount'] order = text_message_record['association_order'] model_entity_name = text_message_record['message_template'][ 'model_id']['model'] if order == False: messageinfo = reply_information.reply_information() print wxOfficeAccountInfo['wx_appid'] messagelist = messageinfo.text_reply_xml( userid, wxOfficeAccountInfo['wx_appid'], int(time.time()), text_message_record['message_template']['message_content']) self.env['send_message'].send_qy_custommessage( messagelist, wxOfficeAccountInfo['wx_qyh_app_id']) self.env['send_message'].insert_qy_text_record( userid, wxOfficeAccountInfo, self.env, text_message_record['message_template']['message_content'], text_message_record['message_template'], "", False, "", "sending", "send") return order_jsons = json.loads(order) model_values = [] for orderinfo in order_jsons: value = self.env[model_entity_name].search([ ('id', '=', orderinfo['id']) ])[0] model_value = {} model_value.update({ "id": text_message_record['message_template']['model_id']['id'], "model_value": value }) model_values.append(model_value) self.env['send_message'].send_qy_text_message( template_code, model_values, userid, wxOfficeAccountInfo) pass