1.說(shuō)明
本文將上傳微信公眾號(hào)自動(dòng)回復(fù)消息的部分代碼,并作簡(jiǎn)要的說(shuō)明。在網(wǎng)上查了很多文章,里面的代碼多多少少都有問(wèn)題,所以這里上傳自己的代碼。
2.正文
1)創(chuàng)建Django項(xiàng)目(我將它命名為wechat)并創(chuàng)建APP(我將它命名為robot)
2)配置路由
/wechat/wechat/urls.py代碼如下:
from django.contrib import admin
from django.urls import path
import robot.views as rv
urlpatterns = [
path('admin/', admin.site.urls),
path('message/', rv.message),
]
3)創(chuàng)建xml模板文件,便于返回xml格式的結(jié)果
/wechat/templates/reply_text.xml代碼如下:
<xml>
<ToUserName><![CDATA[{{toUser}}]]></ToUserName>
<FromUserName><![CDATA[{{fromUser}}]]></FromUserName>
<CreateTime>{{createTime}}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{{content}}]]></Content>
</xml>
4)編寫(xiě)主要功能
/wechat/robot/views.py代碼如下:
from django.shortcuts import render
from django.http import HttpResponse
import hashlib
from xml.etree.ElementTree import fromstring
# Create your views here.
def message(request):
if request.method == 'GET':
if __verify(request.GET):
echostr = request.GET.get('echostr')
return HttpResponse(echostr)
else:
return HttpResponse("Access failed!")
elif request.method == 'POST':
try:
if not __verify(request.GET):
return HttpResponse("Access failed!")
# openid = request.GET.get('openid')
xml_data = fromstring(request.body)
from_user = xml_data.find('ToUserName').text
to_user = xml_data.find('FromUserName').text
create_time = xml_data.find('CreateTime').text
msg_type = xml_data.find('MsgType').text
# msg_id = xml_data.find('MsgId').text
if msg_type == 'text':
content = xml_data.find('Content').text
r_content = '[人工智障]:'+content
c = {'toUser': to_user, 'fromUser': from_user, 'createTime': create_time, 'content': r_content}
return render(request, 'reply_text.xml', context=c)
else:
pass
except Exception as e:
print(e)
def __verify(req_get):
token = '你的token'
signature = req_get.get('signature')
timestamp = req_get.get('timestamp')
nonce = req_get.get('nonce')
s = [timestamp, nonce, token]
s.sort() # 字典序排序
s = ''.join(s) # 將列表轉(zhuǎn)成字符串
sha1 = hashlib.sha1()
sha1.update(s.encode("utf8")) # 將s變量utf8編碼后加密
return sha1.hexdigest() == signature
在驗(yàn)證token這一步,我查了很多文章,沒(méi)一個(gè)能用的。后來(lái)發(fā)現(xiàn)問(wèn)題出在沒(méi)有進(jìn)行utf8編碼上,可能是因?yàn)槲矣玫氖荓inux,所以才會(huì)存在這個(gè)問(wèn)題。