最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[未解决]用Python的微信SDK wechat-sdk中parse_data时出错:ValidateSignatureError

Python crifan 4309浏览 0评论

折腾:

[已解决]Flask中如何获取微信POST发送过来的body的数据

期间,把对应的:

@app.route(‘/wechat_auth’, methods=[‘GET’, ‘POST’])
def wechat_auth():
    signature = request.args.get(‘signature’, ”)
    timestamp = request.args.get(‘timestamp’, ”)
    nonce = request.args.get(‘nonce’, ”)
    echostr = request.args.get(‘echostr’, ”)
    app.logger.debug(‘signature=%s, timestamp=%s, nonce=%s, echostr=%s’, signature, timestamp, nonce, echostr)
    if wechat.check_signature(signature, timestamp, nonce):
        app.logger.debug("wechat check_signature OK")
        if request.method == ‘GET’ :
            respStr = echostr
            app.logger.debug(‘respStr=%s’, respStr)
            return make_response(respStr)
        else :
            # for POST
            requestMethod = request.method
            app.logger.debug(‘requestMethod=%s’, requestMethod)
            # requestMethod=POST
            requestData = request.data
            app.logger.debug(‘requestData=%s’, requestData)
            # <xml>
            #     <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
            #     <Encrypt><![CDATA[6PBVvYed+IuFgEa4BuDeOaNwM3KLqv6uoWqQcSCY+SidbN2VBjWL+N88kp0GU2BvLXyzlvbGGOxvJnFIDRQCDAgBUBhk3YQMWJmR+bB3D5phuVEIFo1MoknxB4xsIi3wVQunlyljyFl43TCwCxIvBVxXeHsKSzYOxhFGL+2ZmelLp46WJRaNrrh8yLl2eK1pRCR09QAoNZISLUszfzlr4N9t4nnl8ZuQpYqEdWt4bH8xsqTRPd91TG6hSio/o46G9Ow2QA16j7l4q9HXV2fZEIdlSJma4Jepl7N9jBDwrjd4zi4MXwsJpQ0KBI3Q1LBojlipt8wk1xzuVzmyidkHzvDtfIa22ZTvEu4MDYdYa8BXRYk1EtGpW0eDCiF/NLOyQzJsFM1T7jGsxjrKUIcYPmLFbNW8qZEIEDkAhahbVCI=]]></Encrypt>
            # </xml>
            requestArgs = request.args
            app.logger.debug(‘requestArgs=%s’, requestArgs)
            # requestArgs=ImmutableMultiDict([(‘nonce’, u’1438950245′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’cb962992182efd9f94f09560b893b20106408e49′), (‘timestamp’, u’1471573757′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’dc3336e6f85053f3563802f4e7b5398e3930d017′)])
            try:
                #wechat.parse_data(requestData)
                wechat.parse_data(requestData, signature, timestamp, nonce)
                app.logger.debug(‘parse post body data OK’)
            except ParseError:
                respStr = "parse post body failed"
                app.logger.debug(respStr)
                return wechat.response_text(respStr)

中的:

wechat.parse_data(requestData)

换成:

                #wechat.parse_data(requestData)
                wechat.parse_data(requestData, signature, timestamp, nonce)

结果竟然出错了:

<div–<——————————————————————————
[2016-08-19 10:44:23 +0000] [29476] [ERROR] Error handling request /wechat_auth?signature=86ac3f6fdbc0260369988f07a72935c5a7e2b4e2&timestamp=1471574663&nonce=1054233353&openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY&encrypt_type=aes&msg_signature=216a681558ba5fdeefd8606ac5e7f3078269e6dd
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 60, in wechat_auth
    wechat.parse_data(requestData, signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py", line 155, in parse_data
    nonce=nonce,
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 112, in decrypt_message
    return self._decrypt_message(msg, msg_signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 97, in _decrypt_message
    raise ValidateSignatureError()
ValidateSignatureError

搜:

wechat parse_data ValidateSignatureError

python3+flask不能解析消息 · Issue #89 · doraemonext/wechat-python-sdk

原来是SDK自己的bug。。。

去:

https://github.com/doraemonext/wechat-python-sdk/blob/master/wechat_sdk/basic.py

wechat-python-sdk/wechat_sdk/basic.py

def parse_data(self, data, msg_signature=None, timestamp=None, nonce=None):

编辑:

vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py

注释掉:

if isinstance(data, six.text_type):  # unicode to str(PY2), str to bytes(PY3)
            data = data.encode(‘utf-8’)

如图:

试试。

结果错误依旧:

<div–<——————————————————————————
[2016-08-19 10:53:25 +0000] [29571] [ERROR] Error handling request /wechat_auth?signature=c6bffafce8b8d52768392e2bf66e3a1efc69862a&timestamp=1471575205&nonce=1218822764&openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY&encrypt_type=aes&msg_signature=741d13aa3740e3b1dceeb8731b89870de9a8fed0
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 60, in wechat_auth
    wechat.parse_data(requestData, signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py", line 155, in parse_data
    nonce=nonce,
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 112, in decrypt_message
    return self._decrypt_message(msg, msg_signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 97, in _decrypt_message
    raise ValidateSignatureError()
ValidateSignatureError

所以取消刚才的注释。

不过再去看看解密的代码:

(SIPEvents) ➜  SIPEvents vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py

把解密代码加了注释:

        timestamp = to_binary(timestamp)
        print ‘timestamp=’,timestamp
        nonce = to_binary(nonce)
        print ‘nonce=’,nonce
        if isinstance(msg, six.string_types):
            try:
                textMsg = to_text(msg)
                print ‘textMsg=’,textMsg
                #msg = xmltodict.parse(to_text(msg))[‘xml’]
                parsedTextMsg = xmltodict.parse(textMsg)
                print ‘parsedTextMsg=’,parsedTextMsg
                msg = parsedTextMsg[‘xml’]
                print ‘msg=’,msg
            except Exception as e:
                raise ParseError(e)

再去测试,

输出:

<div–<——————————————————————————
DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:55]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’1016329670′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’ad99cbe7358671d0196af9a6c9c715aa5df3080c’), (‘timestamp’, u’1471576208′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’81892b198e7618a03bd7f2f1e70f2959e3881f5a’)])

<div–<——————————————————————————

data= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[hzHkhFI5q09PDKr3yPAtm0/No8/Rh0UCzlf7V806GjyDNFUxyoaR8LSJJHHyHg6dhV2b3FNntWJRYsyr1cO7mWie0JHVf04kknF8TTgssfviR8efSK6Na+9L+78GewknZlp/WbK+fh+upVQyLriTN9gxc8xDywrN0ZdHdB7tnh4xLVotBOHqLhqB58E2qRrJbkqpo7s32wkA25wMZ3R4dACmVpClYPQ8ASQTromFmb0FEb2F00XZKDH0WoRS6D6GqFfIa6S8OXre6fIWX08ouRk/oRbFMDFpN8T4HL7L50bQq/eNBCUNkR3ACsX60CMBc8JSDWNKDPRlBK13g5mJVSD88DLbS6ari5EjM+CboNlY3WBWUaB20M+zPr3ARbeYTXeZ7CIdf6V5rt2H8kZTo2kFdGA0jCpQo3MGHyCcbwBBpZtWYyhMIDQdJEO4DkU3z7fA60FB4L3g4hkC4iNNbQ==]]></Encrypt>
</xml>
self.conf.encrypt_mode= safe
timestamp= 1471576208
nonce= 1016329670
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[hzHkhFI5q09PDKr3yPAtm0/No8/Rh0UCzlf7V806GjyDNFUxyoaR8LSJJHHyHg6dhV2b3FNntWJRYsyr1cO7mWie0JHVf04kknF8TTgssfviR8efSK6Na+9L+78GewknZlp/WbK+fh+upVQyLriTN9gxc8xDywrN0ZdHdB7tnh4xLVotBOHqLhqB58E2qRrJbkqpo7s32wkA25wMZ3R4dACmVpClYPQ8ASQTromFmb0FEb2F00XZKDH0WoRS6D6GqFfIa6S8OXre6fIWX08ouRk/oRbFMDFpN8T4HL7L50bQq/eNBCUNkR3ACsX60CMBc8JSDWNKDPRlBK13g5mJVSD88DLbS6ari5EjM+CboNlY3WBWUaB20M+zPr3ARbeYTXeZ7CIdf6V5rt2H8kZTo2kFdGA0jCpQo3MGHyCcbwBBpZtWYyhMIDQdJEO4DkU3z7fA60FB4L3g4hkC4iNNbQ==]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’hzHkhFI5q09PDKr3yPAtm0/No8/Rh0UCzlf7V806GjyDNFUxyoaR8LSJJHHyHg6dhV2b3FNntWJRYsyr1cO7mWie0JHVf04kknF8TTgssfviR8efSK6Na+9L+78GewknZlp/WbK+fh+upVQyLriTN9gxc8xDywrN0ZdHdB7tnh4xLVotBOHqLhqB58E2qRrJbkqpo7s32wkA25wMZ3R4dACmVpClYPQ8ASQTromFmb0FEb2F00XZKDH0WoRS6D6GqFfIa6S8OXre6fIWX08ouRk/oRbFMDFpN8T4HL7L50bQq/eNBCUNkR3ACsX60CMBc8JSDWNKDPRlBK13g5mJVSD88DLbS6ari5EjM+CboNlY3WBWUaB20M+zPr3ARbeYTXeZ7CIdf6V5rt2H8kZTo2kFdGA0jCpQo3MGHyCcbwBBpZtWYyhMIDQdJEO4DkU3z7fA60FB4L3g4hkC4iNNbQ==’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’hzHkhFI5q09PDKr3yPAtm0/No8/Rh0UCzlf7V806GjyDNFUxyoaR8LSJJHHyHg6dhV2b3FNntWJRYsyr1cO7mWie0JHVf04kknF8TTgssfviR8efSK6Na+9L+78GewknZlp/WbK+fh+upVQyLriTN9gxc8xDywrN0ZdHdB7tnh4xLVotBOHqLhqB58E2qRrJbkqpo7s32wkA25wMZ3R4dACmVpClYPQ8ASQTromFmb0FEb2F00XZKDH0WoRS6D6GqFfIa6S8OXre6fIWX08ouRk/oRbFMDFpN8T4HL7L50bQq/eNBCUNkR3ACsX60CMBc8JSDWNKDPRlBK13g5mJVSD88DLbS6ari5EjM+CboNlY3WBWUaB20M+zPr3ARbeYTXeZ7CIdf6V5rt2H8kZTo2kFdGA0jCpQo3MGHyCcbwBBpZtWYyhMIDQdJEO4DkU3z7fA60FB4L3g4hkC4iNNbQ==’)])
[2016-08-19 11:10:08 +0000] [29772] [ERROR] Error handling request /wechat_auth?signature=ad99cbe7358671d0196af9a6c9c715aa5df3080c&timestamp=1471576208&nonce=1016329670&openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY&encrypt_type=aes&msg_signature=81892b198e7618a03bd7f2f1e70f2959e3881f5a
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 60, in wechat_auth
    wechat.parse_data(requestData, signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py", line 160, in parse_data
    nonce=nonce,
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 120, in decrypt_message
    return self._decrypt_message(msg, msg_signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 105, in _decrypt_message
    raise ValidateSignatureError()
ValidateSignatureError

然后加了注释,调试发现:

最后的,解码出来的signature不一样:

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:45]:
requestMethod=POST

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:48]:
requestData=<xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[/dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=]]></Encrypt>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:55]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’153496074′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’3424841cf93ac1e59763baaacaae287fc9079abf’), (‘timestamp’, u’1471576521′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’506d340023b7e1a7878064ccf9c0ce38e7915c41′)])

<div–<——————————————————————————

data= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[/dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=]]></Encrypt>
</xml>
self.conf.encrypt_mode= safe
timestamp= 1471576521
nonce= 153496074
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[/dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’/dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’/dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=’)])
encrypt= /dFR+g9YW7asjHUuZ/z0V+OHqx083HFQmhMtn7QJEqBT62rMKii+/dpYIqoxoQa0Mx41StSJA+lXVqWtQQfyddPNrvAoqBhEFGgjlpaeiOYnwwaymCcNO1nk6HR6ZjU9baBRO1VgiPCFL6b1nwBGCa5FzU2Dv0qzfD2ydd5KQxBvhA8vnZP4ETnYuZDc9SnqSnLR0F/dwqzwK8/JH3FA0Z5AEvdUvT50JVNlBIb7DbIuvBIoO88IoYW1DvlzRZAjb9ffQQzp0G2qoGuxINNWWANf/WLynT33pe95WXo22Uye1Bv8BCN9/NFs4XfC9bngVQyu8xutkL/PPlsExpRKbMGX6rVS8SNtITTwM24IBNj1Pdqr2JM/9JHGQtqe2lD0WYpYEo5FGDOkkWIuEPZ0L6vmGTCkDrhqXkjVr3+ugtU=
self.__token= sipevents
singnature= 506d340023b7e1a7878064ccf9c0ce38e7915c41  msg_signature= 3424841cf93ac1e59763baaacaae287fc9079abf
[2016-08-19 11:15:21 +0000] [29843] [ERROR] Error handling request /wechat_auth?signature=3424841cf93ac1e59763baaacaae287fc9079abf&timestamp=1471576521&nonce=153496074&openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY&encrypt_type=aes&msg_signature=506d340023b7e1a7878064ccf9c0ce38e7915c41
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 60, in wechat_auth
    wechat.parse_data(requestData, signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/basic.py", line 160, in parse_data
    nonce=nonce,
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 123, in decrypt_message
    return self._decrypt_message(msg, msg_signature, timestamp, nonce)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py", line 108, in _decrypt_message
    raise ValidateSignatureError()
ValidateSignatureError

singnature= 506d340023b7e1a7878064ccf9c0ce38e7915c41  msg_signature= 3424841cf93ac1e59763baaacaae287fc9079abf

对应着代码:

        signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt)
        print ‘singnature=’,signature,’ msg_signature=’,msg_signature
        if signature != msg_signature:
            raise ValidateSignatureError()

