10 Public Number Development - Concern/Cancel Concern Events

Keywords: xml

When the user is concerned about and cancels the public number, he will push the event to the developer's URL.

If the server fails to respond within five seconds, the connection will be broken, and the request will be restarted, and a total of three tries will be repeated.

If the server can not guarantee that it can process and reply within five seconds, it can return the empty string directly. The server will not do any processing and will not initiate a retry.

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
</xml>

class WeChatHandler(WeChatBaseHandler):
    """WeChat access interface"""
    def get(self):
        """Developer Verification Interface"""
        echostr = self.get_argument("echostr")
        self.write(echostr)

    def post(self):
        """Receiving and Sending Message Interface"""
        req_xml = self.request.body
        req = xmltodict.parse(req_xml)['xml']
        msg_type = req.get("MsgType")
        if "text" == msg_type:
            resp = {
                "ToUserName":req.get("FromUserName", ""),
                "FromUserName":req.get("ToUserName", ""),
                "CreateTime":int(time.time()),
                "MsgType":"text",
                "Content":req.get("Content", "")
            }
        elif "voice" == msg_type:
            resp = {
                "ToUserName":req.get("FromUserName", ""),
                "FromUserName":req.get("ToUserName", ""),
                "CreateTime":int(time.time()),
                "MsgType":"text",
                "Content":req.get("Recognition", u"Unidentified")
            }
        elif "event" == msg_type:
            if "subscribe" == req.get("Event"):
                resp = {
                     "ToUserName":req.get("FromUserName", ""),
                    "FromUserName":req.get("ToUserName", ""),
                    "CreateTime":int(time.time()),
                    "MsgType":"text",
                    "Content":u"Thank you for your attention!"
                }
            else:
                resp = None
        else:
            resp = {
                "ToUserName":req.get("FromUserName", ""),
                "FromUserName":req.get("ToUserName", ""),
                "CreateTime":int(time.time()),
                "MsgType":"text",
                "Content":"I love you, itcast!"
            }
        if resp:
            resp_xml = xmltodict.unparse({"xml":resp})
        else:
            resp_xml = ""
        self.write(resp_xml)

Posted by zipp on Wed, 02 Oct 2019 23:26:57 -0700