Django开发微信公众平台

处理微信发来的信息,实际上就是处理xml的过程,先写xml工具类

# -*- coding:utf-8 -*-
from xml.dom import minidom
from Web.model.WeiXin import *

def get_attrvalue(node, attrname):
     return node.getAttribute(attrname) if node else ''

def get_nodevalue(node, index = 0):
    return node.childNodes[index].nodeValue if node else ''

def get_xmlnode(node,name):
    return node.getElementsByTagName(name) if node else []

def xml_to_string(xml):
    doc = minidom.parse(xml)
    return doc.toxml('UTF-8')

def get_xml_data(xml):
    doc = minidom.parseString(xml)
    root = doc.documentElement
    ToUserName = get_nodevalue(get_xmlnode(root,'ToUserName')[0]).encode('utf-8','ignore')
    FromUserName = get_nodevalue(get_xmlnode(root,'FromUserName')[0]).encode('utf-8','ignore')
    CreateTime = get_nodevalue(get_xmlnode(root,'CreateTime')[0]).encode('utf-8','ignore')
    MsgType = get_nodevalue(get_xmlnode(root,'MsgType')[0]).encode('utf-8','ignore')
    Content = get_nodevalue(get_xmlnode(root,'Content')[0]).encode('utf-8','ignore')
    MsgId = get_nodevalue(get_xmlnode(root,'MsgId')[0]).encode('utf-8','ignore')
    return WeiXin(ToUserName=ToUserName,FromUserName=FromUserName,CreateTime=CreateTime,MsgType=MsgType,Content=Content,MsgId=MsgId)

if __name__ =='__main__':
    xml = '<xml><ToUserName><![CDATA[gh_d740805e3dda]]></ToUserName><FromUserName><![CDATA[otvK9uEl5TdgfKaDtBhSb6CM49Xs]]></FromUserName><CreateTime>1426579233</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[哈哈]]></Content><MsgId>6127111151090981083</MsgId></xml>'
    print get_xml_data(xml)


封装一个微信xml实体类:

__author__ = 'zan'
class WeiXin():
    def __init__(self,ToUserName,FromUserName,CreateTime,MsgType,Content,MsgId):
        self.ToUserName= ToUserName
        self.FromUserName= FromUserName
        self.CreateTime= CreateTime
        self.MsgType= MsgType
        self.Content= Content
        self.MsgId= MsgId
    def __repr__(self):
        return 'ToUserName=%s,\n FromUserName=%s,\nCreateTime=%s,\n,MsgType=%s,\nContent=%s,\nMsgId=%s\n' %(self.ToUserName,self.FromUserName,self.CreateTime,self.MsgType,self.Content,self.MsgId)

最后解析xml,并返回xml

def weixin(requset):
    print 'requset.body=========%s'%requset.body
    if not requset.body.strip():
        return HttpResponse('error')
    weixinObj = get_xml_data(requset.body)
    print '解析之前 %s'%weixinObj
    toUserName = weixinObj.FromUserName;
    fromUserName = weixinObj.ToUserName;
    weixinObj.FromUserName = fromUserName;
    weixinObj.ToUserName = toUserName;
    print '解析之后 %s'%weixinObj
    result = '<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content><MsgId>%s</MsgId></xml>'%(weixinObj.ToUserName,weixinObj.FromUserName,weixinObj.CreateTime,weixinObj.MsgType,weixinObj.Content,weixinObj.MsgId)
    return HttpResponse(result)



Django开发微信公众平台

上一篇:微信js_sdk的分享功能的问题


下一篇:微信支付签名错误