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

[已解决]用Python版微信SDK wechat-sdk添加处理关注和取消关注公众号的事件

Python crifan 2334浏览 0评论

之前已经处理了微信授权:

[已解决]微信授权登陆后获取用户信息后用Python解码

现在继续去处理,用户关注了微信公众号的事件,以及取消关注的事件

(1)接收事件推送 – 微信公众平台开发者文档

(2)接收事件推送 – 微信公众平台开发者文档

然后用代码:

@app.route(‘/sipevents’, methods=[‘GET’, ‘POST’])
def sipevents():
    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’oswxxxxxxxxxxxxxxxxxxxxxxVVY’), (‘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:
                respFailStr = u"消息体解析失败!"
                app.logger.debug("respFailStr=%s", respFailStr)
                respFailStrXml = wechat.response_text(respFailStr)
                app.logger.debug(‘respFailStrXml=%s’, respFailStrXml)
                return app.make_response(respFailStrXml)
            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)
            elif isinstance(wechat.message, EventMessage):
                # <xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
                # <FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
                # <CreateTime>1471832728</CreateTime>
                # <MsgType><![CDATA[event]]></MsgType>
                # <Event><![CDATA[subscribe]]></Event>
                # <EventKey><![CDATA[]]></EventKey>
                # </xml>
                # <xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
                # <FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
                # <CreateTime>1471830820</CreateTime>
                # <MsgType><![CDATA[event]]></MsgType>
                # <Event><![CDATA[unsubscribe]]></Event>
                # <EventKey><![CDATA[]]></EventKey>
                # </xml>
                if messageType == ‘subscribe’ :
                    respContent = u"欢迎 %s 来到金鸡日历!" % (messageSource)
                    app.logger.debug(‘respContent=%s’, respContent)
                    respContentXml = wechat.response_text(respContent)
                    app.logger.debug(‘respContentXml=%s’, respContentXml)
                    return app.make_response(respContentXml)
                elif messageType == ‘unsubscribe’ :
                    respContent = u"欢迎 %s 下次再来!" % (messageSource)
                    app.logger.debug(‘respContent=%s’, respContent)
                    respContentXml = wechat.response_text(respContent)
                    app.logger.debug(‘respContentXml=%s’, respContentXml)
                    return app.make_response(respContentXml)
                else:
                    respContent = u"暂时不支持此操作: %s" % (messageType)
                    app.logger.debug(‘respContent=%s’, respContent)
                    respContentXml = wechat.response_text(respContent)
                    app.logger.debug(‘respContentXml=%s’, respContentXml)
                    return app.make_response(respContentXml)
            else :
                respStr = u"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")

微信效果:

log:

(SIPEvents) ➜  SIPEvents gunicorn -w 4 -b 127.0.0.1:8080 sipevents:app
[2016-08-22 10:35:36 +0000] [1620] [INFO] Starting gunicorn 19.6.0
[2016-08-22 10:35:36 +0000] [1620] [INFO] Listening at: http://127.0.0.1:8080 (1620)
[2016-08-22 10:35:36 +0000] [1620] [INFO] Using worker: sync
[2016-08-22 10:35:36 +0000] [1625] [INFO] Booting worker with pid: 1625
[2016-08-22 10:35:36 +0000] [1626] [INFO] Booting worker with pid: 1626
[2016-08-22 10:35:36 +0000] [1630] [INFO] Booting worker with pid: 1630
[2016-08-22 10:35:36 +0000] [1632] [INFO] Booting worker with pid: 1632

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:132]:
signature=97f053a24b0542cdaec0cc33451d6505c1b5a080, timestamp=1471833348, nonce=1915076712, echostr=

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

tmp_list= [‘sipevents’, u’1471833348′, u’1915076712′]
after sort: tmp_list= [u’1471833348′, u’1915076712′, ‘sipevents’]
tmp_str= 14718333481915076712sipevents
tmp_str_encoded= 14718333481915076712sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7f0716235350>
tmp_str_hexdigest= 97f053a24b0542cdaec0cc33451d6505c1b5a080
signature= 97f053a24b0542cdaec0cc33451d6505c1b5a080
signature OK

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

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

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

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

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

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:147]:
requestData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833348</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[unsubscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:154]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’1915076712′), (‘timestamp’, u’1471833348′), (‘signature’, u’97f053a24b0542cdaec0cc33451d6505c1b5a080′), (‘openid’, u’oswxxxxxxxxxxxxxxxxxxxxxxVVY’)])

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