搜源码中的get_sha1_signature:

只有:

from wechat_sdk.lib.crypto.utils import get_sha1_signature

所以要去搞清楚:

搜:

get_sha1_signature not work

crypto get_sha1_signature

注意到:

python3+flask不能解析消息 · Issue #89 · doraemonext/wechat-python-sdk

中的:

pycrypto==2.6.1

难道是版本不同的原因?

抽空再去看看我此处的wechat_sdk.lib.crypto的版本是多少

green/utils.py at master · liuwons/green

然后去看此处,本地的代码:

vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/utils.py

# -*- coding: utf-8 -*-
import hashlib
from wechat_sdk.lib.crypto.exceptions import CryptoComputeSignatureError
from wechat_sdk.utils import to_binary
def get_sha1_signature(token, timestamp, nonce, encrypt):
    """
    用 SHA1 算法生成安全签名
    @param token: 票据
    @param timestamp: 时间戳
    @param encrypt: 密文
    @param nonce: 随机字符串
    @return: 安全签名
    """
    try:
        sortlist = [token, timestamp, nonce, to_binary(encrypt)]
        sortlist.sort()
        sha = hashlib.sha1()
        sha.update(to_binary("").join(sortlist))
        return sha.hexdigest()
    except Exception as e:
        raise CryptoComputeSignatureError(e)

然后看到此处的校验算法,和之前的:

wechat-python-sdk/basic.py at master · doraemonext/wechat-python-sdk

    def check_signature(self, signature, timestamp, nonce):
        """
        验证微信消息真实性
        :param signature: 微信加密签名
        :param timestamp: 时间戳
        :param nonce: 随机数
        :return: 通过验证返回 True, 未通过验证返回 False
        """
        if not signature or not timestamp or not nonce:
            return False
        tmp_list = [self.conf.token, timestamp, nonce]
        tmp_list.sort()
        tmp_str = ”.join(tmp_list)
        if signature != hashlib.sha1(tmp_str.encode(‘utf-8’)).hexdigest():
            return False
        return True

好像不一致啊。

而此处的:

signature, timestamp, nonce

之前调用:

check_signature

都是通过的

此处调用:

get_sha1_signature

就是不通过的

-》只能说明:

get_sha1_signature

的算法,有问题。

需要修正。

此处注意到:

get_sha1_signature

比:

check_signature

多了个

encrypt

参数。

不过后来看到:

 vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py

from wechat_sdk.exceptions import ParseError
from wechat_sdk.lib.crypto.base import BaseCrypto
from wechat_sdk.lib.crypto.utils import get_sha1_signature
from wechat_sdk.lib.crypto.exceptions import ValidateSignatureError, ValidateAESKeyError, DecryptAESError
from wechat_sdk.utils import to_binary, to_text
class WechatBaseCrypto(object):
    """微信加密解密基类"""
    def __init__(self, token, encoding_aes_key, _id):
        """构造函数
        :param token: 公众平台上,开发者设置的Token
        :param encoding_aes_key: 公众平台上,开发者设置的EncodingAESKey
        :param _id: 公众号的 appid 或企业号的 corpid
        """
        self.__key = base64.b64decode(to_binary(encoding_aes_key) + to_binary(‘=’))
        if len(self.__key) != 32:
            raise ValidateAESKeyError(encoding_aes_key)
        self.__token = to_binary(token)
        self.__id = to_binary(_id)
        self.__pc = BaseCrypto(self.__key)
    def _check_signature(self, msg_signature, timestamp, nonce, echostr):
        """验证签名有效性
        :param msg_signature: 签名串,对应URL参数的msg_signature
        :param timestamp: 时间戳,对应URL参数的timestamp
        :param nonce: 随机串,对应URL参数的nonce
        :param echostr: 随机串,对应URL参数的echostr
        :return: 解密之后的echostr
        :raise ValidateSignatureError: 签名无效异常
        """
        signature = get_sha1_signature(self.__token, timestamp, nonce, echostr)
        if not signature == msg_signature:
            raise ValidateSignatureError()
        try:
            return self.__pc.decrypt(echostr, self.__id)
        except DecryptAESError as e:
            raise ValidateSignatureError(e)
    def _encrypt_message(self, msg, nonce, timestamp=None):

中的_check_signature

也是类似的

内部调用了:get_sha1_signature

然后注意到此处的类是:

WechatBaseCrypto

难道是:

如果最开始定义了加密的话,不是用官网实例代码的:

WechatBasic

而应该换用此处的:

WechatBaseCrypto

??

去试试

不过在此之前,为了便于查看代码,先去:

[记录]Mac中尝试使用PyCharm打开Python的微信库wechat_sdk的源码

都怀疑,是否真的有人用了:

wechat-sdk

搜:

python wechat-sdk safe模式

参考: 

Python快速搭建自动回复微信公众号 – ^-^ – 博客频道 – CSDN.NET

Python开发之快速搭建自动回复微信公众号功能_小组_ThinkSAAS

-》

liuwons/green: 微信公众号源码 – 微信号Ms_haoqi

结果发现用的是:

"mode": "normal",

-》明文模式。。。

“                       ‘encrypt_mode’: 加解密模式 (‘normal’: 明文模式, ‘compatible’: 兼容模式, ‘safe’: 安全模式(默认))

3. WechatConf 详解 – wechat-python-sdk

python wechat-sdk safe mode

然后换用代码:

# from wechat_sdk import WechatBasic
from wechat_sdk. import WechatBaseCrypto
# wechat = WechatBasic(conf=wechatConf)
wechat = WechatBaseCrypto(conf=wechatConf)
    #if wechat.check_signature(signature, timestamp, nonce):
    if wechat.check_signature(signature, timestamp, nonce, echostr):

结果运行出错:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-19 12:11:16 +0000] [30387] [INFO] Starting gunicorn 19.6.0
[2016-08-19 12:11:16 +0000] [30387] [INFO] Listening at: http://127.0.0.1:8080 (30387)
[2016-08-19 12:11:16 +0000] [30387] [INFO] Using worker: sync
[2016-08-19 12:11:16 +0000] [30392] [INFO] Booting worker with pid: 30392
[2016-08-19 12:11:16 +0000] [30393] [INFO] Booting worker with pid: 30393
[2016-08-19 12:11:16 +0000] [30396] [INFO] Booting worker with pid: 30396
[2016-08-19 12:11:16 +0000] [30399] [INFO] Booting worker with pid: 30399
[2016-08-19 12:11:16 +0000] [30393] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 6, in <module>
    from wechat_sdk import WechatBaseCrypto
