微信公众号开发之前需要配置服务器,配置服务器的时候要进行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
最后推荐一个可免费使用的内网穿透工具
欢迎关注微信公众号:【皮卡战记】