data= <xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833348</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[unsubscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>
self.conf.encrypt_mode= normal

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

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

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:181]:
messageId=0, messageTarget=gh_ac090a9873a8, messageSource=oswxxxxxxxxxxxxxxxxxxxxxxVVY, messageTime=1471833348, messageType=unsubscribe, messageRaw=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833348</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[unsubscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:213]:
respContent=欢迎 oswxxxxxxxxxxxxxxxxxxxxxxVVY 下次再来!

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

text response= 
    <xml>
    <ToUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471833348</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[欢迎 oswxxxxxxxxxxxxxxxxxxxxxxVVY 下次再来!]]></Content>
    </xml>

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:215]:
respContentXml=
    <xml>
    <ToUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471833348</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[欢迎 oswxxxxxxxxxxxxxxxxxxxxxxVVY 下次再来!]]></Content>
    </xml>

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:132]:
signature=3b63d7ecfdb7f841c8c4fbe69aaf9d895af4bd5e, timestamp=1471833397, nonce=2109017160, echostr=

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

tmp_list= [‘sipevents’, u’1471833397′, u’2109017160′]
after sort: tmp_list= [u’1471833397′, u’2109017160′, ‘sipevents’]
tmp_str= 14718333972109017160sipevents
tmp_str_encoded= 14718333972109017160sipevents
tmp_str_sha1= <sha1 HASH object @ 0x7f071621f490>
tmp_str_hexdigest= 3b63d7ecfdb7f841c8c4fbe69aaf9d895af4bd5e
signature= 3b63d7ecfdb7f841c8c4fbe69aaf9d895af4bd5e
signature OK

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

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

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

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

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

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:147]:
requestData=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833397</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:154]:
requestArgs=ImmutableMultiDict([(‘nonce’, u’2109017160′), (‘timestamp’, u’1471833397′), (‘signature’, u’3b63d7ecfdb7f841c8c4fbe69aaf9d895af4bd5e’), (‘openid’, u’oswxxxxxxxxxxxxxxxxxxxxxxVVY’)])

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

data= <xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833397</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>
self.conf.encrypt_mode= normal

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

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

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:181]:
messageId=0, messageTarget=gh_ac090a9873a8, messageSource=oswxxxxxxxxxxxxxxxxxxxxxxVVY, messageTime=1471833397, messageType=subscribe, messageRaw=<xml><ToUserName><![CDATA[gh_ac090a9873a8]]></ToUserName>
<FromUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></FromUserName>
<CreateTime>1471833397</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
<EventKey><![CDATA[]]></EventKey>
</xml>

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

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:207]:
respContent=欢迎 oswxxxxxxxxxxxxxxxxxxxxxxVVY 来到金鸡日历!

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

text response= 
    <xml>
    <ToUserName><![CDATA[oswxxxxxxxxxxxxxxxxxxxxxxVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471833397</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[欢迎 oswjmv4X0cCXcfkIwjoDfCkeTVVY 来到金鸡日历!]]></Content>
    </xml>

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

DEBUG in sipevents [/usr/share/nginx/html/SIPEvents/sipevents.py:209]:
respContentXml=
    <xml>
    <ToUserName><![CDATA[oswjmv4X0cCXcfkIwjoDfCkeTVVY]]></ToUserName>
    <FromUserName><![CDATA[gh_ac090a9873a8]]></FromUserName>
    <CreateTime>1471833397</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[欢迎 oswjmv4X0cCXcfkIwjoDfCkeTVVY 来到金鸡日历!]]></Content>
    </xml>

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

转载请注明:在路上 » [已解决]用Python版微信SDK wechat-sdk添加处理关注和取消关注公众号的事件

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.188 seconds, using 22.23MB memory