最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]尝试使用明文模式去测试微信的Python版的SDK wechat-sdk

Flask crifan 1181浏览 0评论

对于:

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

折腾了足够长时间,还是失败

最终是:

感觉是该sdk的加密有问题

-》signature计算的有问题

-》导致即使通过调整一些代码

返回给微信端,结果也还是因为加密出错,而报错

现在,去试试,改为明文模式

先去微信端的配置改为明文:

然后再去Flask的服务器的代码中去改为明文:

#!/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
from wechat_sdk.messages import (
    TextMessage,
    ImageMessage,
    VoiceMessage,
    VideoMessage,
    ShortVideoMessage,
    LinkMessage,
    LocationMessage,
    EventMessage,
    UnknownMessage
)
app = Flask(__name__)
app.debug=True
wechatConf = WechatConf(
    token=’yyy’, 
    appid=’xxx’,
    appsecret=’xxxx’,
    # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式
    #encrypt_mode=’safe’,
    encrypt_mode=’normal’,
    # 如果传入此值则必须保证同时传入 token, appid
    encoding_aes_key=’nnnnnn’
)
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
            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:
                # decryptedReqData = wechat.conf.crypto.decrypt_message(requestData, signature, timestamp, nonce)
                # app.logger.debug(‘decryptedReqData=%s’, decryptedReqData)
                # app.logger.debug(‘decrypt post body data OK’)
                # wechat.parse_data(decryptedReqData)
                #wechat.parse_data(decryptedReqData, signature, timestamp, nonce)
                #wechat.parse_data(requestData, signature, timestamp, nonce)
                wechat.parse_data(requestData)
                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(‘type(msgContent)=%s, msgContent=%s’, type(msgContent), msgContent)
                resonseTextContent = wechat.response_text(msgContent)
                app.logger.debug(‘resonseTextContent=%s’, resonseTextContent)
                return app.make_response(resonseTextContent)
            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)

然后运行后,微信端发送消息,

Flask服务器端对应的log为:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 wechat_auth:app
[2016-08-20 10:29:27 +0000] [9856] [INFO] Starting gunicorn 19.6.0
[2016-08-20 10:29:27 +0000] [9856] [INFO] Listening at: http://127.0.0.1:8080 (9856)
[2016-08-20 10:29:27 +0000] [9856] [INFO] Using worker: sync
[2016-08-20 10:29:27 +0000] [9861] [INFO] Booting worker with pid: 9861
[2016-08-20 10:29:27 +0000] [9862] [INFO] Booting worker with pid: 9862
[2016-08-20 10:29:27 +0000] [9866] [INFO] Booting worker with pid: 9866
[2016-08-20 10:29:27 +0000] [9868] [INFO] Booting worker with pid: 9868

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:50]:
signature=9034d157a1c8021510757b1717ec7df542641d9c, timestamp=1471660178, nonce=1258920617, echostr=

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

tmp_list= [‘sipevents’, u’1471660178′, u’1258920617′]
after sort: tmp_list= [u’1258920617′, u’1471660178′, ‘sipevents’]
tmp_str= 12589206171471660178sipevents
tmp_str_encoded= 12589206171471660178sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7fa63470f0d0>
tmp_str_hexdigest= 9034d157a1c8021510757b1717ec7df542641d9c
signature= 9034d157a1c8021510757b1717ec7df542641d9c
signature OK

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

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

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

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

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

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

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:65]:
requestData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></FromUserName>
<CreateTime>1471660178</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[明文是正常工作的]]></Content>
<MsgId>6320732335744110260</MsgId>
</xml>

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

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:72]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’1258920617′), (‘timestamp’, u’1471660178′), (‘signature’, u’9034d157a1c8021510757b1717ec7df542641d9c’), (‘openid’, u’oswjmv4X0cCXcfkIwjoDfCkeTVVY’)])

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

data= <xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></FromUserName>
<CreateTime>1471660178</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[明文是正常工作的]]></Content>
<MsgId>6320732335744110260</MsgId>
</xml>
self.conf.encrypt_mode= normal

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:84]:
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 0xe6 in position 218: ordinal not in range(128)
Logged from file wechat_auth.py, line 97

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:101]:
type(msgContent)=<type ‘unicode’>, msgContent=明文是正常工作的

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

text response= 
    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471660178</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[明文是正常工作的]]></Content>
    </xml>

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

DEBUG in wechat_auth [/usr/share/nginx/html/SIPEvents/wechat_auth.py:103]:
resonseTextContent=
    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471660178</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[明文是正常工作的]]></Content>
    </xml>

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

微信可以正常收到回复了:

-》

说明还是那个sdk加密有问题

算了。

暂时就先用明文模式。

以后有空再去折腾那个加密模式。

转载请注明:在路上 » [已解决]尝试使用明文模式去测试微信的Python版的SDK wechat-sdk

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
64 queries in 0.107 seconds, using 19.05MB memory