注意点
- 官方示例是Pthon2 版本的,如果是Python3 版本需要有改动
- 验证成功返回 echostr 要是 数字格式的
公众号侧配置 (公众号后台 - 基本配置)
服务器侧配置
- 代码部分
官方示例(python2)
# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import web
class Handle(object):
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxx" #请按照公众平台官网\基本配置中信息填写
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print "handle/GET func: hashcode, signature: ", hashcode, signature
if hashcode == signature:
return echostr
else:
return ""
except Exception, Argument:
return Argument
python3 版本 (Django)
class WeChatTokenViewSet(viewsets.ViewSet):
def list(self, request):
try:
token = 'pTpKJrLR1qwaNat6mzUWXvVblHB1uZS3'
timestamp = request.query_params.get('timestamp')
nonce = request.query_params.get('nonce')
echostr = request.query_params.get('echostr')
signature = request.query_params.get('signature')
list = [token, timestamp, nonce]
list.sort()
temp = ''.join(list)
sha1 = hashlib.sha1(temp.encode('utf-8'))
hashcode = sha1.hexdigest()
print("handle/GET func: hashcode, signature: ", hashcode, signature)
if hashcode == signature:
return Response(int(echostr), status=status.HTTP_200_OK)
else:
print('微信Token校验失败')
return Response('', status=status.HTTP_200_OK)
except Exception as e:
print('微信Token解析失败', e)
return Response('', status=status.HTTP_200_OK)
完成Token 校验后
需要增加 IP 白名单 将服务器 IP 加入白名单
标签:sha1,return,Python,微信,list,hashcode,Token,echostr,signature From: https://www.cnblogs.com/wangshaojiea/p/16841778.html本文由一文多发运营工具平台 EaseWriting 发布