PHP
PHP生成腾讯云V3签名
PHP生成腾讯云V3签名
最近有个需求,需要对接腾讯云API,实在不想用那一坨SDK,决定对着签名说明,自己写V3签名流程,就拿文生图接口来做说明,下面直接贴出代码
/** * 创建Authorization * @param string $params * @param string $action * @return array */ function createAuthorizationHeader($params = "", $action = "") { //初始化参数 $secretId = ""; $secretKey = ""; $host = "aiart.tencentcloudapi.com"; $service = "aiart"; $version = "2022-12-29"; $region = "ap-guangzhou"; $timestamp = time(); $algorithm = "TC3-HMAC-SHA256"; //拼接规范请求串 $httpRequestMethod = "POST"; $canonicalUri = "/"; $canonicalQueryString = ""; $canonicalHeaders = "content-type:application/json; charset=utf-8\n" . "host:" . $host . "\n"; $signedHeaders = "content-type;host"; $hashedRequestPayload = hash("SHA256", $params); $canonicalRequest = $httpRequestMethod . "\n" . $canonicalUri . "\n" . $canonicalQueryString . "\n" . $canonicalHeaders . "\n" . $signedHeaders . "\n" . $hashedRequestPayload; //拼接待签名字符串 $date = gmdate("Y-m-d", $timestamp); $credentialScope = $date . "/" . $service . "/tc3_request"; $hashedCanonicalRequest = hash("SHA256", $canonicalRequest); $stringToSign = $algorithm . "\n" . $timestamp . "\n" . $credentialScope . "\n" . $hashedCanonicalRequest; //计算签名 $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); //拼接 Authorization $authorization = $algorithm . "Credential=" . $secretId . "/" . $credentialScope . ",SignedHeaders=content-type;host,Signature=" . $signature; //初始化请求头 $headers = array(); array_push($headers, "Authorization:" . $authorization); array_push($headers, "Content-Type: application/json; charset=utf-8"); array_push($headers, "Host:" . $host); array_push($headers, "X-TC-Region:" . $region); array_push($headers, "X-TC-Action:" . $action); array_push($headers, "X-TC-Version:" . $version); array_push($headers, "X-TC-Timestamp:" . $timestamp); array_push($headers, "X-TC-Language:zh-CN"); //返回 return $headers; } /** * curl请求 * @param $url * @param $mode * @param $data * @param $header * @return mixed|string */ function httpsRequest($url, $mode, $data, $header) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //HTTP Referer 来源地址 curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_HOST']); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); if ($mode == 'post') { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); } $data = curl_exec($curl); if (curl_errno($curl)) { return 'ERROR' . curl_error($curl); } curl_close($curl); $data = json_decode($data, true); return $data; }
调用直接使用如下
$data = textToImage("樱花");
这样便成功实现V3签名并调用接口。
0条评论