Exemple #1
0
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)
Exemple #2
0
    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)
Exemple #3
0
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
Exemple #4
0
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
Exemple #5
0
def interface(request):
    msg_signature = request.GET.get('msg_signature', '')
    signature = request.GET.get('signature', msg_signature)
    timestamp = request.GET.get('timestamp', '')
    nonce = request.GET.get('nonce', '')
    echostr = request.GET.get('echostr', '')
    crypto = WeChatCrypto(WECHAT_TOKEN, AES_KEY, APPID)
    if request.method == 'GET':
        signer = WeChatSigner()
        signer.add_data(WECHAT_TOKEN, timestamp, nonce)
        log.debug('>>> Signatrue:{},get:{},body:{}'.format(
            signer.signature, request.GET, request.body))
        try:
            echostr = crypto.check_signature(signature, timestamp, nonce,
                                             echostr)
        except InvalidSignatureException as e:
            log.error('>>> SignatrueException:{},get:{},body:{}'.format(
                e, request.GET, request.body))
            return HttpResponse('')
        return HttpResponse(echostr)

    # 处理POST请求
    try:
        decrypted_xml = crypto.decrypt_message(request.body, msg_signature,
                                               timestamp, nonce)
    except (InvalidCorpIdException, InvalidSignatureException):
        # to-do: 处理异常或忽略
        log.error('>>> Decrypt message exception,get:{},body:{}'.format(
            request.GET, request.body))
        return HttpResponse('Decrypt message exception')

    xml = response_message(decrypted_xml, request)
    encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
    response = HttpResponse(encrypted_xml, content_type="application/xml")
    return response
Exemple #6
0
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
Exemple #7
0
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
Exemple #8
0
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
Exemple #9
0
    def test_encrypt_message(self):
        origin_crypto = _crypto.PrpCrypto
        _crypto.PrpCrypto = PrpCryptoMock

        nonce = '461056294'
        timestamp = '1411525903'
        reply = """<xml>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[test]]></Content>
<FromUserName><![CDATA[wx49f0ab532d5d035a]]></FromUserName>
<ToUserName><![CDATA[messense]]></ToUserName>
<AgentID>1</AgentID>
<CreateTime>1411525903</CreateTime>
</xml>"""

        expected = """<xml>
<Encrypt><![CDATA[9s4gMv99m88kKTh/H8IdkOiMg6bisoy3ypwy9H4hvSPe9nsGaqyw5hhSjdYbcrKk+j3nba4HMOTzHrluLBYqxgNcBqGsL8GqxlhZgURnAtObvesEl5nZ+uBE8bviY0LWke8Zy9V/QYKxNV2FqllNXcfmstttyIkMKCCmVbCFM2JTF5wY0nFhHZSjPUL2Q1qvSUCUld+/WIXrx0oyKQmpB6o8NRrrNrsDf03oxI1p9FxUgMnwKKZeOA/uu+2IEvEBtb7muXsVbwbgX05UPPJvFurDXafG0RQyPR+mf1nDnAtQmmNOuiR5MIkdQ39xn1vWwi1O5oazPoQJz0nTYjxxEE8kv3kFxtAGVRe3ypD3WeK2XeFYFMNMpatF9XiKzHo3]]></Encrypt>
<MsgSignature><![CDATA[407518b7649e86ef23978113f92d27afa9296533]]></MsgSignature>
<TimeStamp>1411525903</TimeStamp>
<Nonce><![CDATA[461056294]]></Nonce>
</xml>"""

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        encrypted = crypto.encrypt_message(reply, nonce, timestamp)

        _crypto.PrpCrypto = origin_crypto

        self.assertEqual(expected, encrypted)
