火山引擎 通用文生图V2.0 PHP签名
函数
public function request($Service, $Version, $Region, $Host, $ContentType, $method, $query, $header, $action, $body)
{
$ak = $this->access_key;
$sk = $this->secret_key;
$credential = [
'accessKeyId' => $ak,
'secretKeyId' => $sk,
'service' => $Service,
'region' => $Region,
];
$query = array_merge($query, [
'Action' => $action,
'Version' => $Version
]);
ksort($query);
$requestParam = [
'body' => $body,
'host' => $Host,
'path' => '/',
'method' => $method,
'contentType' => $ContentType,
'date' => gmdate('Ymd\THis\Z'),
'query' => $query
];
$xDate = $requestParam['date'];
$shortXDate = substr($xDate, 0, 8);
$xContentSha256 = hash('sha256', $requestParam['body']);
$signResult = [
'Host' => $requestParam['host'],
'X-Content-Sha256' => $xContentSha256,
'X-Date' => $xDate,
'Content-Type' => $requestParam['contentType']
];
$signedHeaderStr = join(';', ['content-type', 'host', 'x-content-sha256', 'x-date']);
$canonicalRequestStr = join("\n", [
$requestParam['method'],
$requestParam['path'],
http_build_query($requestParam['query']),
join("\n", ['content-type:' . $requestParam['contentType'], 'host:' . $requestParam['host'], 'x-content-sha256:' . $xContentSha256, 'x-date:' . $xDate]),
'',
$signedHeaderStr,
$xContentSha256
]);
$hashedCanonicalRequest = hash("sha256", $canonicalRequestStr);
$credentialScope = join('/', [$shortXDate, $credential['region'], $credential['service'], 'request']);
$stringToSign = join("\n", ['HMAC-SHA256', $xDate, $credentialScope, $hashedCanonicalRequest]);
$kDate = hash_hmac("sha256", $shortXDate, $credential['secretKeyId'], true);
$kRegion = hash_hmac("sha256", $credential['region'], $kDate, true);
$kService = hash_hmac("sha256", $credential['service'], $kRegion, true);
$kSigning = hash_hmac("sha256", 'request', $kService, true);
$signature = hash_hmac("sha256", $stringToSign, $kSigning);
$signResult['Authorization'] = sprintf("HMAC-SHA256 Credential=%s, SignedHeaders=%s, Signature=%s", $credential['accessKeyId'] . '/' . $credentialScope, $signedHeaderStr, $signature);
$header = array_merge($header, $signResult);
$client = new GuzzleHttp\Client([
'base_uri' => 'https://' . $requestParam['host'],
'timeout' => 120.0,
'verify' => false,
]);
return $client->request($method, 'https://' . $requestParam['host'] . $requestParam['path'], [
'headers' => $header,
'query' => $requestParam['query'],
'body' => $requestParam['body']
]);
}
调用方法
request(
$Service = 'cv',
$Version = '2024-06-06',
$Region = 'cn-north-1',
$Host = 'visual.volcengineapi.com',
$ContentType = 'application/json',
$method = "POST",
$quert = [],
$header = [],
$action = 'HighAesGeneralV20L',
$requestBody
);