(requestPayload: string, timestamp: number, secretId: string, secretKey: string)
| 46 | |
| 47 | // 生成腾讯云API签名 |
| 48 | async function createTencentSignature(requestPayload: string, timestamp: number, secretId: string, secretKey: string): Promise<string> { |
| 49 | const date = new Date(timestamp * 1000).toISOString().substring(0, 10); |
| 50 | |
| 51 | // 步骤1:拼接规范请求串 |
| 52 | const httpRequestMethod = "POST"; |
| 53 | const canonicalUri = "/"; |
| 54 | const canonicalQueryString = ""; |
| 55 | const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:tmt.tencentcloudapi.com\n`; |
| 56 | const signedHeaders = "content-type;host"; |
| 57 | |
| 58 | const hashedRequestPayload = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(requestPayload)); |
| 59 | const hashedPayloadHex = Array.from(new Uint8Array(hashedRequestPayload)) |
| 60 | .map(b => b.toString(16).padStart(2, '0')) |
| 61 | .join(''); |
| 62 | |
| 63 | const canonicalRequest = `${httpRequestMethod}\n${canonicalUri}\n${canonicalQueryString}\n${canonicalHeaders}\n${signedHeaders}\n${hashedPayloadHex}`; |
| 64 | |
| 65 | // 步骤2:拼接待签名字符串 |
| 66 | const algorithm = "TC3-HMAC-SHA256"; |
| 67 | const credentialScope = `${date}/tmt/tc3_request`; |
| 68 | |
| 69 | const hashedCanonicalRequest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonicalRequest)); |
| 70 | const hashedCanonicalRequestHex = Array.from(new Uint8Array(hashedCanonicalRequest)) |
| 71 | .map(b => b.toString(16).padStart(2, '0')) |
| 72 | .join(''); |
| 73 | |
| 74 | const stringToSign = `${algorithm}\n${timestamp}\n${credentialScope}\n${hashedCanonicalRequestHex}`; |
| 75 | |
| 76 | // 步骤3:计算签名 |
| 77 | const kDate = await generateHmacSignature(`TC3${secretKey}`, date); |
| 78 | const kService = await generateHmacSignature(kDate, "tmt"); |
| 79 | const kSigning = await generateHmacSignature(kService, "tc3_request"); |
| 80 | const signatureBuffer = await generateHmacSignature(kSigning, stringToSign); |
| 81 | const signature = arrayBufferToHex(signatureBuffer); |
| 82 | |
| 83 | // 步骤4:拼接 Authorization |
| 84 | const authorization = `${algorithm} Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; |
| 85 | |
| 86 | return authorization; |
| 87 | } |
| 88 | |
| 89 | async function tencent(message: any) { |
| 90 | try { |
no test coverage detected