Exemple #10
0
    def test_encrypt_message(self):
        origin_crypto = _crypto.PrpCrypto
        _crypto.PrpCrypto = PrpCryptoMock

        nonce = '461056294'
        timestamp = '1411525903'
        reply = """<xml>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[test]]></Content>
<FromUserName><![CDATA[wx49f0ab532d5d035a]]></FromUserName>
<ToUserName><![CDATA[messense]]></ToUserName>
<AgentID>1</AgentID>
<CreateTime>1411525903</CreateTime>
</xml>"""

        expected = """<xml>
<Encrypt><![CDATA[9s4gMv99m88kKTh/H8IdkOiMg6bisoy3ypwy9H4hvSPe9nsGaqyw5hhSjdYbcrKk+j3nba4HMOTzHrluLBYqxgNcBqGsL8GqxlhZgURnAtObvesEl5nZ+uBE8bviY0LWke8Zy9V/QYKxNV2FqllNXcfmstttyIkMKCCmVbCFM2JTF5wY0nFhHZSjPUL2Q1qvSUCUld+/WIXrx0oyKQmpB6o8NRrrNrsDf03oxI1p9FxUgMnwKKZeOA/uu+2IEvEBtb7muXsVbwbgX05UPPJvFurDXafG0RQyPR+mf1nDnAtQmmNOuiR5MIkdQ39xn1vWwi1O5oazPoQJz0nTYjxxEE8kv3kFxtAGVRe3ypD3WeK2XeFYFMNMpatF9XiKzHo3]]></Encrypt>
<MsgSignature><![CDATA[407518b7649e86ef23978113f92d27afa9296533]]></MsgSignature>
<TimeStamp>1411525903</TimeStamp>
<Nonce><![CDATA[461056294]]></Nonce>
</xml>"""

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        encrypted = crypto.encrypt_message(reply, nonce, timestamp)

        _crypto.PrpCrypto = origin_crypto

        self.assertEqual(expected, encrypted)
Exemple #11
0
    def dispatch(self, request, *args, **kwargs):
        wx_conf = self.get_wx_conf()
        self.crypto = WeChatCrypto(wx_conf.Token, wx_conf.EncodingAESKey,
                                   wx_conf.corp_id)

        self.wx_data['signature'] = request.GET.get('msg_signature', '')
        self.wx_data['timestamp'] = request.GET.get('timestamp', '')
        self.wx_data['nonce'] = request.GET.get('nonce', '')
        return super().dispatch(request, *args, **kwargs)
Exemple #12
0
    def test_check_signature_should_ok(self):
        signature = 'dd6b9c95b495b3f7e2901bfbc76c664930ffdb96'
        timestamp = '1411443780'
        nonce = '437374425'
        echo_str = '4ByGGj+sVCYcvGeQYhaKIk1o0pQRNbRjxybjTGblXrBaXlTXeOo1+bXFXDQQb1o6co6Yh9Bv41n7hOchLF6p+Q=='  # NOQA

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        echo_str = crypto.check_signature(signature, timestamp, nonce,
                                          echo_str)
Exemple #13
0
    def test_check_signature_should_ok(self):
        signature = 'dd6b9c95b495b3f7e2901bfbc76c664930ffdb96'
        timestamp = '1411443780'
        nonce = '437374425'
        echo_str = '4ByGGj+sVCYcvGeQYhaKIk1o0pQRNbRjxybjTGblXrBaXlTXeOo1+bXFXDQQb1o6co6Yh9Bv41n7hOchLF6p+Q=='  # NOQA

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        echo_str = crypto.check_signature(
            signature,
            timestamp,
            nonce,
            echo_str
        )
Exemple #14
0
def weixin_handler():
    # 从config文件中获取
    token = os.getenv('WECHAT_TOKEN', config.WECHAT_TOKEN)
    encodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY',
                               config.WECHAT_ENCODING_AES_KEY)
    appId = os.getenv('WECHAT_APP_ID', config.WECHAT_APP_ID)

    # 从请求中获取
    signature = flask.request.args.get("signature")
    timestamp = flask.request.args.get("timestamp")
    nonce = flask.request.args.get("nonce")
    echostr = flask.request.args.get("echostr")
    # encrypt_type = flask.request.args.get("encrypt_type")
    msg_signature = flask.request.args.get("msg_signature")
    '''
    print('signature:', signature)
    print('timestamp: ', timestamp)
    print('nonce:', nonce)
    print('echo_str:', echostr)
    print('encrypt_type:', encrypt_type)
    print('msg_signature:', msg_signature)
    '''

    crypto = WeChatCrypto(token, encodingAESKey, appId)
    try:
        check_signature(token, signature, timestamp, nonce)  # 签名验证
    except InvalidSignatureException:
        flask.abort(403)  # 校验token失败,证明这条消息不是微信服务器发送过来的

    if flask.request.method == "GET":  # 如果时明文模式 直接返回echoster
        return echostr
    elif flask.request.method == "POST":  # 如果时加密模式 先对传入的数据解密
        try:
            msg = crypto.decrypt_message(flask.request.data, msg_signature,
                                         timestamp, nonce)
            print('Descypted message: \n%s' % msg)  # 输出数据内容
        except (InvalidSignatureException, InvalidAppIdException):
            flask.abort(404)
        msg = parse_message(msg)  # 解析xml
        if msg.type == 'text':
            res = get_robot_reply(msg.content)
            reply = TextReply(message=msg)
            reply.content = '%s' % (res)
        elif msg.type == "image":  # 图片回复
            reply = ImageReply(message=msg)
            reply.media_id = msg.media_id
        else:
            reply = TextReply(content="暂时不支持此种类型的回复哦~", message=msg)
        print('Enscypted message: \n%s' % reply)
        # 返回加密信息
        return crypto.encrypt_message(reply.render(), nonce, timestamp)
