python3:微信平台开发(1)-token验证

1、环境安装
python3.8

安装web.py
安装libxml2, libxslt, lxml python
安装libxml2参考
https://www.cnblogs.com/lizm166/p/8099245.html
https://www.cnblogs.com/marvelousone/p/12185582.html


pip install web.py lxml virtualenv

2、测试脚本

参考
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html
https://blog.csdn.net/HemingwayM/article/details/100019070
# -*- coding:utf-8 -*-
#!/usr/bin/env python3

import web

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

class Handle(object):
    def GET(self):
        return "hello, this is handle view"

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
运行代码:8081端口(注意云服务器的防火墙要放行8081端口)
 sudo python main.py 8081
在浏览器输入http://外网IP/wx

在这里插入图片描述


token验证

参考
https://www.cnblogs.com/milesma/p/12075263.html
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
#filename main.py
import web
from handle import Handle

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

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
#filename handle.py
import hashlib
import web


class Handle(object):

    def POST(self):
        pass

    # get方法,验证token
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "token success!"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "hello2020"  # 请按照公众平台官网\基本配置中信息填写,两个token保持一致

            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:
                return ""

        except Exception as Argument:
            return Argument

重新启动成功后(python main.py 80),点击提交按钮。若提示”token验证失败”, 请认真检查代码或网络链接等。若token验证成功,会自动返回基本配置的主页面,点击启动按钮

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值