生成腾讯云的鉴权签名的 Python 代码,一直验证失败,有没有使用过的大佬帮忙看一下?

vps网友提供 05-05 讨论归档 8

根据文档提供的方法生成签名后,请求 API 一直返回 4100-验证失败。
有没有用过的大佬帮忙看看哪里出了问题?
参考的文档是这个: https://cloud.tencent.com/document/api/271/2053

谢谢

import requests
import os
import time
import random
import urllib.parse
import hashlib
import hmac
import base64


# HmacSHA256 加密算法
def Hmac_SHA256(string, key):
    string_b = bytes(string, encoding="utf-8")
    key_b = bytes(key, encoding="utf-8")
    signature = base64.b64encode(hmac.new(key=key_b, msg=string_b, digestmod=hashlib.sha256).digest())
    return signature.decode("utf-8")


# 请求 API
def req_api():
    # 生成通用参数
    nonce = str(random.randint(1, 65535))
    timestamp = str(int(time.time()))
    region = "sz"
    action = "TextSentiment"
    # 密钥
    TX_SecretKey = os.getenv("TX_SecretKey")
    TX_SecretId = os.getenv("TX_SecretId")
    # 请求方式
    method = "GET"

    # 组合字符串
    url = "wenzhi.api.qcloud.com/v2/index.php"
    params = {
        "Action": action,
        "Nonce": nonce,
        "Region": region,
        "SecretId": TX_SecretId,
        "SignatureMethod": "HmacSHA256",
        "Timestamp": timestamp,
    }
    params_string = urllib.parse.urlencode(params)
    src_string = "{}{}?{}".format(method, url, params_string)
    print(src_string)
    # 使用 hamxsha256+base64 生成签名
    sign_string = Hmac_SHA256(src_string, TX_SecretKey)
    print("Signature is {}".format(sign_string))

    url = "https://wenzhi.api.qcloud.com/v2/index.php"
    params = {
        "Action": action,
        "Nonce": nonce,
        "Region": region,
        "SecretId": TX_SecretId,
        "Timestamp": timestamp,
        "Signature": sign_string,
        "content": "双万兆服务器就是好,只是内存小点",
    }

    response = requests.get(url, params=params, verify=False)
    print(response.text)

if __name__ == '__main__':
    req_api()

本文由 vps网友提供,转载请注明出处

本文链接: https://www.vpsvsvps.com/discuss/a/1676471909094526976.html

标签:
zjp
05-05

前几个星期刚写过
注意文档示例里对参数排序是不区分公共参数和接口参数的,但我发现翻译接口需要分开排序。如果还是始终签名不对,可以试试

Nick2VIPUser
05-05

@zyxbcde 我去看下,谢谢哈

Nick2VIPUser
05-05

@GoLand 谢谢!确实漏掉了,我再试一下!

zyxbcde
05-05

腾讯云有 sdk 啊,好像用起来挺简单的。

GoLand
05-05



用文档里给的数据试了下。参数排序那步你就漏了。

Nick2VIPUser
05-05

@tencentcloud 好的,谢谢🙏

tencentcloud
05-05

楼主您好,收到您的反馈啦,如您方便,关于报错 4100-验证失败的问题,欢迎您登录官网控制台提交工单,会有专家为您高效解决。感谢您的反馈与支持。