Exemple #15
0
    def test_decrypt_message(self):
        xml = """<xml><ToUserName><![CDATA[wx49f0ab532d5d035a]]></ToUserName>
<Encrypt><![CDATA[RgqEoJj5A4EMYlLvWO1F86ioRjZfaex/gePD0gOXTxpsq5Yj4GNglrBb8I2BAJVODGajiFnXBu7mCPatfjsu6IHCrsTyeDXzF6Bv283dGymzxh6ydJRvZsryDyZbLTE7rhnus50qGPMfp2wASFlzEgMW9z1ef/RD8XzaFYgm7iTdaXpXaG4+BiYyolBug/gYNx410cvkKR2/nPwBiT+P4hIiOAQqGp/TywZBtDh1yCF2KOd0gpiMZ5jSw3e29mTvmUHzkVQiMS6td7vXUaWOMZnYZlF3So2SjHnwh4jYFxdgpkHHqIrH/54SNdshoQgWYEvccTKe7FS709/5t6NMxuGhcUGAPOQipvWTT4dShyqio7mlsl5noTrb++x6En749zCpQVhDpbV6GDnTbcX2e8K9QaNWHp91eBdCRxthuL0=]]></Encrypt>
<AgentID><![CDATA[1]]></AgentID>
</xml>"""

        signature = '74d92dfeb87ba7c714f89d98870ae5eb62dff26d'
        timestamp = '1411525903'
        nonce = '461056294'

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        msg = crypto.decrypt_message(xml, signature, timestamp, nonce)
        self.assertEqual('test', msg['Content'])
        self.assertEqual('messense', msg['FromUserName'])
Exemple #16
0
    def test_decrypt_binary_message(self):
        xml = b"""<xml><ToUserName><![CDATA[wx49f0ab532d5d035a]]></ToUserName>
<Encrypt><![CDATA[RgqEoJj5A4EMYlLvWO1F86ioRjZfaex/gePD0gOXTxpsq5Yj4GNglrBb8I2BAJVODGajiFnXBu7mCPatfjsu6IHCrsTyeDXzF6Bv283dGymzxh6ydJRvZsryDyZbLTE7rhnus50qGPMfp2wASFlzEgMW9z1ef/RD8XzaFYgm7iTdaXpXaG4+BiYyolBug/gYNx410cvkKR2/nPwBiT+P4hIiOAQqGp/TywZBtDh1yCF2KOd0gpiMZ5jSw3e29mTvmUHzkVQiMS6td7vXUaWOMZnYZlF3So2SjHnwh4jYFxdgpkHHqIrH/54SNdshoQgWYEvccTKe7FS709/5t6NMxuGhcUGAPOQipvWTT4dShyqio7mlsl5noTrb++x6En749zCpQVhDpbV6GDnTbcX2e8K9QaNWHp91eBdCRxthuL0=]]></Encrypt>
<AgentID><![CDATA[1]]></AgentID>
</xml>"""

        signature = '74d92dfeb87ba7c714f89d98870ae5eb62dff26d'
        timestamp = '1411525903'
        nonce = '461056294'

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        msg = crypto.decrypt_message(xml, signature, timestamp, nonce)
        msg_dict = xmltodict.parse(msg)['xml']
        self.assertEqual('test', msg_dict['Content'])
        self.assertEqual('messense', msg_dict['FromUserName'])
