您的当前位置:首页正文

小程序配置消息推送

2024-11-10 来源:个人技术集锦

配置以上信息后,点击提交时, 服务器需要配置GET请求,同时验证签名,签名通过后,返回参数echo_str, 切忌: 一定转化为int类型;

python fastapi实现代码如下:

async def callback_file(request: Request):
    """
    文件内容检测
    :param request:
    :return:
    """
    data = await request.body()
    query_params = request.query_params
    query_dict = dict(query_params)
    signature = query_dict.get('signature')
    echo_str = query_dict.get('echostr')
    timestamp = query_dict.get('timestamp')
    nonce = query_dict.get('nonce')
    if validate_signature(signature, timestamp, nonce):
        logger.info(f"签名验证通过, echo_str: {echo_str}, data: {data}")
        # return int(nonce)
        return "success"
    else:
        # 签名验证失败,返回错误信息
        return {"error": "Invalid signature"}


def validate_signature(signature: str, timestamp: str, nonce: str) -> bool:
    """
    签名验证
    :param signature:
    :param timestamp:
    :param nonce:
    :return:
    """
    expected_signature = generate_signature(timestamp, nonce)
    return expected_signature == signature


def generate_signature(timestamp: str, nonce: str) -> str:
    """
    将token、timestamp、nonce进行字典序排序后拼接,并进行sha1加密
    :param timestamp:
    :param nonce:
    :return:
    """
    sort_list = [token, timestamp, nonce]
    sort_list.sort()
    sort_str = ''.join(sort_list)
    return hashlib.sha1(sort_str.encode()).hexdigest()

不同的场景下, 请求方式不一样。默认配置页面提交是GET请求。 其他的场景下是POST 请求;

Top