用Django開發一個公眾號,實現的功能是用戶發一條文本消息,我直接返回回去
#代碼
我的代碼如下:
views.py
# 微信調用測試使用
class WeixinInterfaceView(View):
def get(self, request):
# 得到GET內容
signature = request.GET.get('signature', None)
timestamp = request.GET.get('timestamp', None)
nonce = request.GET.get('nonce', None)
echostr = request.GET.get('echostr', None)
# 自己的token
token = 'SvenWeng' # 這裡改寫你在微信公眾平台裡輸入的token
# 字典序排序
tmpList = [token, timestamp, nonce]
tmpList.sort()
tmpstr = '%s%s%s' % tuple(tmpList)
# sha1加密算法
tmpstr = hashlib.sha1(tmpstr).hexdigest()
# 如果是來自微信的請求,則回復echostr
if tmpstr == signature:
return render(request, 'get.html', {'str': echostr},
content_type='text/plain')
def post(self, request):
# str_xml = request.body.decode('utf-8') # use body to get raw data
str_xml = smart_str(request.body)
xml = etree.fromstring(str_xml) # 進行XML解析
toUserName = xml.find('ToUserName').text
fromUserName = xml.find('FromUserName').text
createTime = xml.find('CreateTime').text
msgType = xml.find('MsgType').text
content = xml.find('Content').text # 獲得用戶所輸入的內容
msgId = xml.find('MsgId').text
return render(request, 'reply_text.xml',
{'toUserName': toUserName,
'fromUserName': fromUserName,
'createTime': time.time(),
'msgType': msgType,
'content': content,
},
content_type='application/xml'
)
reply_text.xml
<xml>
<ToUserName><![CDATA[{{ toUserName }}]]></ToUserName>
<FromUserName><![CDATA[{{ fromUserName }}]]></FromUserName>
<CreateTime>{{ createTime }}</CreateTime>
<MsgType><![CDATA[{{ msgType }}]]></MsgType>
<Content><![CDATA[{{ content }}]]></Content>
</xml>
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^grzx/', include('MyBlog.urls', namespace='grzx')),
url(r'^', include('MyBlog.urls')),
url(r'^weixin/', csrf_exempt(WeixinInterfaceView.as_view())),
]
urlpatterns += staticfiles_urlpatterns()
我使用測試工具受到返回的結果是這樣的
<xml>
<ToUserName><![CDATA[diandianweizixun]]></ToUserName>
<FromUserName><![CDATA[wyb199026]]></FromUserName>
<CreateTime>1452836946.28</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[111111111]]></Content>
</xml>
我這個返回和微信的開發文檔要求是一樣的,為什麼我在公眾號上回復提示暫時無法服務?附上微信測試工具返回的結果
請求地址:http://www.ddhbblog.sinaapp.com/weixin/
Connection: keep-alive
Date: Fri, 15 Jan 2016 05:50:13 GMT
Transfer-Encoding: chunked
Set-Cookie: saeut=CkMPGlaYiJVgTmYsBOEuAg==; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/
Via: yq26.pyruntime
Server: nginx
Content-Type: application/xml
<xml>
<ToUserName>
<![CDATA[diandianweizixun]]>
</ToUserName>
<FromUserName>
<![CDATA[wyb199026]]>
</FromUserName>
<CreateTime>1452837013.23</CreateTime>
<MsgType>
<![CDATA[text]]>
</MsgType>
<Content>
<![CDATA[12312312]]>
</Content>
</xml>
求大神指點迷津
https://www.zhihu.com/question/34501713/answer/60667535