Exemple #17
0
 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)
Exemple #18
0
    def init(self, env, from_ui=False):
        self.init_data(env)
        global CorpEnvDict
        CorpEnvDict[env.cr.dbname] = self

        config = env['wx.corp.config'].sudo().get_cur()
        Corp_Token = config.Corp_Token
        Corp_AESKey = config.Corp_AESKey

        Corp_Id = config.Corp_Id
        Corp_Secret = config.Corp_Secret
        Corp_Agent = config.Corp_Agent
        Corp_Agent_Secret = config.Corp_Agent_Secret

        from wechatpy.enterprise.crypto import WeChatCrypto
        _logger.info('Create crypto: %s %s %s' %
                     (Corp_Token, Corp_AESKey, Corp_Id))
        try:
            self.crypto_handle = WeChatCrypto(Corp_Token, Corp_AESKey, Corp_Id)
        except:
            _logger.error(u'初始化企业微信客户端实例失败,请在微信对接配置中填写好相关信息!')
            if from_ui:
                raise ValidationError(u'对接失败,请检查相关信息是否填写正确')
        self.init_client(Corp_Id, Corp_Agent_Secret)
        self.init_txl_client(Corp_Id, Corp_Secret)
        self.current_agent = Corp_Agent
Exemple #19
0
    def init(self, env):
        global CorpEnvDict
        CorpEnvDict[env.cr.dbname] = self

        Param = env['ir.config_parameter'].sudo()

        Corp_Token = Param.get_param('Corp_Token') or ''
        Corp_AESKey = Param.get_param('Corp_AESKey') or ''

        Corp_Id = Param.get_param('Corp_Id') or ''       # 企业号
        Corp_Secret = Param.get_param('Corp_Secret') or ''
        Corp_Agent = Param.get_param('Corp_Agent') or 0
        Corp_Agent_Secret = Param.get_param('Corp_Agent_Secret') or ''

        from wechatpy.enterprise.crypto import WeChatCrypto
        _logger.info('Create crypto: %s %s %s'%(Corp_Token, Corp_AESKey, Corp_Id))
        try:
            self.crypto_handle = WeChatCrypto(Corp_Token, Corp_AESKey, Corp_Id)
        except:
            _logger.error(u'初始化企业微信客户端实例失败,请在微信对接配置中填写好相关信息!')
        self.init_client(Corp_Id, Corp_Agent_Secret)
        self.init_txl_client(Corp_Id, Corp_Secret)
        self.current_agent = Corp_Agent

        try:
            users = env['wx.corpuser'].sudo().search([('last_uuid','!=',None)])
            for obj in users:
                self.OPENID_UUID[obj.userid] = obj.last_uuid
                self.UUID_OPENID[obj.last_uuid] = obj.userid
        except:
            env.cr.rollback()
            import traceback;traceback.print_exc()

        print('corp client init: %s %s'%(self.OPENID_UUID, self.UUID_OPENID))
Exemple #20
0
 def execute(self, cr, uid, ids, context=None):
     super(wxcorp_config_settings,self).execute(cr, uid, ids, context)
     record = self.browse(cr, uid, ids[0], context=context)
     from ..rpc import corp_client
     from ..controllers import wx_handler
     from wechatpy.enterprise.crypto import WeChatCrypto
     wx_handler.crypto = WeChatCrypto(record.Corp_Token, record.Corp_AESKey, record.Corp_Id)
     corp_client.init_client(record.Corp_Id, record.Corp_Secret)
Exemple #21
0
 def __init__(self):
     Param = request.env()['ir.config_parameter']
     
     self.TOKEN = Param.get_param('wx_token') or 'K5Dtswpte'
     self.EncodingAESKey = Param.get_param('EncodingAESKey') or ''
     self.CorpId = Param.get_param('CorpId') or ''       # 企业号
     
     global crypto
     crypto = WeChatCrypto(self.TOKEN, self.EncodingAESKey, self.CorpId)
Exemple #22
0
 def execute(self):
     self.ensure_one()
     super(wxcorp_config_settings, self).execute()
     record = self
     from ..rpc import corp_client
     from ..controllers import wx_handler
     from wechatpy.enterprise.crypto import WeChatCrypto
     wx_handler.crypto = WeChatCrypto(record.Corp_Token, record.Corp_AESKey, record.Corp_Id)
     corp_client.init_client(record.Corp_Id, record.Corp_Secret)
