def weixin(request): if request.method == 'GET': response=HttpResponse() try: signature = request.GET['signature'] timestamp = request.GET['timestamp'] nonce = request.GET['nonce'] echostr = request.GET['echostr'] except: pass response.write(echostr) return response elif request.method == 'POST': xml = request.raw_post_data doc = minidom.parseString(xml) root = doc.documentElement node = root.getElementsByTagName('MsgType')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data MsgType = rc node = root.getElementsByTagName('ToUserName')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data ToUserName = rc node = root.getElementsByTagName('FromUserName')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data FromUserName = rc node = root.getElementsByTagName('CreateTime')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data CreateTime = rc dbgFile.write(ToUserName+' '+FromUserName+' '+CreateTime+'\n') if MsgType == 'event': node = root.getElementsByTagName('Event')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data Event = str(rc) if Event == 'subscribe': #用戶關注公衆號觸發事件 elif Event == 'LOCATION': #location service node = root.getElementsByTagName('Latitude')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data Latitude = rc node = root.getElementsByTagName('Longitude')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data Longitude = rc node = root.getElementsByTagName('Precision')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data Precision = rc elif Event == 'CLICK': #微信菜單click事件 node = root.getElementsByTagName('EventKey')[0] rc = "" for n in node.childNodes: if n.nodeType in ( n.TEXT_NODE, n.CDATA_SECTION_NODE): rc = rc + n.data EventKey = rc if EventKey == 'V_INDUSTRYNEWS': #依據菜單設置的值進行判斷 elif MsgType == 'text': #用戶發送文本信息 elif MsgType == 'voice': #用戶發送語音信息 elif MsgType == 'image': #用戶發送圖片信息 elif MsgType == 'voice': #用戶發送語音信息
這段時間一直在搞微信,就將微信回調以及動做處理的東西整理了一下,分享出來。
node
上述代碼包括了微信回調以及部分動做的操做判斷。重構一下會更簡潔些,爲了能總體的查看微信的回調模式,就用了笨辦法直接全寫在了一塊兒。代碼裏包括了用戶關注、判斷用戶發送信息類別,菜單click事件判斷。可根據判斷結果對用戶進行回覆操做。python