微信公众号开发配置基本环境时需要服务器验证token,官方文档给出了验证token的步骤:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30# -*- 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
这段代码用Python2在服务器端进行token验证,由于我使用的是Python3,依照官方给出的这段验证代码,一直无法验证成功,调试发现:服务器获得的微信发过来的请求参数都没有问题,但是sha1加密后的字符串始终不对,应该是加密部分出了问题(Python2/3中hashlib应该是不兼容的)。查了一下(参考),果然,有两点需要注意:
在py2中不用对字符encode()编码,py3中必须encode()编码否则sha1.hexdigest()答案将不是你想要的。
在py3中 必须对map使用list 或tuple或循环输出才会得到正确答案。
修改Python3的token验证代码:1
2
3
4
5
6
7
8
9
10
11
12...
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
list(map(sha1.update,[x.encode() for x in lis ]))
hashcode = sha1.hexdigest()
# print("handle/GET func: hashcode, signature: ", hashcode, signature)
if hashcode == signature:
    return echostr
else:
    return ""
...