Exemple #23
0
    def test_check_signature_should_fail(self):
        from wechatpy.exceptions import InvalidSignatureException

        signature = 'dd6b9c95b495b3f7e2901bfbc76c664930ffdb96'
        timestamp = '1411443780'
        nonce = '437374424'
        echo_str = '4ByGGj+sVCYcvGeQYhaKIk1o0pQRNbRjxybjTGblXrBaXlTXeOo1+bXFXDQQb1o6co6Yh9Bv41n7hOchLF6p+Q=='  # NOQA

        crypto = WeChatCrypto(self.token, self.encoding_aes_key, self.corp_id)
        self.assertRaises(InvalidSignatureException, crypto.check_signature,
                          signature, timestamp, nonce, echo_str)
Exemple #24
0
def hello_world():
    try:
        signature = request.args.get('signature', None)
        timestamp = request.args.get('timestamp', None)
        nonce = request.args.get('nonce')

        check_signature(TOKEN, signature, timestamp, nonce)

        wechat_logger.info('request.args is %s' % request.args)

        crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
        echo_str = request.args.get('echostr', '')
        try:
            echo_str = crypto.check_signature(signature, timestamp, nonce,
                                              echo_str)
        except InvalidSignatureException:
            abort(403)
        return echo_str
    except:
        return 'error'
Exemple #25
0
    def __init__(self):
        Param = request.env()['ir.config_parameter']

        self.TOKEN = Param.get_param('Corp_Token') or 'NN07w58BUvhuHya'
        self.EncodingAESKey = Param.get_param(
            'Corp_AESKey') or 'esGH2pMM98SwPMMQpXPG5Y5QawuL67E2aBvNP10V8Gl'
        self.CorpId = Param.get_param('Corp_Id') or ''  # 企业号
        self.Secret = Param.get_param('Corp_Secret') or ''

        global crypto
        crypto = WeChatCrypto(self.TOKEN, self.EncodingAESKey, self.CorpId)
        from ..rpc import corp_client
        corp_client.init_client(self.CorpId, self.Secret)
Exemple #26
0
    def __init__(self):
        aas_application = request.env['aas.wechat.enapplication'].sudo(
        ).search([('app_code', '=', 'aas_quality')], limit=1)
        self.token = aas_application.app_token
        self.encoding_aeskey = aas_application.encoding_aes_key
        self.corpid = aas_application.corp_id
        self.role_secret = aas_application.role_secret

        global quality_crypto
        quality_crypto = WeChatCrypto(self.token, self.encoding_aeskey,
                                      self.corpid)
        global quality_client
        quality_client = WeChatClient(self.corpid, self.role_secret)
Exemple #27
0
 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
Exemple #28
0
    def weixin_callback(self, **kwargs):
        crypto = WeChatCrypto(Token, EncodingAESKey, CorpId)
        msg_signature, timestamp, nonce = kwargs[
            'msg_signature'], kwargs['timestamp'], kwargs['nonce']
        if request.httprequest.method == 'GET':
            try:
                echostr = crypto.check_signature(
                    msg_signature,
                    timestamp,
                    nonce,
                    kwargs['echostr'],
                )
            except InvalidSignatureException:
                return 'error'
            return echostr
        else:
            try:
                msg = crypto.decrypt_message(
                    request.httprequest.data,
                    msg_signature,
                    timestamp,
                    nonce,
                )
                msg = wechatpy.parse_message(msg)

                if msg.event == 'subscribe':
                    url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s' % (
                        self.get_token(), msg.source)
                    userinfo = urllib2.urlopen(url).read()

                    ormenv = request.env
                    employee = ormenv['hr.employee'].sudo().search(
                        [('user_id', '=', msg.source)])
                    employee.corp_weixinid = simplejson.loads(
                        userinfo).get('weixinid')

                    reply = wechatpy.replies.ArticlesReply(message=msg)

                    reply.add_article({
                        'title': '欢迎关注',
                        'description': '欢迎您关注',
                        # 'image': 'image url',
                        'url': request.httprequest.host_url + 'mobile/ui/home',
                    })
                    return crypto.encrypt_message(reply.render(), nonce, timestamp)

                return 'ok'
                if msg.type == 'text':
                    reply = wechatpy.create_reply(msg.content, msg)
                else:
                    reply = wechatpy.create_reply(
                        'Sorry, can not handle this for now', msg)
                return crypto.encrypt_message(reply.render(), nonce, timestamp)

            except InvalidSignatureException:
                return 'error'
