Beispiel #1
0
 def check_server_valid(self, request, cfg_apppartner):
     postdata = {}
     data = request.url  # web.input()
     print "URL:" + data
     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]
     # 自己的token
     token = cfg_apppartner['enterpriseaccount']['wx_apptoken']
     symmetric_key = cfg_apppartner['enterpriseaccount'][
         'wx_encodingasekey']
     appid = cfg_apppartner['enterpriseaccount'][
         'wx_appid']  # 这里改写你在微信公众平台里输入的token
     token = unquote(token)
     timestamp = unquote(timestamp)
     echostr = unquote(echostr)
     signature = unquote(signature)
     print "token:" + token
     print "timestamp:" + timestamp
     print "nonce:" + nonce
     print "msg_signature:" + signature
     print 'echostr:' + echostr
     #symmetric_key = cfg_apppartner['encodingAESKey']#"N2UAlci4D2WX3xyf6mWdsdCv2T3tIDB4wdNxlDVhuon"
     #appid=cfg_apppartner['appid']#"wxe28ca91a338a7638"
     wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key,
                                                 appid)
     decrypt_data = wXBizMsgCrypt.VerifyURL(signature, timestamp, nonce,
                                            echostr)
     print decrypt_data
     if decrypt_data[0] == 0:
         sReplyEchoStr = decrypt_data[1]
         print sReplyEchoStr
         return sReplyEchoStr
     else:
         errcode = str(decrypt_data[0])
         print errcode
     pass
Beispiel #2
0
 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]
Beispiel #3
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"默认未实现")
Beispiel #4
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
Beispiel #5
0
 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"默认未实现")
