微信公众号Token验证


微信公众号开发之前需要配置服务器,配置服务器的时候要进行Token验证,具体方法可参考官方文档

关键步骤

main.py

# -*- 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

由于微信官方文档给的代码,是python2.0+版本的,而Python3.0+的哈希算法不一样,在验证Token的时候会出现hashcode 与 signature 不相等,还存在一些语法兼容问题,需要对代码进行修改。

# -*- 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 = "xxx" #请按照公众平台官网\基本配置中信息填写

            # 此处代码替换
            list = [token,timestamp,nonce]
            list.sort()
            sha1 = hashlib.sha1()
            sha1.update(list[0].encode("utf-8"))
            sha1.update(list[1].encode("utf-8"))
            sha1.update(list[2].encode("utf-8"))
            hashcode = sha1.hexdigest() #获取加密串

            print("handle/GET func: hashcode, signature: ", hashcode, signature)
            if hashcode == signature:
                return echostr
            else:
                print("不一致")
                return ""
        except Exception as Argument:
            return Argument

运行脚本

python main.py 80

如果报以下错误,是因为没有安装相关依赖

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import web
ImportError: No module named web

安装 web 依赖(未报错,则已经安装)

pip install web.py

如出现以下警告,是因为权限问题

WARNING: The directory '/Users/xxxxx/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

运行一下命令,修改权限再次安装

sudo chown root /Users/wenlincheng/Library/Caches/pip

最后运行脚本,在公众号后台基本设置中进行认证

python main.py 80

最后推荐一个可免费使用的内网穿透工具

http://www.ngrok.cc/


欢迎关注微信公众号:【皮卡战记】

皮卡战记

文章作者: Pikaman
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Pikaman !
评论
 上一篇
MySQL 5.7 修改用户密码 MySQL 5.7 修改用户密码
需要注意的是数据库user表中会有两个root用户,一个是本地登录用户,一个是远程登录用户,修改密码的时候需要区分。 # 切换到mysql库 use mysql; # 修改本地登录的root用户 update user set authe
2021-03-11
下一篇 
按照中文首字母排序Go语言实现 按照中文首字母排序Go语言实现
汉语转拼音库 go get -u github.com/mozillazg/go-pinyin结构体 // 结构体 type ProductListView struct { Id int `gorm:"pr
2020-05-20
  目录