ImportError: cannot import name WechatBaseCrypto

搜:

import WechatBaseCrypto

sae下,调用wechat-sdk报错:ImportError: cannot import name _AES · Issue #106 · doraemonext/wechat-python-sdk

green/__init__.py at master · liuwons/green

换成:

# from wechat_sdk import WechatBaseCrypto
from wechat_sdk.lib.crypto.crypto import WechatBaseCrypto

试试:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-19 12:14:38 +0000] [30451] [INFO] Starting gunicorn 19.6.0
[2016-08-19 12:14:38 +0000] [30451] [INFO] Listening at: http://127.0.0.1:8080 (30451)
[2016-08-19 12:14:38 +0000] [30451] [INFO] Using worker: sync
[2016-08-19 12:14:38 +0000] [30456] [INFO] Booting worker with pid: 30456
[2016-08-19 12:14:38 +0000] [30457] [INFO] Booting worker with pid: 30457
[2016-08-19 12:14:38 +0000] [30458] [INFO] Booting worker with pid: 30458
[2016-08-19 12:14:38 +0000] [30460] [INFO] Booting worker with pid: 30460
[2016-08-19 12:14:38 +0000] [30456] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 7, in <module>
    from wechat_sdk.lib.crypto.crypto import WechatBaseCrypto
ImportError: No module named crypto

用:

from wechat_sdk.lib.crypto import WechatBaseCrypto

结果:

(SIPEvents) ➜  SIPEvents [2016-08-19 12:15:39 +0000] [30506] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
    worker.init_process()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app
    __import__(module)
  File "/usr/share/nginx/html/SIPEvents/wechat_auth.py", line 25, in <module>
    wechat = WechatBaseCrypto(conf=wechatConf)
TypeError: __init__() got an unexpected keyword argument ‘conf’
[2016-08-19 12:15:39 +0000] [30506] [INFO] Worker exiting (pid: 30506)

去看源码,果然是没有conf参数:

