2024年1月8日 21:52 by wst
公众号开发公众号开发中根据实际需求,要自动回复用户的消息。今天研究了下,实现方法如下。
@csrf_exempt
def receive(request):
"接收微信公众号消息"
if request.method == 'GET':
token = WX_TOKEN # 设置自定义的Token值
print("GETParameters:", request.GET)
signature = request.GET.get('signature')
timestamp = request.GET.get('timestamp')
nonce = request.GET.get('nonce')
echostr = request.GET.get('echostr')
tmp_list = [token, timestamp, nonce]
tmp_list.sort()
tmp_str = "".join(tmp_list).encode("utf-8")
sha1 = hashlib.sha1(tmp_str).hexdigest()
if sha1 == signature:
return HttpResponse(echostr)
else:
return HttpResponse('')
elif request.method == 'POST':
xml_data = request.body
xml_dic = xmltodict.parse(xml_data)
print("xml_data:", xml_data)
print("xml_dict:", xml_dic)
resp_dict = {
'ToUserName': xml_dic['xml']['FromUserName'],
'FromUserName': xml_dic['xml']['ToUserName'],
'CreateTime': int(time.time()),
'MsgType': 'text',
'Content': xml_dic['xml']['Content']
}
resp_xml = xmltodict.unparse({'xml': resp_dict})
return HttpResponse(resp_xml, content_type='text/xml')
只是列出了核心代码,看不懂老铁可以评论区留言。