微信服务号开发接口管理之token配置失败

配置成功.png

基本原理

利用token, timestamp, nonce三个值,计算出一个hashcode,与前端参数signature进行对比。

如果后端的token值,与网页所填写的保持一致,那么计算出来的hashcode就会与前端参数signature相同,否则就会不同,从而达到验证的目的。

示意图(官方)

image.png

微信服务号配置.png

服务器地址(URL):是下面两个程序部署的服务器的地址,
注意如果80端口被占用,需要nginx进行转发。
http端口固定80,不可填写其他
https端口固定443,不可填写其他
令牌(Token):只需要与程序中的token保持一致即可,自定义。
EncodingAESKey:点击随机生成

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

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

if __name__ == '__main__':
    app = web.application(urls, globals())
    web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", 5003))

web的包依赖安装:推荐使用这个,conda没有和pip超时报错
pip3 install web.py -i https://mirrors.aliyun.com/pypi/simple/

# -*- 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 = "xxx12345678"

            list1 = [token, timestamp, nonce]
            list1.sort()
            list2 = [ x.encode('utf-8') for x in list1]
            sha1 = hashlib.sha1()
            [sha1.update(x) for x in list2]
            hashcode = sha1.hexdigest()
            print("handle/GET func: hashcode, signature: ", hashcode, signature)
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception as Argument:
            return Argument

参考文档
开始开发 / 接入指南 (qq.com)
基础能力 / 服务端能力 / 消息推送 (qq.com)
开发前必读 / 入门指引 (qq.com) 主要是这篇里的配置,一步一步来。
下载 这个是官方提供的demo代码,但是有问题,提供的python代码是python2.7版本的与Python3不兼容

官方demo代码.png

微信公众号开发中基本配置验证token失败的情况 - 知乎 (zhihu.com) 这个文章也是重要参考

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容