class WechatBaseCrypto(object):
    """微信加密解密基类"""
    def __init__(selftokenencoding_aes_key_id):
        """构造函数
        :param token: 公众平台上,开发者设置的Token
        :param encoding_aes_key: 公众平台上,开发者设置的EncodingAESKey
        :param _id: 公众号的 appid 或企业号的 corpid
        """
        self.__key base64.b64decode(to_binary(encoding_aes_keyto_binary(‘=’))
        if len(self.__key) != 32:
            raise ValidateAESKeyError(encoding_aes_key)
        self.__token to_binary(token)
        self.__id to_binary(_id)
        self.__pc BaseCrypto(self.__key)

参考:

/Users/crifan/dev/dev_src/Weixin/wechat-python-sdk-master/tests/test_basic.py

中的:

    def test_parse_data_text_message(self):
        message """<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>"""
        wechat WechatBasic()
        wechat.parse_data(data=message)
        message wechat.message
        self.assertIsInstance(message, TextMessage)
        self.assertEqual(message.id, 1234567890123456)
        self.assertEqual(message.target, ‘toUser’)
        self.assertEqual(message.source, ‘fromUser’)
        self.assertEqual(message.time, 1348831860)
        self.assertEqual(message.type, ‘text’)
        self.assertEqual(message.content, ‘this is a test’)

可以看出,此处的:

WechatBasic的wechat,去parse_data的message是没有加密的。

而对于加了密的message,则参考:

/Users/crifan/dev/dev_src/Weixin/wechat-python-sdk-master/tests/core/test_conf.py

中的:

safe_request_message """<xml>
<ToUserName><![CDATA[gh_1b2959761a7d]]></ToUserName>
<Encrypt><![CDATA[JCqIUfe7GJ84SQdp7M4y2xrnsqUp9ihcNZrAErcA8KSc5ewTAYCX1CtAiZqntANyYmFdQqwNAQXMU3vQGbJms/rXSjz4vN77kc9SbIDphNKRYXyaEI5P8iuQHlAjyfUE2kXnWjusYEPnKaB5RLkanwbNwhWVzgYbV4OVst9hSMepv3WpVzOBZlj8CpqhklqwHJuOda4X7unQzwRWyLA8M/lzPDCdN3rcRqz2wH9SlEc0JfjKXKk1RmBFYhHbJ2boeLFc7dIg0Sc3JNMCBw7MU4tBWAEuD+wedUSy45zZ0u1HeQSe13d6QSlVOoC9Ta0InwnlL28VpngEMru4YGeDGoyRKgDOYbDr71dI0sp/kInAKwPXWbOcqd0LFQ9P9Y+BxW4z5BNkYo9LFubXbilnO/VzU8++zuAhFSED11baYFs=]]></Encrypt>
</xml>"""
def test_init_with_safe_encrypt_mode(self):
    """ 测试安全模式下的初始化 """
    conf WechatConf(token=self.token, appid=self.appid, appsecret=self.appsecret,
                      encrypt_mode=‘safe’encoding_aes_key=self.encoding_aes_key)
    self.assertEqual(conf.token, self.token)
    self.assertEqual(conf.appid, self.appid)
    self.assertEqual(conf.appsecret, self.appsecret)
    self.assertEqual(conf.encoding_aes_key, self.encoding_aes_key)
    self.assertIsNotNone(conf.crypto)
    # 测试解密微信服务器的请求消息
    req conf.crypto.decrypt_message(msg=self.safe_request_message, msg_signature=self.msg_signature,
                                      timestamp=self.timestamp, nonce=self.nonce)
    self.assertEqual(xmltodict.parse(req), xmltodict.parse(self.normal_request_message))
    # 测试加密返回信息
    origin_crypto conf.crypto._WechatBaseCrypto__pc
    conf.crypto._WechatBaseCrypto__pc TestBaseCrypto(key=conf.crypto._WechatBaseCrypto__key)
    resp conf.crypto.encrypt_message(msg=self.response_message, nonce=self.nonce, timestamp=self.timestamp)
    self.assertEqual(xmltodict.parse(resp), xmltodict.parse(self.response_encrypted_message))
    conf.crypto._WechatBaseCrypto__pc origin_crypto

则是需要:

调用:

conf.crypto.decrypt_message

去解码后,才可以得到,普通的message:

normal_request_message

一样。

结果试了试:

#!/usr/bin/python
# -*- coding: UTF-8 -*-  
from flask import Flask, g, request, make_response
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic
# from wechat_sdk import WechatBaseCrypto
# from wechat_sdk.lib.crypto.crypto import WechatBaseCrypto
# from wechat_sdk.lib.crypto import WechatBaseCrypto
from wechat_sdk.exceptions import ParseError
app = Flask(__name__)
app.debug=True
wechatConf = WechatConf(
    token=‘aaaa’, 
    appid=’wx00000′,
    appsecret=’8310asjdlkjgjdgkldjgjglddd’,
    # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式
    encrypt_mode=’safe’,
    # 如果传入此值则必须保证同时传入 token, appid
    encoding_aes_key=’b7NCPES6jasshgasdfadfdsfd3eT6Z0EoSf2cLpt’
)
wechat = WechatBasic(conf=wechatConf)
# wechat = WechatBaseCrypto(conf=wechatConf)
@app.route("/")
def hello():
    return "Hello SIPEvents!"
@app.route(‘/wechat_auth’, methods=[‘GET’, ‘POST’])
def wechat_auth():
    signature = request.args.get(‘signature’, ”)
    timestamp = request.args.get(‘timestamp’, ”)
    nonce = request.args.get(‘nonce’, ”)
    echostr = request.args.get(‘echostr’, ”)
    app.logger.debug(‘signature=%s, timestamp=%s, nonce=%s, echostr=%s’, signature, timestamp, nonce, echostr)
    if wechat.check_signature(signature, timestamp, nonce):
    # if wechat.check_signature(signature, timestamp, nonce, echostr):
        app.logger.debug("wechat check_signature OK")
        if request.method == ‘GET’ :
            respStr = echostr
            app.logger.debug(‘respStr=%s’, respStr)
            return make_response(respStr)
        else :
            # for POST
            requestMethod = request.method
            app.logger.debug(‘requestMethod=%s’, requestMethod)
            # requestMethod=POST
            encryptedReqData = request.data
            app.logger.debug(‘encryptedReqData=%s’, encryptedReqData)
            # <xml>
            #     <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
            #     <Encrypt><![CDATA[6PBVvYed+IuFgEa4BuDeOaNwM3KLqv6uoWqQcSCY+SidbN2VBjWL+N88kp0GU2BvLXyzlvbGGOxvJnFIDRQCDAgBUBhk3YQMWJmR+bB3D5phuVEIFo1MoknxB4xsIi3wVQunlyljyFl43TCwCxIvBVxXeHsKSzYOxhFGL+2ZmelLp46WJRaNrrh8yLl2eK1pRCR09QAoNZISLUszfzlr4N9t4nnl8ZuQpYqEdWt4bH8xsqTRPd91TG6hSio/o46G9Ow2QA16j7l4q9HXV2fZEIdlSJma4Jepl7N9jBDwrjd4zi4MXwsJpQ0KBI3Q1LBojlipt8wk1xzuVzmyidkHzvDtfIa22ZTvEu4MDYdYa8BXRYk1EtGpW0eDCiF/NLOyQzJsFM1T7jGsxjrKUIcYPmLFbNW8qZEIEDkAhahbVCI=]]></Encrypt>
            # </xml>
            requestArgs = request.args
            app.logger.debug(‘requestArgs=%s’, requestArgs)
            # requestArgs=ImmutableMultiDict([(‘nonce’, u’1438950245′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’cb962992182efd9f94f09560b893b20106408e49′), (‘timestamp’, u’1471573757′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’dc3336e6f85053f3563802f4e7b5398e3930d017′)])
            try:
                decryptedReqData = wechat.conf.crypto.decrypt_message(encryptedReqData, signature, timestamp, nonce)
                app.logger.debug(‘decryptedReqData=%s’, decryptedReqData)
                app.logger.debug(‘decrypt post body data OK’)
                wechat.parse_data(decryptedReqData)
                # wechat.parse_data(encryptedReqData, signature, timestamp, nonce)
                app.logger.debug(‘parse post body data OK’)
            except ParseError:
                respStr = "parse post body failed"
                app.logger.debug(respStr)
                return wechat.response_text(respStr)
            messageId = wechat.message.id          # 对应于 XML 中的 MsgId
            messageTarget = wechat.message.target  # 对应于 XML 中的 ToUserName
            messageSource = wechat.message.source  # 对应于 XML 中的 FromUserName
            messageTime = wechat.message.time      # 对应于 XML 中的 CreateTime
            messageType = wechat.message.type      # 对应于 XML 中的 MsgType
            messageRaw = wechat.message.raw        # 原始 XML 文本,方便进行其他分析
            app.logger.debug(‘messageId=%s, messageTarget=%s, messageSource=%s, messageTime=%s, messageType=%s, messageRaw=%s’, messageId, messageTarget, messageSource, messageTime, messageType, messageRaw)
            if isinstance(wechat.message, TextMessage) :
                msgContent = wechat.message.content
                app.logger.debug(‘msgContent=%s’, msgContent)
                return wechat.response_text(msgContent)
            else :
                respStr = "Not Support type of POST"
                app.logger.debug(‘respStr=%s’, respStr)
                return wechat.response_text(respStr)
    else :
        app.logger.debug("wechat check_signature wrong")
        return wechat.response_text("wechat auth failed")
if __name__ == ‘__main__’:
    app.run(debug=True)

问题依旧。

参考:

jxtech/wechatpy: WeChat SDK for Python

去下载源码,看看其是如何解码的。

看起来:

/Users/crifan/dev/dev_src/Weixin/wechatpy-master/wechatpy/utils.py

中的:

class WeChatSigner(object):
    """WeChat data signer"""
    def __init__(selfdelimiter=b”):
        self._data []
        self._delimiter to_binary(delimiter)
    def add_data(self*args):
        """Add data to signer"""
        for data in args:
            self._data.append(to_binary(data))
    @property
    def signature(self):
        """Get data signature"""
        self._data.sort()
        str_to_sign self._delimiter.join(self._data)
        return hashlib.sha1(str_to_sign).hexdigest()

也和上面的代码,没多大区别

貌似是同样的解密和加密,生成SHA1的算法

此处,最终是把:

Flask服务器中的:

vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py

中的:

def _decrypt_message(self, msg, msg_signature, timestamp, nonce):

中的获取sh1的部分注释掉了:

        #signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt)
        #print ‘singnature=’,signature,’ msg_signature=’,msg_signature
        #if signature != msg_signature:
        #    raise ValidateSignatureError()

然后最后就可以正常解密了:

然后微信端输入内容,此处至少解密是没问题的

然后加了密返回内容,看起来也是没问题的:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-19 20:51:14 +0000] [2812] [INFO] Starting gunicorn 19.6.0
[2016-08-19 20:51:14 +0000] [2812] [INFO] Listening at: http://127.0.0.1:8080 (2812)
[2016-08-19 20:51:14 +0000] [2812] [INFO] Using worker: sync
[2016-08-19 20:51:14 +0000] [2817] [INFO] Booting worker with pid: 2817
[2016-08-19 20:51:14 +0000] [2818] [INFO] Booting worker with pid: 2818
[2016-08-19 20:51:14 +0000] [2819] [INFO] Booting worker with pid: 2819
[2016-08-19 20:51:14 +0000] [2824] [INFO] Booting worker with pid: 2824

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:49]:
signature=c8bc7e2cd5b828a9a267dbc5a66287fd40993634, timestamp=1471611078, nonce=1607653060, echostr=

