123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- /**
- * 腾讯云公共请求参数类
- * Created by PhpStorm.
- * User: phperstar
- * Date: 2019/11/11
- * Time: 10:54 AM
- */
- namespace Util\TencentCloud;
- class CommonRequest
- {
- /**
- * 生成公共请求参数header头
- * 官方文档地址: https://cloud.tencent.com/document/api/382/38767
- * @param string $region 区域名称
- * @param string $secretId 密钥
- * @param string $secretKey 密钥
- * @param string $service 服务名称
- * @param array $allParams 请求接口的所有参数
- */
- static function createCommonRequestHeader($region, $secretId, $secretKey, $service, $allParams, $host)
- {
- $time = time();
- $signature = self::createSignature($secretId, $secretKey, $allParams, $host, $service, $time);
- $returnData = [];
- $returnData['X-TC-Region'] = $region; // 地域参数
- $returnData['X-TC-Timestamp'] = $time; // 当前unix时间戳
- $returnData['Authorization'] = $signature;
- return $returnData;
- }
- /**
- * 生成签名
- * 官网文档地址: https://cloud.tencent.com/document/api/382/38768
- */
- static function createSignature($secretId, $secretKey, $allParams, $host, $service, $time)
- {
- // 拼接规范请求串
- $canonicalRequest = [
- 'HTTPRequestMethod' => 'POST', // HTTP请求方法
- 'CanonicalURI' => '/', // URL参数
- 'CanonicalQueryString' => '', //HTTP 查询字符串
- 'CanonicalHeaders' => 'content-type:application/json'."\n".'host:'.$host."\n", // 参与签名头部信息
- 'SignedHeaders' => 'content-type;host', // 参与签名的头部信息
- 'HashedRequestPayload' => strtolower(bin2hex(hash("SHA256", json_encode($allParams, JSON_UNESCAPED_UNICODE), true))),
- ];
- $canonicalRequestStr = '';
- $mark = "\n";
- $i = 1;
- foreach ($canonicalRequest as $key => $value){
- if($i == (count($canonicalRequest)) ){
- $mark = '';
- }
- $canonicalRequestStr .= $value . $mark ;
- $i++;
- }
- // 拼接待签名字符串
- $credentialScope = gmdate('Y-m-d', $time).'/'.$service.'/'.'tc3_request';
- $hashedCanonicalRequest = strtolower(bin2hex(hash("SHA256", $canonicalRequestStr, true)));
- $stringToSign = [
- 'algorithm' => 'TC3-HMAC-SHA256',
- 'timestamp' => $time,
- 'credentialScope' => $credentialScope,
- 'hashedCanonicalRequest' => $hashedCanonicalRequest,
- ];
- $stringToSignStr = '';
- $mark = "\n";
- $i = 1;
- foreach ($stringToSign as $key => $value){
- if($i == (count($stringToSign)) ){
- $mark = '';
- }
- $stringToSignStr .= $value . $mark ;
- $i++;
- }
- // 计算签名
- $secretDate = hash_hmac('SHA256', gmdate('Y-m-d', $time), 'TC3'.$secretKey, true);
- $secretService = hash_hmac('SHA256', $service, $secretDate, true);
- $secretSigning = hash_hmac('SHA256', 'tc3_request', $secretService, true);
- $signture = strtolower(hash_hmac('SHA256', $stringToSignStr, $secretSigning));
- // authorization
- $authorization = 'TC3-HMAC-SHA256 Credential='.$secretId.'/'.$credentialScope.', SignedHeaders=content-type;host, Signature='.$signture;
- return $authorization;
- }
- }
|