Beispiel #6
0
    def wechat(self, **kw):
        env = Environment(http.request.cr, SUPERUSER_ID, http.request.context)
        data = http.request.httprequest.data
        print kw
        print 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]
        # token=unquote(token)
        # timestamp=unquote(timestamp)
        # msg_signature=unquote(msg_signature)
        # wXBizMsgCrypt = WXBizMsgCrypt.WXBizMsgCrypt(token, symmetric_key,appid)
        suiteId = 'tjeaae807dcefd96c8'
        symmetric_key = "qspRg9bhytjI28Jb1gpAj8YDg9JGWHq4LFfqfNumla6"
        appsercret = "lok8-TQ1d3n1pUZW86nKiG-b3DUYHdAwGwnDPQj23U15I_iOxHhOi5HATn8GJvem"
        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:
            postdata = xmltodict.parse((decrypt_data[1]))['xml']
            # for el in etree.fromstring(decrypt_data[1]):
            #     postdata[el.tag] = el.text
            print postdata
            ItemCount = postdata['ItemCount']
            print ItemCount
            PackageId = postdata['PackageId']
            print PackageId
            Items = postdata['Item']
            print Items
            result = PackageId
            if 'AgentType' in postdata:
                count = (int)(ItemCount)
                if count == 1:
                    print postdata['Item']
                    MsgType = postdata['Item']['MsgType']
                    print MsgType
                    if MsgType == "event":
                        print postdata['Item']
                        pass
                    elif MsgType == "text":
                        FromUserName = postdata['Item']['FromUserName']
                        content2 = postdata['Item']['Content']
                        print FromUserName
                        Receiver_type = postdata['Item']['Receiver']['Type']
                        print Receiver_type
                        Receiver_ID = postdata['Item']['Receiver']['Id']
                        print Receiver_ID
                        MsgId = postdata['Item']['MsgId']
                        content = FromUserName + "说话的" + "文本消息内容是:" + content2 + "|" + str(
                            int(time.time()))
                        key = suiteId + "suite_access_token"
                        suite_access_token = cache.redis.get(key)
                        third_platform = env['wx.third_platform'].search([
                            ('auth_component_appid', '=', suiteId)
                        ])
                        officialaccount = env['wx.officialaccount'].search([
                            ('wx_appid', '=', appid),
                            ('auth_component', '=', third_platform.id),
                            ('third_auth_id', '=', 1)
                        ])
                        text_template = {}
                        text_template.update({"id": ""})
                        try:
                            env['send_message'].insert_qy_text_record(
                                FromUserName, officialaccount, env, content,
                                text_template, "", False, "", "sending",
                                "send")
                        except Exception as e:
                            _logger.info("插入文本消息记录出错:" + str(e))
                        corp_access_token = qy_open_public_sdk.get_corp_access_token(
                            suite_access_token, suiteId, appid,
                            officialaccount['third_auth_code'])
                        print corp_access_token
                        send_user = '******'
                        receiver_type = 'group'
                        receiver_id = '9223372036864775811'
                        session_result = qy_open_public_sdk.send_text_session(
                            corp_access_token, send_user, content,
                            receiver_type, receiver_id)
                        print session_result
                    elif MsgType == "image":
                        FromUserName = postdata['Item']['FromUserName']
                        MediaId = postdata['Item']['MediaId']
                        PicUrl = postdata['Item']['PicUrl']
                        print FromUserName
                        Receiver_type = postdata['Item']['Receiver']['Type']
                        print Receiver_type
                        Receiver_ID = postdata['Item']['Receiver']['Id']
                        print Receiver_ID
                        # content =FromUserName+"说话的"+ "文本消息内容是:"+content2+"|" + str(int(time.time()))
                        content = FromUserName + "发送的图片地址为:" + PicUrl
                        key = suiteId + "suite_access_token"
                        suite_access_token = cache.redis.get(key)
                        officialaccount = env['wx.officialaccount'].search([
                            ('wx_appid', '=', appid),
                            ('third_auth_SuiteId', '=', suiteId),
                            ('third_auth_id', '=', 1)
                        ])
                        corp_access_token = qy_open_public_sdk.get_corp_access_token(
                            suite_access_token, suiteId, appid,
                            officialaccount['third_auth_code'])
                        print corp_access_token
                        send_user = '******'
                        receiver_type = 'group'
                        receiver_id = '9223372036864775811'
                        session_result = qy_open_public_sdk.send_text_session(
                            corp_access_token, send_user, content,
                            receiver_type, receiver_id)
                        print session_result
                        session_image_result = qy_open_public_sdk.send_image_session(
                            corp_access_token, send_user, MediaId,
                            receiver_type, receiver_id)
                        print session_image_result
                    elif MsgType == "voice":
                        FromUserName = postdata['Item']['FromUserName']
                        MediaId = postdata['Item']['MediaId']

                        print FromUserName
                        Receiver_type = postdata['Item']['Receiver']['Type']
                        print Receiver_type
                        Receiver_ID = postdata['Item']['Receiver']['Id']
                        print Receiver_ID
                        # content =FromUserName+"说话的"+ "文本消息内容是:"+content2+"|" + str(int(time.time()))
                        content = FromUserName + "发送的是语音。。。"
                        key = suiteId + "suite_access_token"
                        suite_access_token = cache.redis.get(key)
                        officialaccount = env['wx.officialaccount'].search([
                            ('wx_appid', '=', appid),
                            ('third_auth_SuiteId', '=', suiteId),
                            ('third_auth_id', '=', 1)
                        ])
                        corp_access_token = qy_open_public_sdk.get_corp_access_token(
                            suite_access_token, suiteId, appid,
                            officialaccount['third_auth_code'])
                        print corp_access_token
                        send_user = '******'
                        receiver_type = 'group'
                        receiver_id = '9223372036864775811'
                        session_result = qy_open_public_sdk.send_text_session(
                            corp_access_token, send_user, content,
                            receiver_type, receiver_id)
                        print session_result
                        session_image_result = qy_open_public_sdk.send_voice_session(
                            corp_access_token, send_user, MediaId,
                            receiver_type, receiver_id)
                        print session_image_result
                else:
                    for i in range(count):
                        print postdata['Item'][i]
                        MsgType = postdata['Item'][i]['MsgType']
                        print MsgType
                        if MsgType == "event":
                            print postdata['Item'][i]
                            pass
                        elif MsgType == "text":
                            FromUserName = postdata['Item'][i]['FromUserName']
                            print FromUserName
                            content2 = postdata['Item']['Content']
                            Receiver_type = postdata['Item'][i]['Receiver'][
                                'Type']
                            print Receiver_type
                            Receiver_ID = postdata['Item'][i]['Receiver']['Id']
                            print Receiver_ID
                            content = FromUserName + "说话的" + "文本消息内容是:" + content2 + "|" + str(
                                int(time.time()))
                            key = suiteId + "suite_access_token"
                            suite_access_token = cache.redis.get(key)
                            officialaccount = env['wx.officialaccount'].search(
                                [('wx_appid', '=', appid),
                                 ('third_auth_SuiteId', '=', suiteId),
                                 ('third_auth_id', '=', 1)])
                            text_template = {}
                            text_template.update({"id": ""})
                            try:
                                env['send_message'].insert_qy_text_record(
                                    FromUserName, officialaccount, env,
                                    content, text_template, "", False, "",
                                    "sending", "send")
                            except Exception as e:
                                _logger.info("插入文本消息记录出错:" + str(e))
                            corp_access_token = qy_open_public_sdk.get_corp_access_token(
                                suite_access_token, suiteId, appid,
                                officialaccount['third_auth_code'])
                            print corp_access_token
                            send_user = '******'
                            receiver_type = 'group'
                            receiver_id = '9223372036864775811'
                            session_result = qy_open_public_sdk.send_text_session(
                                corp_access_token, send_user, content,
                                receiver_type, receiver_id)
                            print session_result
                        elif MsgType == "image":
                            FromUserName = postdata['Item'][i]['FromUserName']
                            MediaId = postdata['Item'][i]['MediaId']
                            PicUrl = postdata['Item'][i]['PicUrl']
                            print FromUserName
                            Receiver_type = postdata['Item'][i]['Receiver'][
                                'Type']
                            print Receiver_type
                            Receiver_ID = postdata['Item'][i]['Receiver']['Id']
                            print Receiver_ID
                            # content =FromUserName+"说话的"+ "文本消息内容是:"+content2+"|" + str(int(time.time()))
                            content = FromUserName + "发送的图片地址为:" + PicUrl
                            key = suiteId + "suite_access_token"
                            suite_access_token = cache.redis.get(key)
                            officialaccount = env['wx.officialaccount'].search(
                                [('wx_appid', '=', appid),
                                 ('third_auth_SuiteId', '=', suiteId),
                                 ('third_auth_id', '=', 1)])
                            corp_access_token = qy_open_public_sdk.get_corp_access_token(
                                suite_access_token, suiteId, appid,
                                officialaccount['third_auth_code'])
                            print corp_access_token
                            send_user = '******'
                            receiver_type = 'group'
                            receiver_id = '9223372036864775811'
                            session_result = qy_open_public_sdk.send_text_session(
                                corp_access_token, send_user, content,
                                receiver_type, receiver_id)
                            print session_result
                            session_image_result = qy_open_public_sdk.send_image_session(
                                corp_access_token, send_user, MediaId,
                                receiver_type, receiver_id)
                            print session_image_result
                        elif MsgType == "voice":
                            FromUserName = postdata['Item'][i]['FromUserName']
                            MediaId = postdata['Item'][i]['MediaId']

                            print FromUserName
                            Receiver_type = postdata['Item'][i]['Receiver'][
                                'Type']
                            print Receiver_type
                            Receiver_ID = postdata['Item'][i]['Receiver']['Id']
                            print Receiver_ID
                            # content =FromUserName+"说话的"+ "文本消息内容是:"+content2+"|" + str(int(time.time()))
                            content = FromUserName + "发送的是语音。。。"
                            key = suiteId + "suite_access_token"
                            suite_access_token = cache.redis.get(key)
                            officialaccount = env['wx.officialaccount'].search(
                                [('wx_appid', '=', appid),
                                 ('third_auth_SuiteId', '=', suiteId),
                                 ('third_auth_id', '=', 1)])
                            corp_access_token = qy_open_public_sdk.get_corp_access_token(
                                suite_access_token, suiteId, appid,
                                officialaccount['third_auth_code'])
                            print corp_access_token
                            send_user = '******'
                            receiver_type = 'group'
                            receiver_id = '9223372036864775811'
                            session_result = qy_open_public_sdk.send_text_session(
                                corp_access_token, send_user, content,
                                receiver_type, receiver_id)
                            print session_result
                            session_image_result = qy_open_public_sdk.send_voice_session(
                                corp_access_token, send_user, MediaId,
                                receiver_type, receiver_id)
                            print session_image_result
            print result
            return 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]
        return 'success'
Beispiel #7
0
 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]
Beispiel #8
0
 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]