<div–<——————————————————————————

tmp_list= [‘sipevents’, u’1471611078′, u’1607653060′]
after sort: tmp_list= [u’1471611078′, u’1607653060′, ‘sipevents’]
tmp_str= 14716110781607653060sipevents
tmp_str_encoded= 14716110781607653060sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7f8467727120>
tmp_str_hexdigest= c8bc7e2cd5b828a9a267dbc5a66287fd40993634
signature= c8bc7e2cd5b828a9a267dbc5a66287fd40993634
signature OK

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:53]:
wechat check_signature OK

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:61]:
requestMethod=POST

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:64]:
encryptedReqData=<xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==]]></Encrypt>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:71]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’1607653060′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’c8bc7e2cd5b828a9a267dbc5a66287fd40993634′), (‘timestamp’, u’1471611078′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’ee1632e53c230858db7966bce9eae509bb93bc8c’)])

<div–<——————————————————————————

timestamp= 1471611078
nonce= 1607653060
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==’)])
encrypt= 5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==
self.__token= sipevents
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:76]:
decryptedReqData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></FromUserName>
<CreateTime>1471611077</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好啊]]></Content>
<MsgId>6320521448554901304</MsgId>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:77]:
decrypt post body data OK

<div–<——————————————————————————

data= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==]]></Encrypt>
</xml>
self.conf.encrypt_mode= safe
timestamp= 1471611078
nonce= 1607653060
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==’)])
encrypt= 5RAqolinMihDIozBqEM6GCOJmAxfTF0L62V7l6oLgI/YKhTfeBwZlRVdZseuObbl2yiBD6aPCGApcw6bDWISUWe3EpE0D7kCXErBeuqiFVsCODsyit3iyHfkqXmnRD6xz7ZGNWIcMeRnS+DfNiIZnAwrvNbYbscBVC72EKW6knYzDWNBYm+HrxdvoiuvPqy7VhvpqMBmz3S33JJ0LAxnbOCbfHsC/RktYeouSKztDnW349MV0t5EhKawAP1mw87v7iQhp+cEfK9Dw52UjejAYKHr4l9b92YGfGHYdJ1ik2rjxVxgOphpkMReLpik43JcRvDsnLvrvRglJCKym2Hlt4Z4zkZ6N/TUi+GwfmUTl7FLCz9UQBlIFt0kdSVNFsiuFFNc0ZTPy4aQJfDqGFfqn1PlB/zk5vtomiy7WT8lYtFlU9eSvhLP8pCzVMmiQ6j2skPjPKG18CsSqEpNuBMvsA==
self.__token= sipevents
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:82]:
parse post body data OK

<div–<——————————————————————————

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 465, in format
    record.message = record.getMessage()
  File "/usr/local/lib/python2.7/logging/__init__.py", line 329, in getMessage
    msg = msg % self.args
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe4 in position 218: ordinal not in range(128)
Logged from file wechat_auth.py, line 95

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:99]:
msgContent=你好啊

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:101]:
resonseTextContent=<xml>
<Encrypt><![CDATA[Ci4FvnDqa01BPv2uMgXmsNnapGkOSSrMjasIVApFN07fp6JJ9t+rst9+ptL8UQNcogtq8an5A0BCGxzHhApMkrd1IlDuyoR8/q66WKafPYiaeQ4m2VIJZln1wAUpkZjE4MYpk9RPNx3c4EkM9Vk6a6RNwj5GirEJsaFGKYwWR/EnmDcjOLvmA1B2mGThrIP+46+CVAp4e1REVKwJtsJBk1RWwI+ymcYJ7Ucdj0SRVTx+vg4a7PM8O3AOsr6WlPeiNAFl+6oPhLZ8qRRKDeFzvm5AqQZ+ST0eBH0QbreJfahqGSytjzEaVlU8UBxOEcE1C482S5dg2DcuTlJVBKMX/43j+FBFBddo5t0VC+Xb80dJ4KEoqeRM8iaV+h+WSBkD7mMWV11/WTkBY7KdcvbisFYIE27tJIOlE+Mg31t/p7yOF/F8OrQKI/5ELh9DZALNWAeBP46xHWZlNLtF5ioorA==]]></Encrypt>
<MsgSignature><![CDATA[f1c6497e83a823ec6cc94eb3144addd2aa890cde]]></MsgSignature>
<TimeStamp>1471611078</TimeStamp>
<Nonce><![CDATA[1082767148]]></Nonce>
</xml>

<div–<——————————————————————————

即返回了:

<xml>
<Encrypt><![CDATA[Ci4FvnDqa01BPv2uMgXmsNnapGkOSSrMjasIVApFN07fp6JJ9t+rst9+ptL8UQNcogtq8an5A0BCGxzHhApMkrd1IlDuyoR8/q66WKafPYiaeQ4m2VIJZln1wAUpkZjE4MYpk9RPNx3c4EkM9Vk6a6RNwj5GirEJsaFGKYwWR/EnmDcjOLvmA1B2mGThrIP+46+CVAp4e1REVKwJtsJBk1RWwI+ymcYJ7Ucdj0SRVTx+vg4a7PM8O3AOsr6WlPeiNAFl+6oPhLZ8qRRKDeFzvm5AqQZ+ST0eBH0QbreJfahqGSytjzEaVlU8UBxOEcE1C482S5dg2DcuTlJVBKMX/43j+FBFBddo5t0VC+Xb80dJ4KEoqeRM8iaV+h+WSBkD7mMWV11/WTkBY7KdcvbisFYIE27tJIOlE+Mg31t/p7yOF/F8OrQKI/5ELh9DZALNWAeBP46xHWZlNLtF5ioorA==]]></Encrypt>
<MsgSignature><![CDATA[f1c6497e83a823ec6cc94eb3144addd2aa890cde]]></MsgSignature>
<TimeStamp>1471611078</TimeStamp>
<Nonce><![CDATA[1082767148]]></Nonce>
</xml>

看起来是正常的啊

但是微信端还是显示:

该公众号暂时无法提供服务,请稍后再试

又去试了试:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app                                                    
[2016-08-19 21:04:11 +0000] [2956] [INFO] Starting gunicorn 19.6.0
[2016-08-19 21:04:11 +0000] [2956] [INFO] Listening at: http://127.0.0.1:8080 (2956)
[2016-08-19 21:04:11 +0000] [2956] [INFO] Using worker: sync
[2016-08-19 21:04:11 +0000] [2961] [INFO] Booting worker with pid: 2961
[2016-08-19 21:04:11 +0000] [2964] [INFO] Booting worker with pid: 2964
[2016-08-19 21:04:12 +0000] [2967] [INFO] Booting worker with pid: 2967
[2016-08-19 21:04:12 +0000] [2969] [INFO] Booting worker with pid: 2969

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:49]:
signature=ec3dac8605aec26f5693f8229b017f8e9c31320f, timestamp=1471611861, nonce=1331490337, echostr=

