分享

Python校验请求是否来自微信服务器

 小小明代码实体 2021-11-30

官方文档文档内容如下:

验证消息的确来自微信服务器

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:

参数描述
signature微信加密签名,signature结合了开发者填写的token参数和
请求中的timestamp参数、nonce参数。
timestamp时间戳
nonce随机数
echostr随机字符串

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:

1)将token、timestamp、nonce三个参数进行字典序排序 2)将三个参数字符串拼接成一个字符串进行sha1加密 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

检验signature的PHP示例代码:

private function checkSignature()
{
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];

    $token = TOKEN;
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );

    if( $tmpStr == $signature ){
        return true;
    }else{
        return false;
    }
}

可惜官网只提供了PHP的代码,我现在把它翻译成python代码:

def checkSignature(data):
    signature = data.get('signature')
    timestamp = data.get('timestamp')
    nonce = data.get("nonce")
    if not signature or not timestamp or not nonce:
        return False
    tmp_str = "".join(sorted([TOKEN, timestamp, nonce]))
    tmp_str = hashlib.sha1(tmp_str.encode('UTF-8')).hexdigest()
    if tmp_str == signature:
        return True
    else:
        return False

在Flask web框架中使用以下代码测试,已经测试通过:

@app.route('/test', methods=['GET'])
def test():
    if checkSignature(request.args):
        return "校验成功"
    else:
        return "校验失败"

不过我个人觉得这个校验运算也是一笔计算资源的开销,我用来公众号开发的测试服务器配置了nginx反向代理,python web程序本身只接收nginx服务器转发的请求,如果微信公众号提供了让nginx只接收微信服务器请求的方法就好了(当然也可能已经有现成的实现我不知道,望知道的大佬能够指导我一下)。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多