https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html
官方文档关键代码如下:
# -*- 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
补充:
1.服务器是阿里云的机器;
2.公众号是微信公众平台测试号;
3.参考的文档是:https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html#_1-4-%E5%BC%80%E5%8F%91%E8%80%85%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
问题原因:
官方文档(上面的参考文档)python代码有问题
解决:
另一份官方文档的说明是正确的,文档地址:https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html
本人测试可行的代码如下:
# -*- 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(v8)" signature = data.signature timestamp = data.timestamp nonce = data.nonce echostr = data.echostr token = "fkonsdrtmxckzoe15cyiibnwy2l6hduh" list = [token, timestamp, nonce] list.sort() sorted_str = ''.join(list) hash_obj = hashlib.sha1(sorted_str.encode('utf-8')) calc_signature = hash_obj.hexdigest() print("handle/GET func: calc_signature, signature: ", calc_signature, signature) if calc_signature == signature: return echostr else: return "" except Exception as Argument: print("Argument:", Argument) return Argument