<div–<——————————————————————————

tmp_list= [‘sipevents’, u’1471611861′, u’1331490337′]
after sort: tmp_list= [u’1331490337′, u’1471611861′, ‘sipevents’]
tmp_str= 13314903371471611861sipevents
tmp_str_encoded= 13314903371471611861sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7f42c21d1120>
tmp_str_hexdigest= ec3dac8605aec26f5693f8229b017f8e9c31320f
signature= ec3dac8605aec26f5693f8229b017f8e9c31320f
signature OK

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:53]:
wechat check_signature OK

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:61]:
requestMethod=POST

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:64]:
encryptedReqData=<xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=]]></Encrypt>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:71]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’1331490337′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’ec3dac8605aec26f5693f8229b017f8e9c31320f’), (‘timestamp’, u’1471611861′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’f506ba4659a772c2194ca49ea66e20eb17927960′)])

<div–<——————————————————————————

timestamp= 1471611861
nonce= 1331490337
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=’)])
encrypt= I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=
self.__token= sipevents
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:76]:
decryptedReqData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></FromUserName>
<CreateTime>1471611861</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[但是]]></Content>
<MsgId>6320524815809261568</MsgId>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:77]:
decrypt post body data OK

<div–<——————————————————————————

data= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=]]></Encrypt>
</xml>
self.conf.encrypt_mode= safe
timestamp= 1471611861
nonce= 1331490337
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=’)])
encrypt= I0OSKQ8g8KB/cFtnEvCKV6n521E1cfbkb6kEOhAstCcG+wWa+A7PbEHDI+21VoeR+LngfjfDbk/uY4JRpaPzga0umS7cliglIV97i0Zq9lCiZAFKIdRxBYWNPLCkKVMNiFerJChGJ8TH4Hl1yri47ipjsNjPv1Xu9xeUeXWEPumAFiTlHAiPtRKxvfKbtCiVsSJ4jiXXxbq2zixW502UQWXmXf3y5DtMJQ4GITQtEmMBF032NNA0prMzBGlMdJsATTHuD/WGHHUalKtfy/EXAy5a2lqOpUYYQmOwa9CJggm0/vDdy9Sjds/vSYqLeTsocQhP6n4Jw08mfo0EHzhYElhgq39WVgFMluzVhETG1z2z9NNsE1Zz96kwsEv8qymeiAFgciqbK66l5HaBLwpWjySrzE5vy0GfiP/WFIhiUew=
self.__token= sipevents
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:82]:
parse post body data OK

<div–<——————————————————————————

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 465, in format
    record.message = record.getMessage()
  File "/usr/local/lib/python2.7/logging/__init__.py", line 329, in getMessage
    msg = msg % self.args
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe4 in position 218: ordinal not in range(128)
Logged from file wechat_auth.py, line 95

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:99]:
msgContent=但是

<div–<——————————————————————————

text response= 
    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471611861</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[但是]]></Content>
    </xml>

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:101]:
resonseTextContent=<xml>
<Encrypt><![CDATA[zntVmgenZucDR/mnfhW3R14NOv/xCMsEYSdOMh5LU+iNTY04RjFLvH7/aykF/ob2eWsaw+94yEiHYg1TSLqXPiG8qjw0Y6BGDXGpDWr2X129TebxSIwLGlfTPVYl1dZbl69AeBXJ3rReSD3R5CDNc4XKqEI0mTL9Ips0WwkxEBXCsH+DzMJAXfykQAvAU9g4GuFKwU3c+UuzP555BM5//Ff9a11eqfsncV1kTbGKp7nyKYWwgiEHe3oPcPG6RXpjDKLQlgnOhfBtQ7bVmQjmHIjzTHYXef2r0efRtV/pxRTo9e9UGuAHGNVa7ZvzyogzjWku7qQnqmQuoJOOK3XaE2Fm0+UH1hXQx9ziy36YuDitzFQBpEPpl2kDRGGLqA8PoT4Z5Q8vHrfOGlazJZBOq3sRipeth0Ug8yftx/lei3Y=]]></Encrypt>
<MsgSignature><![CDATA[098b00c2fb816a4a69afbb575bfd1f9063863077]]></MsgSignature>
<TimeStamp>1471611861</TimeStamp>
<Nonce><![CDATA[1266049743]]></Nonce>
</xml>

<div–<——————————————————————————

看到了:

返回的,加了密之前的text的xml:

    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471611861</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[但是]]></Content>
    </xml>

搜:

wechat response_text 不工作

response_text  wechat

wechat 返回加了密的文本消息

参考:

wechat-sdk3版本中微信加密消息接口的小问题 · Issue #64 · doraemonext/wechat-python-sdk

和微信官网比:

被动回复用户消息 – 微信公众平台开发者文档

好像没有错误啊。

接入指引 – 微信公众平台开发者文档

也好像看起来一致,没问题啊。

然后,换了另外一种办法:

不去注释掉之前的:

vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/cryptos.py

中的:

def _decrypt_message(self, msg, msg_signature, timestamp, nonce):

中的get_sha1_signature那个部分:

        signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt)
        print ‘singnature=’,signature,’ msg_signature=’,msg_signature
        if signature != msg_signature:
            raise ValidateSignatureError()

而是,把中的获取sha1的函数get_sha1_signature改为,和

/Users/crifan/dev/dev_src/Weixin/wechat-python-sdk-master/wechat_sdk/basic.py

中的check_signature一样的逻辑:

即,去修改:

vim /root/Envs/SIPEvents/lib/python2.7/site-packages/wechat_sdk-0.6.4-py2.7.egg/wechat_sdk/lib/crypto/utils.py

为:

def get_sha1_signature(token, timestamp, nonce, encrypt):
        #sortlist = [token, timestamp, nonce, to_binary(encrypt)]
        sortlist = [token, timestamp, nonce]

即,去掉了encrypt,这个(要加密的)密文

则就是使得,在get_sha1_signature之后再去比较,就可以成功了。

即:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-19 21:25:44 +0000] [3178] [INFO] Starting gunicorn 19.6.0
[2016-08-19 21:25:44 +0000] [3178] [INFO] Listening at: http://127.0.0.1:8080 (3178)
[2016-08-19 21:25:44 +0000] [3178] [INFO] Using worker: sync
[2016-08-19 21:25:44 +0000] [3183] [INFO] Booting worker with pid: 3183
[2016-08-19 21:25:44 +0000] [3186] [INFO] Booting worker with pid: 3186
[2016-08-19 21:25:44 +0000] [3187] [INFO] Booting worker with pid: 3187
[2016-08-19 21:25:44 +0000] [3191] [INFO] Booting worker with pid: 3191

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:49]:
signature=2b305611c2bee0228d5abe720b119993a0863bad, timestamp=1471613148, nonce=2017910665, echostr=