Exemple #29
0
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")
Exemple #30
0
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 ''
def replay_msg(request):
    wechat_app = EntWechatConf.objects.values().first()
    token = wechat_app['token']  # 访问令牌
    encoding_aes_key = wechat_app['encoding_aes_key']  # 应用EncodingAESKey
    corp_id = wechat_app['corp_id']  # 企业ID
    signature = request.GET.get('msg_signature', '')
    timestamp = request.GET.get('timestamp', '')
    nonce = request.GET.get('nonce', '')
    echo_str = request.GET.get('echostr', '')
    crypto = WeChatCrypto(token, encoding_aes_key, corp_id)
    if request.method == 'GET':
        try:
            secho_str = crypto.check_signature(signature, timestamp, nonce,
                                               echo_str)
        except InvalidSignatureException:
            raise
        return HttpResponse(secho_str)
    raw_message = request.body
    try:
        decrypted_xml = crypto.decrypt_message(raw_message, signature,
                                               timestamp, nonce)
    except (InvalidSignatureException, InvalidCorpIdException):
        raise
    else:
        msg = parse_message(decrypted_xml)
        if msg.type == 'event':
            if msg.event == 'location':
                # from webapp.views.tencent.message_template import replay_msg
                # replay_msg()
                # 把位置信息存入数据库中
                try:
                    LocationLog.objects.create(
                        **{
                            "name": msg.source,
                            "create_date": msg.create_time,
                            "latitude": msg.latitude,
                            "longitude": msg.longitude,
                            "precision": msg.precision
                        })
                except Exception as e:
                    print(e)

                reply = TextReply(content="", message=msg)
                xml = reply.render()
                encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
                return HttpResponse(encrypted_xml)
            if msg.event == 'scancode_push':
                m = ScanCodePushEvent(msg)
                print(m)
                reply = TextReply(content=m.scan_result, message=msg)
                xml = reply.render()
                encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
                return HttpResponse(encrypted_xml)
            if msg.event == 'view':
                print(msg.source)
                reply = TextReply(content="", message=msg)
                xml = reply.render()
                encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
                return HttpResponse(encrypted_xml)
        if msg.type == 'text' or msg.type == 'enter_agent':
            reply = TextReply(content="谢谢", message=msg)
            xml = reply.render()
            encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
            return HttpResponse(encrypted_xml)
        if msg.type == 'unknown':
            reply = TextReply(content="", message=msg)
            xml = reply.render()
            encrypted_xml = crypto.encrypt_message(xml, nonce, timestamp)
            return HttpResponse(encrypted_xml)
Exemple #32
0
        env.setdefault(k, v)
    redis_host = env["REDIS_HOST"]
    redis_port = int(env["REDIS_PORT"])
    redis_pwd = env["REDIS_PWD"]
    wechat_corp_id = env["WECHAT_CORP_ID"]
    wechat_secret = env["WECHAT_SECRET"]
    wechat_crypto_token = env['WECHAT_CRYPTO_TOKEN']
    wechat_crypto_encoding_aes_key = env['WECHAT_CRYPTO_AES_KEY']
    wechat_invite_code = env['WECHAT_INVITE_CODE']
    wechat_create_menu = distutils.util.strtobool(env['WECHAT_CREATE_MENU'])
    agent_id = env['AGENT_ID']
    image_id = env['IMAGE_ID']
    debug = distutils.util.strtobool(env['DEBUG'])
    logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
    for i in [redis_host, redis_port, redis_pwd, wechat_corp_id, wechat_secret,
              wechat_crypto_token, wechat_crypto_encoding_aes_key, agent_id]:
        if i == 'set_it':
            logging.error(env.items())
            logging.error('部分变量未设置,请检查你的变量设置是否正确。')
            time.sleep(30)
            exit(-1)
    if wechat_create_menu:
        create_menu()
    r = redis.Redis(host=redis_host, port=redis_port, db=0, password=redis_pwd)
    crypto = WeChatCrypto(token=wechat_crypto_token, encoding_aes_key=wechat_crypto_encoding_aes_key,
                          corp_id=wechat_corp_id)
    client = WeChatClient(corp_id=wechat_corp_id, secret=wechat_secret, session=RedisStorage(r))
    # 启用京东登录事件循环
    jd_qrcode.start_loop()
    run()
