PHP 混元模型Api 生成v3签名

public function buildSignature($secretId, $secretKey, $region, $action, $payload) {
    $host      = 'hunyuan.tencentcloudapi.com';
    $service   = "hunyuan";
    $version   = "2023-09-01";
    $timestamp = time();
    $algorithm = "TC3-HMAC-SHA256";

    // step 1: build canonical request string
    $httpRequestMethod = "POST";
    $canonicalUri = "/";
    $canonicalQueryString = "";
    $canonicalHeaders = implode("\n", [
        "content-type:application/json; charset=utf-8",
        "host:".$host,
        "x-tc-action:".strtolower($action),
        ""
    ]);
    $signedHeaders = implode(";", [
        "content-type",
        "host",
        "x-tc-action",
    ]);
    $hashedRequestPayload = hash("SHA256", $payload);
    $canonicalRequest = $httpRequestMethod."\n"
        .$canonicalUri."\n"
        .$canonicalQueryString."\n"
        .$canonicalHeaders."\n"
        .$signedHeaders."\n"
        .$hashedRequestPayload;

    // step 2: build string to sign
    $date = gmdate("Y-m-d", $timestamp);
    $credentialScope = $date."/".$service."/tc3_request";
    $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
    $stringToSign = $algorithm."\n"
        .$timestamp."\n"
        .$credentialScope."\n"
        .$hashedCanonicalRequest;

    // step 3: sign string
    $secretDate = hash_hmac("SHA256", $date, "TC3".$secretKey, true);
    $secretService = hash_hmac("SHA256", $service, $secretDate, true);
    $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true);
    $signature = hash_hmac("SHA256", $stringToSign, $secretSigning);

    // step 4: build authorization
    $authorization = $algorithm
        ." Credential=".$secretId."/".$credentialScope
        .", SignedHeaders=".$signedHeaders.", Signature=".$signature;

        // curl command
        $curl = "curl"
            .' -H "Authorization: '.$authorization.'"'
            .' -H "Content-Type: application/json; charset=utf-8"'
            .' -H "Host: '.$host.'"'
            .' -H "X-TC-Action: '.'ChatCompletions'.'"'
            .' -H "X-TC-Timestamp: '.$timestamp.'"'
            .' -H "X-TC-Version: '.$version.'"'
            .' -H "X-TC-Region: '.$region.'"'
            ." -d '".$payload."'"
            ." 'https://".$host."'";

        return $curl;
}
// 示例调用
$secretId = 'secretId';
$secretKey = 'secretKey';
$region = "ap-guangzhou";
$action = "ChatCompletions";
$payload = '{"Model":"hunyuan-pro","Messages":[{"Role":"user","Content":"计算1+1"}],"Stream":true}';

$curlCommand = buildSignature($secretId, $secretKey, $region, $action, $payload);
echo $curlCommand.PHP_EOL;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值