php 对接腾讯直播api的一些坑

本文使用查询流状态为例

 

授权时出现  The provided credentials could not be validated. Please check your signature is correct.

 在获取Authorization 时我们一般使用 json_encode() 将数组转为json

但是在 DescribeLiveStreamState 中没有参数就导致 json_encode([]) = string(2) "[]", 导致签名失败

这个坑我找了好久

下面是小编的demo  如有需要拷贝过去修改 action ,payload 既可

$secretKey = '';
$secretId = '';
$url = 'https://live.tencentcloudapi.com/';
$endpoint = 'live.tencentcloudapi.com';
$contentType =  'application/json';
$action = 'DescribeLiveStreamState';
$requestClient = 'SDK_PHP_3.0.627';
$timestamp = time();
$version = '2018-08-01';
$payload = [];


$payload = $payload ? json_encode($payload) : '{}';
$payloadHash = hash("SHA256", $payload);
$canonicalHeaders = "content-type:".$contentType."\n".
    "host:".$endpoint."\n";
$reqmethod = 'POST';
$canonicalUri = '/';
$canonicalQueryString = '';
$signedHeaders = "content-type;host";
$canonicalRequest = $reqmethod."\n".
    $canonicalUri."\n".
    $canonicalQueryString."\n".
    $canonicalHeaders."\n".
    $signedHeaders."\n".
    $payloadHash;
$algo = "TC3-HMAC-SHA256";
$date = gmdate("Y-m-d", $timestamp);
$service = explode(".", $endpoint)[0];
$credentialScope = $date."/".$service."/tc3_request";
$hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
$str2sign = $algo."\n".
    $timestamp."\n".
    $credentialScope."\n".
    $hashedCanonicalRequest;

$dateKey = hash_hmac("SHA256", $date, "TC3".$secretKey, true);
$serviceKey = hash_hmac("SHA256", $service, $dateKey, true);
$reqKey = hash_hmac("SHA256", "tc3_request", $serviceKey, true);
$signature = hash_hmac("SHA256", $str2sign, $reqKey);
$auth = $algo.
    " Credential=".$secretId."/".$credentialScope.
    ", SignedHeaders=content-type;host, Signature=".$signature;
$header =  [
    'Host: '.$endpoint,
    'X-TC-Action: '.$action,
    'X-TC-RequestClient: '.$requestClient,
    'X-TC-Timestamp: '.$timestamp,
    'X-TC-Version: '.$version,
    'Content-Type: '.$contentType,
    'Authorization: '.$auth
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
$output = curl_exec($curl);
curl_close($curl);
$res = json_decode($output,true);
print_r($res);

  

posted @ 2022-05-15 16:10  &权  阅读(298)  评论(0编辑  收藏  举报