Exemple #33
0
class WechatBaseView(View):
    app_name = 'zdzq_main'
    # wx_conf = WxConf(app_name=app_name)
    # crypto = WeChatCrypto(wx_conf.Token, wx_conf.EncodingAESKey, wx_conf.corp_id)
    wx_data = {}

    def get_wx_conf(self):
        return WxConf(app_name=self.app_name)

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        wx_conf = self.get_wx_conf()
        self.crypto = WeChatCrypto(wx_conf.Token, wx_conf.EncodingAESKey,
                                   wx_conf.corp_id)

        self.wx_data['signature'] = request.GET.get('msg_signature', '')
        self.wx_data['timestamp'] = request.GET.get('timestamp', '')
        self.wx_data['nonce'] = request.GET.get('nonce', '')
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        echo_str = request.GET.get('echostr', '')
        print(echo_str, 'get')
        try:
            echo_str = self.crypto.check_signature(echo_str=echo_str,
                                                   **self.wx_data)
            print('ok', 'get')
        except InvalidSignatureException:
            echo_str = 'error'
            print('error', 'get')
        return HttpResponse(echo_str)

    # POST方式用于接受和返回请求
    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 get_url(self,so):
    #     return "%s" % (self.request.build_absolute_uri(so.get_absolute_url()))

    # def get_title(self):
    #     title = "%s/金额:¥%s    [%s]" % (
    #         self.model._meta.verbose_name, self.object.amount, self.object.get_state_display())
    #     return title

    def get_items(self, so):
        print('get_items')
        html = '\n---------------------------------'
        for item in so.items.all():
            if html:
                html += '\n'
            html += '(%s) %s /%s夹/%s件/%s%s *¥%s' % (
                item.line, item.product,
                str(item.package_list.get_part()) if item.package_list else '',
                item.piece, item.quantity, item.uom, item.price)
        html += '\n---------------------------------\n'
        html += '合计:'
        print('item html', html)
        for key, item in so.get_total().items():
            html += '%s:%s %s件/%s%s\n' % (key, item['part'] if item.get(
                'part') else '', item['piece'], item['quantity'], item['uom'])
        html += '\n金额:¥ %s' % so.amount
        return html

    def get_description(self, so):
        print('desc')
        html = '单号:%s\n' % so.order
        html += '\n客户:%s' % so.partner
        html += '\n销往:%s' % so.get_address()
        html += "\n订单日期:%s" % (datetime.strftime(so.date, "%Y/%m/%d"))
        html += "\n销售:%s" % so.handler
        now = datetime.now()
        print('ready get_items')
        html += '%s' % self.get_items(so)
        html += '\n操作:%s \n@%s' % (self.request.user,
                                   datetime.strftime(now, '%Y/%m/%d %H:%M'))
        return html

    def reply_event(self):
        msg = self.orign_msg
        print('msg:%s' % msg)
        # print('msg_key:%s' % msg.key)
        print('msg_scan_result:%s' % msg.scan_result)
        if msg.key == 'so_code':
            # TODO: 增加搜索编号的方法
            so_num = msg.scan_result
            print(so_num[:9])
            from sales.models import SalesOrder
            try:
                so = SalesOrder.objects.get(order=so_num[:9])
                print(so)
                massage = (
                    {
                        'title':
                        '%s' % so,
                        'description':
                        self.get_description(so),
                        'url':
                        '%s' %
                        self.request.build_absolute_uri(so.get_absolute_url()),
                        # 'image': '%s' % (image.content.url if image else '')
                    }, )
                print(massage)
                # massages.append(massage)
            except Exception as e:
                massage = '没有查找到单号:%s' % so_num[:9]
            content = create_reply(massage, msg)
            # print(content)
        else:
            content = create_reply('该条形码没有信息', msg)
        return content.render()