腾讯云 API 会对每个请求进行身份验证,用户使用原生 API 接入需要使用安全凭证,经过特定的步骤对请求进行签名(Signature),每个请求都需要在公共参数中,指定该签名结果并以指定的方式和格式发送请求,以下内容主要介绍 API 接口文档参数以及V3签名方法。
API 文档
公共参数
公共参数是用于标识用户和接口签名的参数,API 接口文档上不会展示公共参数说明,但每次请求 API 均需要携带这些参数,才能正常发起请求。
签名方法
腾讯云支持V1、V3两种签名方式,推荐使用签名方法 V3计算签名,签名方法 V3(或被称为 TC3-HMAC-SHA256)相比签名方法 V1更安全,支持更大的请求包,且 POST JSON 格式,性能有一定提升。

使用签名方法 V3 时,公共参数需要统一放到 HTTP Header 请求头部中,如下表所示:
参数名称 | 类型 | 必选 | 描述 |
Action | String | 是 | HTTP 请求头:X-TC-Action。操作的接口名称,该字段取值为 ImageModeration。 |
Region | String | - | HTTP 请求头:X-TC-Region。地域参数,用来标识希望操作哪个地域的数据。取值参考接口文档中输入参数章节关于公共参数 Region 的说明。 注意:某些接口不需要传递该参数,接口文档中会对此特别说明,此时即使传递该参数也不会生效。 |
Timestamp | Integer | 是 | HTTP 请求头:X-TC-Timestamp。当前 UNIX 时间戳,可记录发起 API 请求的时间。例如 1529223702。 注意:如果与服务器时间相差超过5分钟,会引起签名过期错误。 |
Version | String | 是 | HTTP 请求头:X-TC-Version。操作的 API 的版本。取值参考接口文档中入参公共参数 Version 的说明。该字段取值为2020-12-29。 |
Authorization | String | 是 | HTTP 标准身份认证头部字段,例如:
TC3-HMAC-SHA256
Credential
=AKID****/Date/service/tc3_request,
SignedHeaders
=content-type
;host, Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024
其中,TC3-HMAC-SHA256:签名方法,目前固定取该值。 Credential:签名凭证。 AKID**** 是 SecretId。 Date 是 UTC 标准时间的日期,取值需要和公共参数 X-TC-Timestamp 换算的 UTC 标准时间日期一致。 service 为具体产品名,通常为域名前缀,例如域名 cvm.tencentcloudapi.com 意味着产品名是 cvm。本产品取值为 ims。 tc3_request 为固定字符串。 SignedHeaders:参与签名计算的头部信息,content-type 和 host 为必选头部。 Signature:签名摘要,计算过程请参见 签名版本 v3 签名过程。 |
Token | String | 否 | HTTP 请求头:X-TC-Token。即 安全凭证服务 所颁发的临时安全凭证中的 Token,使用时需要将 SecretID 和 SecretKey 的值替换为临时安全凭证中的 TmpSecretId 和 TmpSecretKey。使用长期密钥时不能设置此 Token 字段。 |
Language | String | 否 | HTTP 请求头:X-TC-Language。指定接口返回的语言,仅部分接口支持此参数。 取值:zh-CN,en-US。zh-CN 返回中文,en-US 返回英文。 |
云 API 支持 GET 和 POST 请求。
对于 GET 方法,只支持
Content-Type: application/x-www-form-urlencoded
协议格式。对于 POST 方法,目前支持
Content-Type: application/json
协议格式。示例代码
以下为 Java、Go、Python、PHP 示例 demo,填写密钥信息、接口入参即可调用,其他语言请参考 签名方法 V3-签名演示,签名演示是云服务器服务作为示例,实际调用时需要根据 API 接口文档填写参数。
import okhttp3.*;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.TimeZone;public class ImageModeration {public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取String secretId = "SecretId";String secretKey = "SecretKey";String service = "ims";String version = "2020-12-29";String action = "ImageModeration";String region = "ap-guangzhou";// 通过参数传递 BizType 和 FileUrlString bizType = "default";String fileUrl = "http://example.com/image.jpg"; // 替换为实际的文件 URLString body = createRequestBody(bizType, fileUrl);String resp = doRequest(secretId, secretKey, service, version, action, body, region);System.out.println(resp);}// singleton client for connection reuse and better performanceprivate static final OkHttpClient client = new OkHttpClient();public static String doRequest(String secretId, String secretKey,String service, String version, String action,String body, String region) throws IOException, NoSuchAlgorithmException, InvalidKeyException {Request request = buildRequest(secretId, secretKey, service, version, action, body, region);System.out.println(request.method() + " " + request.url());System.out.println(request.headers());System.out.println(body);Response response = client.newCall(request).execute();return response.body().string();}public static Request buildRequest(String secretId, String secretKey,String service, String version, String action,String body, String region) throws NoSuchAlgorithmException, InvalidKeyException {String host = "ims.tencentcloudapi.com";String endpoint = "https://" + host;String contentType = "application/json; charset=utf-8";String timestamp = String.valueOf(System.currentTimeMillis() / 1000);String auth = getAuth(secretId, secretKey, host, contentType, timestamp, body);return new Request.Builder().header("Host", host).header("X-TC-Timestamp", timestamp).header("X-TC-Version", version).header("X-TC-Action", action).header("X-TC-Region", region).header("X-TC-RequestClient", "SDK_JAVA_BAREBONE").header("Authorization", auth).url(endpoint).post(RequestBody.create(MediaType.parse(contentType), body)).build();}private static String getAuth(String secretId, String secretKey, String host, String contentType,String timestamp, String body) throws NoSuchAlgorithmException, InvalidKeyException {String canonicalUri = "/";String canonicalQueryString = "";String canonicalHeaders = "content-type:" + contentType + "\\nhost:" + host + "\\n";String signedHeaders = "content-type;host";String hashedRequestPayload = sha256Hex(body.getBytes(StandardCharsets.UTF_8));String canonicalRequest = "POST"+ "\\n"+ canonicalUri+ "\\n"+ canonicalQueryString+ "\\n"+ canonicalHeaders+ "\\n"+ signedHeaders+ "\\n"+ hashedRequestPayload;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");sdf.setTimeZone(TimeZone.getTimeZone("UTC"));String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));String service = host.split("\\\\.")[0];String credentialScope = date + "/" + service + "/" + "tc3_request";String hashedCanonicalRequest =sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));String stringToSign ="TC3-HMAC-SHA256\\n" + timestamp + "\\n" + credentialScope + "\\n" + hashedCanonicalRequest;byte[] secretDate = hmac256(("TC3" + secretKey).getBytes(StandardCharsets.UTF_8), date);byte[] secretService = hmac256(secretDate, service);byte[] secretSigning = hmac256(secretService, "tc3_request");String signature =printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();return "TC3-HMAC-SHA256 "+ "Credential="+ secretId+ "/"+ credentialScope+ ", "+ "SignedHeaders="+ signedHeaders+ ", "+ "Signature="+ signature;}public static String sha256Hex(byte[] b) throws NoSuchAlgorithmException {MessageDigest md;md = MessageDigest.getInstance("SHA-256");byte[] d = md.digest(b);return printHexBinary(d).toLowerCase();}private static final char[] hexCode = "0123456789ABCDEF".toCharArray();public static String printHexBinary(byte[] data) {StringBuilder r = new StringBuilder(data.length * 2);for (byte b : data) {r.append(hexCode[(b >> 4) & 0xF]);r.append(hexCode[(b & 0xF)]);}return r.toString();}public static byte[] hmac256(byte[] key, String msg) throws NoSuchAlgorithmException, InvalidKeyException {Mac mac = Mac.getInstance("HmacSHA256");SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());mac.init(secretKeySpec);return mac.doFinal(msg.getBytes(StandardCharsets.UTF_8));}// 创建请求体的方法public static String createRequestBody(String bizType, String fileUrl) {return String.format("{\\"BizType\\":\\"%s\\",\\"FileUrl\\":\\"%s\\"}", bizType, fileUrl);}}
package imsimport ("bytes""crypto/hmac""crypto/sha256""encoding/hex""encoding/json""fmt""log""net/http""strconv""strings""time")// 定义请求参数的结构体type Payload struct {BizType string `json:"BizType"`FileUrl string `json:"FileUrl"`}func sha256hex(s string) string {b := sha256.Sum256([]byte(s))return hex.EncodeToString(b[:])}func hmacsha256(s, key string) string {hashed := hmac.New(sha256.New, []byte(key))hashed.Write([]byte(s))return string(hashed.Sum(nil))}func main() {service := "ims"version := "2020-12-29"action := "ImageModeration"region := "ap-guangzhou"// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取secretId := "SecretId"secretKey := "SecretKey"host := "ims.tencentcloudapi.com"algorithm := "TC3-HMAC-SHA256"var timestamp = time.Now().Unix()// ************* 步骤 1:拼接规范请求串 *************httpRequestMethod := "POST"canonicalURI := "/"canonicalQueryString := ""contentType := "application/json; charset=utf-8"canonicalHeaders := fmt.Sprintf("content-type:%s\\nhost:%s\\nx-tc-action:%s\\n",contentType, host, strings.ToLower(action))signedHeaders := "content-type;host;x-tc-action"// 创建请求参数payloadData := Payload{BizType: "default",FileUrl: "http://example.com/image.jpg", // 这里替换为实际的文件 URL}// 将payload编码为 JSONpayloadBytes, err := json.Marshal(payloadData)if err != nil {log.Fatalf("Error marshaling payload: %v", err)}payload := string(payloadBytes)hashedRequestPayload := sha256hex(payload)canonicalRequest := fmt.Sprintf("%s\\n%s\\n%s\\n%s\\n%s\\n%s",httpRequestMethod,canonicalURI,canonicalQueryString,canonicalHeaders,signedHeaders,hashedRequestPayload)// log.Println(canonicalRequest)// ************* 步骤 2:拼接待签名字符串 *************date := time.Unix(timestamp, 0).UTC().Format("2006-01-02")credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, service)hashedCanonicalRequest := sha256hex(canonicalRequest)string2sign := fmt.Sprintf("%s\\n%d\\n%s\\n%s",algorithm,timestamp,credentialScope,hashedCanonicalRequest)// log.Println(string2sign)// ************* 步骤 3:计算签名 *************secretDate := hmacsha256(date, "TC3"+secretKey)secretService := hmacsha256(service, secretDate)secretSigning := hmacsha256("tc3_request", secretService)signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretSigning)))// log.Println(signature)// ************* 步骤 4:拼接 Authorization *************authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",algorithm,secretId,credentialScope,signedHeaders,signature)// log.Println(authorization)// ************* 步骤 5:构造并发起请求 *************url := "https://" + hosthttpRequest, _ := http.NewRequest("POST", url, bytes.NewReader(payloadBytes))httpRequest.Header = map[string][]string{"Host": {host},"X-TC-Action": {action},"X-TC-Version": {version},"X-TC-Timestamp": {strconv.FormatInt(timestamp, 10)},"Content-Type": {contentType},"Authorization": {authorization},}if region != "" {httpRequest.Header["X-TC-Region"] = []string{region}}httpClient := http.Client{}resp, err := httpClient.Do(httpRequest)if err != nil {log.Println(err)return}defer resp.Body.Close()body := &bytes.Buffer{}_, err = body.ReadFrom(resp.Body)if err != nil {log.Println(err)return}log.Println(body.String())}
#!/usr/bin/env python3# -*- coding:utf-8 -*-import hashlibimport hmacimport jsonimport timeimport datetimeimport requests# 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密# 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305# 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取secret_id = "SecretId"secret_key = "SecretKey"service = "ims"host = "ims.tencentcloudapi.com" # 接口域名action = "ImageModeration" # 接口名endpoint = "https://" + hostregion = "ap-guangzhou" # 地域version = "2020-12-29" # 版本为固定值algorithm = "TC3-HMAC-SHA256"def do_action(params):timestamp = int(time.time())day = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).strftime("%Y-%m-%d")# ************* 步骤 1:拼接规范请求串 *************http_request_method = "POST"canonical_url = "/"canonical_querystring = ""ct = "application/json; charset=utf-8"payload = json.dumps(params)canonical_headers = "content-type:%s\\nhost:%s\\n" % (ct, host)signed_headers = "content-type;host"hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()canonical_request = (http_request_method+ "\\n"+ canonical_url+ "\\n"+ canonical_querystring+ "\\n"+ canonical_headers+ "\\n"+ signed_headers+ "\\n"+ hashed_request_payload)# print(canonical_request)# ************* 步骤 2:拼接待签名字符串 *************credential_scope = day + "/" + service + "/" + "tc3_request"hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()string_to_sign = (algorithm+ "\\n"+ str(timestamp)+ "\\n"+ credential_scope+ "\\n"+ hashed_canonical_request)# print(string_to_sign)secret_date = sign(("TC3" + secret_key).encode("utf-8"), day)secret_service = sign(secret_date, service)secret_signing = sign(secret_service, "tc3_request")signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()# print(signature)# ************* 步骤 4:拼接 Authorization *************authorization = (algorithm+ " "+ "Credential="+ secret_id+ "/"+ credential_scope+ ", "+ "SignedHeaders="+ signed_headers+ ", "+ "Signature="+ signature)# print(authorization)headers = {"Authorization": authorization,"Content-Type": "application/json; charset=utf-8","Host": host,"X-TC-Action": action,"X-TC-Timestamp": str(timestamp),"X-TC-Version": version,"X-TC-Region": region,}# 发送请求resp = requests.post(url=endpoint, data=payload, headers=headers)return resp.text# 计算签名摘要函数def sign(key, msg):return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()if __name__ == "__main__":file_url = "http://example.com/image.jpg" # 这里替换为实际的文件 URLparams = {"BizType": "default", "FileUrl": file_url}resp = do_action(params)print(resp)
<?phpfunction sign($key, $msg) {return hash_hmac("sha256", $msg, $key, true);}function sendRequest($secret_id, $secret_key, $biz_type, $file_url, $req_region = "ap-guangzhou") {// 定义服务信息$service = "ims";$host = "ims.tencentcloudapi.com";$version = "2020-12-29";$action = "ImageModeration";$endpoint = "https://ims.tencentcloudapi.com";$algorithm = "TC3-HMAC-SHA256";$timestamp = time();$date = gmdate("Y-m-d", $timestamp);// 构造 payload$payload_data = ["BizType" => $biz_type,"FileUrl" => $file_url];$payload = json_encode($payload_data);// ************* 步骤 1:拼接规范请求串 *************$http_request_method = "POST";$canonical_uri = "/";$canonical_querystring = "";$ct = "application/json; charset=utf-8";$canonical_headers = "content-type:".$ct."\\nhost:".$host."\\nx-tc-action:".strtolower($action)."\\n";$signed_headers = "content-type;host;x-tc-action";$hashed_request_payload = hash("sha256", $payload);$canonical_request = "$http_request_method\\n$canonical_uri\\n$canonical_querystring\\n$canonical_headers\\n$signed_headers\\n$hashed_request_payload";// ************* 步骤 2:拼接待签名字符串 *************$credential_scope = "$date/$service/tc3_request";$hashed_canonical_request = hash("sha256", $canonical_request);$string_to_sign = "$algorithm\\n$timestamp\\n$credential_scope\\n$hashed_canonical_request";// ************* 步骤 3:计算签名 *************$secret_date = sign("TC3".$secret_key, $date);$secret_service = sign($secret_date, $service);$secret_signing = sign($secret_service, "tc3_request");$signature = hash_hmac("sha256", $string_to_sign, $secret_signing);// ************* 步骤 4:拼接 Authorization *************$authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";// ************* 步骤 5:构造并发起请求 *************$headers = ["Authorization" => $authorization,"Content-Type" => "application/json; charset=utf-8","Host" => $host,"X-TC-Action" => $action,"X-TC-Timestamp" => $timestamp,"X-TC-Version" => $version];if ($req_region) {$headers["X-TC-Region"] = $req_region;}try {$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $endpoint);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers));curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);if ($response === FALSE) {throw new Exception(curl_error($ch), curl_errno($ch));}curl_close($ch);return $response;} catch (Exception $err) {echo 'Curl error: ' . $err->getMessage();}}// 使用示例$biz_type = "default";$file_url = "http://example.com/image.jpg"; // 这里替换为实际的文件 URLtry {// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取$response = sendRequest("SecretId", "SecretKey", $biz_type, $file_url);echo $response;} catch (Exception $err) {echo $err->getMessage();}?>
签名失败
存在以下签名失败的错误码,请根据实际情况处理。
错误码 | 错误描述 |
AuthFailure.SignatureExpire | 签名过期。Timestamp 与服务器接收到请求的时间相差不得超过五分钟。 |
AuthFailure.SecretIdNotFound | |
AuthFailure.SignatureFailure | 签名错误。可能是签名计算错误,或者签名与实际发送的内容不相符合,也有可能是密钥 SecretKey 错误导致的。 |
AuthFailure.TokenFailure | 临时证书 Token 错误。 |
AuthFailure.InvalidSecretId | 密钥非法(不是云 API 密钥类型)。 |