<div–<——————————————————————————

tmp_list= [‘sipevents’, u’1471613148′, u’2017910665′]
after sort: tmp_list= [u’1471613148′, u’2017910665′, ‘sipevents’]
tmp_str= 14716131482017910665sipevents
tmp_str_encoded= 14716131482017910665sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7f158d6ec0d0>
tmp_str_hexdigest= 2b305611c2bee0228d5abe720b119993a0863bad
signature= 2b305611c2bee0228d5abe720b119993a0863bad
signature OK

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:53]:
wechat check_signature OK

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:61]:
requestMethod=POST

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:64]:
encryptedReqData=<xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==]]></Encrypt>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:71]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’2017910665′), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’), (‘signature’, u’2b305611c2bee0228d5abe720b119993a0863bad’), (‘timestamp’, u’1471613148′), (‘encrypt_type’, u’aes’), (‘msg_signature’, u’9efbedde0421e474d8e95a77d9ca0c3d332205d2′)])

<div–<——————————————————————————

timestamp= 1471613148
nonce= 2017910665
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==’)])
encrypt= wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==
self.__token= sipevents
singnature= 2b305611c2bee0228d5abe720b119993a0863bad  msg_signature= 2b305611c2bee0228d5abe720b119993a0863bad
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:76]:
decryptedReqData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></FromUserName>
<CreateTime>1471613148</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[好好好]]></Content>
<MsgId>6320530343432171852</MsgId>
</xml>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:77]:
decrypt post body data OK

<div–<——————————————————————————

data= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==]]></Encrypt>
</xml>
self.conf.encrypt_mode= safe
timestamp= 1471613148
nonce= 2017910665
textMsg= <xml>
    <ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
    <Encrypt><![CDATA[wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==]]></Encrypt>
</xml>
parsedTextMsg= OrderedDict([(u’xml’, OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==’)]))])
msg= OrderedDict([(u’ToUserName’, u’gh_ac090a9873a8′), (u’Encrypt’, u’wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==’)])
encrypt= wb3SSzSLgl76O0eUhAcsqeMXINMDWLD0M2q81uQs0sqCG82T4kUzGycmkaNVdmnu2hY32j/yVtR+4lK+Ewf/649l+r0+xM+lZbBH1plGOm9VDcrHmC1gOKU87K05i/CYSmHHSOYqflu41MvVDQf3TiKKatmCTgAELZ2Ub0tS5E8/oBkYa/vjym2iiqbjtmgSxfIw0ZW1P1glgBAepuakzI3AH4paaH6377LUhq4zl/NGuZgO7Iqv2a48K1BYx7x/Mvp7xTAAn6blpJcLcKF6F8QBgjSE9zhz/xdTCG0Ad2NPsfr2HV0w9GZbaQJ0EHRJU0Fk8d0W02Jsnu+olcV3IHA+262HCtQh1eBvVHEKZfoIGN9ucOUlOzNmEJhupaTDdWqAI2Dmq4Dt+5lV82LbvktL1QrL1+4AU88LiKHhwfExWF2BiIGzQdIJ+KDtJvalNSI+ZrwZ4UIQmqUkdsE2sg==
self.__token= sipevents
singnature= 2b305611c2bee0228d5abe720b119993a0863bad  msg_signature= 2b305611c2bee0228d5abe720b119993a0863bad
self.__id= wx906274ff0f9165dd

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:82]:
parse post body data OK

<div–<——————————————————————————

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/local/lib/python2.7/logging/__init__.py", line 465, in format
    record.message = record.getMessage()
  File "/usr/local/lib/python2.7/logging/__init__.py", line 329, in getMessage
    msg = msg % self.args
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 218: ordinal not in range(128)
Logged from file wechat_auth.py, line 95

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:99]:
msgContent=好好好

<div–<——————————————————————————

text response= 
    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471613148</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[好好好]]></Content>
    </xml>

<div–<——————————————————————————

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:101]:
resonseTextContent=<xml>
<Encrypt><![CDATA[+X7JrrxP+8cu+DvrZMmiPuUxHwOFZlohJWKlOXBOkAUGnaYxf05ZxG3VvtqPSlRrkMgc11xVsYHF587/GqUQZtv3xoNaksqJcyj2rDM/2Jn+a2sdL+9Qkwrp2S+SLU9rRaHry4RG0vg9GyX5NoCh479mw5zCez7vBqNXqAuBtR6VC1LcCvBl/kiXUgR9aD2aaJZGkKWB0DkUxfOyZUbgtETH6PTmR05fFZZZUanRLxabSDrgPx6gsqc96iSaXE91K0iVhMQBkOMtpUm5auHGgitlhevnGhWQeCjuu1vRXXdPq6v7r0FRbPTRS39hO67ed/zoFJNcMdCIVxtYJDyMeHP90bu3Z9uQy6T3hWIdmWG4+JvN47K3aF8QxCDPSf5celBpDBFBSugICjefY4+o2vJ7sf4AvOhk1zeucVb6QPVIAM6AikXl71pp1twoOY4eKiR0DtqRop70shPuNio7JQ==]]></Encrypt>
<MsgSignature><![CDATA[05353167e25b78f7e3c46d19d012ebe47cc75911]]></MsgSignature>
<TimeStamp>1471613148</TimeStamp>
<Nonce><![CDATA[1834786501]]></Nonce>
</xml>

<div–<——————————————————————————

中的:

singnature= 2b305611c2bee0228d5abe720b119993a0863bad  msg_signature= 2b305611c2bee0228d5abe720b119993a0863bad

但是,即使是这样,最后微信公众号那边,还是问题依旧:

回复文本,服务器还是出错,显示:

该公众号暂时无法提供服务,请稍后再试

去调试看看:

微信公众平台接口调试工具

然后去测试,发现是:

请求地址:
http://xxxx/wechat_auth
成功或失败:
Decrypt Fail!  
错误原因:
Compare signature error, the singnature WeiXin computed:cbc29f9cb6cba1291cc1bbd8fd1d166d627e3e2d, The use uf token:sipevents

搜:

Compare signature error, the singnature WeiXin

Compare signature error, the signature WeiXin

Decrypt Fail! Compare signature error, the singnature WeiXin  

微信JSSDK说明文档 – 微信公众平台开发者文档

微信 Decrypt Fail! Compare signature error

消息体签名及加解密使用报错 · Issue #140 · node-webot/wechat

测试消息回复竟然成这样了 – 微信源码专区 – 【9秒社团】-中国最大的移动开源技术社区

微信公众平台开发者中心安全模式消息体加解密实现 – 方倍工作室 – 博客园

转载请注明:在路上 » [未解决]用Python的微信SDK wechat-sdk中parse_data时出错:ValidateSignatureError

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.213 seconds, using 22.39MB memory