微信公众号开发-token验证

1.搭建python环境

1.1

安装python2.7版本以上(官方推荐),我这里安装3.11版本,记得勾上path选项(能省很多事)

1.2

安装web.py,libxml2,lxml

pip install web.py
pip install libxml2-python3
pip install lxml

2.编辑代码

# -*- coding: utf-8 -*-
# filename: main.py
import web
from handle import Handle

urls = (
    '/wx', 'Handle',
)

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
"""
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 = "*****"   # 自己定义的tokent

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            sha1.update(''.join(list).encode('utf-8'))  # 将py3中的字符串编码为bytes类型
            hashcode = sha1.hexdigest()
            print("handle/GET func: hashcode, signature:", hashcode, signature)
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception as e:
            print(e)


if __name__ == '__main__':
    pass

3.运行代码(端口80)

python main.py

4.公众号后台设置


官方文档