其他分享
首页 > 其他分享> > 微信服务器配置 token验证失败

微信服务器配置 token验证失败

作者:互联网

微信服务器配置 token验证失败

为微信公众号配置服务器时提示【token验证失败】

Author: Mon's_Works

注意事项

服务器要求

基本原理

在网页上提交配置时,网页会向URL发送若干参数,并期望服务器返回其中的一个。如果返回值正确,则配置成功,否则失败。

实现步骤

1.后端收到请求时,从请求中获取signature, echostr, timestamp, nonce等4个参数;

2.利用所得参数,根据官方提供的计算方法进行验证。理论上,如果只是测试,这个验证过程可以省略,直接返回结果。

3.返回echostr,格式为整数,而非字符串。如果以字符串格式返回echostr,也会提示【token验证失败】。

后端代码示例

官方示例采用Python 2,以下示例为Python 3,有所改动,注意甄别。

from fastapi import FastAPI
import hashlib


app = FastAPI()


@app.get("/")
async def root(signature: str = '', echostr: str = '', timestamp: str = '', nonce: str = ''):
    token = "与网页所填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()
    if hashcode == signature:
        print('successed')
        # 需返回数字,而非字符串
        return int(echostr)
    else:
        print('failed')
        return 0

 验证逻辑

基本原理

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

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

示意图(官方)

 

标签:sha1,验证,微信,list,token,echostr,signature,服务器
来源: https://www.cnblogs.com/monsino/p/16317152.html