tencent cloud

Feedback

Avatar aPaas API Calling Methods

Last updated: 2024-07-18 17:37:46
    This document mainly provides the method to generate the URL for calling the TCADH aPaas platform API, along with sample demos in common programming languages, including Golang, Java, C++, Python, and JavaScript.

    I. Obtaining Required Parameters

    For obtaining necessary parameters such as appkey and accesstoken, see the methods provided in the corresponding API documentation.

    II. Common Parameters

    Parameters
    Type
    Mandatory
    Description
    appkey
    string
    Yes
    The appkey obtained according to the methods provided in each API documentation.
    timestamp
    string
    Yes
    Request timestamp in seconds. The timestamp cannot differ from the current time by more than five minutes, otherwise, authentication will fail.
    requestid
    string
    No
    Only some APIs (such as creating a long connection channel for interactive Avatar) require this parameter. Please see the corresponding API documentation for the acquisition method.
    signature
    string
    Yes
    Request signature (see Signature Method for details).

    III. Signature Method

    When calling any aPaas API, you need to include common parameters such as the request signature in the URL as a QueryString.
    Request Parameter Signature Steps are as follows:
    1. The signature rules are as follows and described with an example (a pseudo-code for reference only):
    appkey = example_appkey
    accesstoken = example_accesstoken
    Domain name routing = https://api.example.com/v2/ivh/example_uri
    2. According to the corresponding API documentation, all required parameters except for signature should be sorted alphabetically to form the plaintext for generating the signature. The example only uses appkey and timestamp as parameters (please confirm the required parameters for each API in the relevant documentation). The concatenated and sorted string example is:
    appkey=example_appkey&timestamp=1717639699
    3. Use the accesstoken to perform HmacSha256 encryption on the signature string, and then encode it with base64:
    hashBytes = HmacSha256("appkey=example_appkey&timestamp=1717639699","example_accesstoken")
    signature = Base64Encode(hashBytes)
    4. The obtained signature value is:
    aCNWYzZdplxWVo+JsqzZc9+J9XrwWWITfX3eQpsLVno=
    5. Urlencode the signature value (this is mandatory, otherwise it may cause authentication failures), and then concatenate it to get the final request URL as follows:
    https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D

    IV. Demo

    The user only needs to fill in all common parameters required for accessing the corresponding API except the signature into the corresponding positions in the demo to generate the request signature and concatenate it into the complete URL for accessing the API.
    Golang
    Java
    C++
    Python
    JavaScript
    package main
    
    import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
    "net/url"
    "sort"
    "strconv"
    "time"
    )
    
    func GenSignature(signingContent string, accessToken string) string {
    
    // Calculate the HMAC-SHA256 value.
    h := hmac.New(sha256.New, []byte(accessToken))
    h.Write([]byte(signingContent))
    
    // Encode the HMAC-SHA256 value in Base64.
    hashInBase64 := base64.StdEncoding.EncodeToString(h.Sum(nil))
    
    // URL encode
    encodeSign := url.QueryEscape(hashInBase64)
    
    // Concatenate the signature.
    signature := "&signature=" + encodeSign
    
    return signature
    }
    
    func GenReqURL(parameter map[string]string, accessToken string, baseURL string) string {
    // Concatenate the string to be signed in alphabetical order.
    signingContent := ""
    pathKey := make([]string, 0, len(parameter))
    for k := range parameter {
    pathKey = append(pathKey, k)
    }
    sort.Strings(pathKey)
    for _, k := range pathKey {
    if signingContent != "" {
    signingContent += "&"
    }
    signingContent += k + "=" + parameter[k]
    }
    
    // Calculate the signature.
    signature := GenSignature(signingContent, accessToken)
    
    // Concatenate the complete URL for accessing the API.
    return baseURL + "?" + signingContent + signature
    }
    
    func main() {
    baseUrl := "https://api.example.com/v2/ivh/example_uri"
    accesstoken := "example_accesstoken"
    wssUrl := "wss://api.example.com/v2/ws/ivh/example_uri"
    // Example I (Accessing an API that requires appkey and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    parameter := map[string]string{
    "appkey": "example_appkey",
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // "timestamp": "1717639699",
    // It is recommended to use the following statement to generate the current timestamp:
    "timestamp": strconv.FormatInt(time.Now().Unix(), 10),
    }
    url1 := GenReqURL(parameter, accesstoken, baseUrl)
    // The output with the example timestamp should be as follows:
    // Example 1:https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D
    fmt.Println("Example 1:" + url1)
    
    /// Example II (Accessing an API that requires appkey, requestID and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    parameter = map[string]string{
    "appkey": "example_appkey",
    "requestid": "example_requestid",
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // "timestamp": "1717639699",
    // The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    "timestamp": strconv.FormatInt(time.Now().Unix(), 10),
    }
    url2 := GenReqURL(parameter, accesstoken, wssUrl)
    // The output with the example timestamp should be as follows:
    // Example 2:wss://api.example.com/v2/ws/ivh/example_uri?appkey=example_appkey&requestid=example_requestid&timestamp=1717639699&signature=QVenICk0VHtHGYZKXM6IC%2BW1CjZC1joSr%2Fx0gfKKYT4%3D
    fmt.Println("Example 2:" + url2)
    }
    
    import java.util.*;
    import java.util.stream.Collectors;
    import java.time.Instant;
    import java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.util.Base64;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.io.UnsupportedEncodingException;
    
    public class Presigned {
    
    public static String GenSignature(String signingContent, String accessToken) {
    try {
    // Calculate the HMAC-SHA256 value.
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(accessToken.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    
    String hashInBase64 = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(signingContent.getBytes(StandardCharsets.UTF_8)));
    
    // URL encode
    String encodeSign = URLEncoder.encode(hashInBase64, StandardCharsets.UTF_8.toString());
    
    // Concatenate the signature.
    String signature = "&signature=" + encodeSign;
    
    return signature;
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
    }
    }
    
    public static String GenReqURL(Map<String, String> parameter, String accessToken, String baseURL) {
    // Concatenate the string to be signed in alphabetical order.
    String signingContent = parameter.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .map(entry -> entry.getKey() + "=" + entry.getValue())
    .collect(Collectors.joining("&"));
    
    // Calculate the signature.
    String signature = GenSignature(signingContent, accessToken);
    
    // Concatenate the complete URL for accessing the API.
    return baseURL + "?" + signingContent + signature;
    }
    
    public static void main(String[] args) {
    String baseUrl = "https://api.example.com/v2/ivh/example_uri";
    String accesstoken = "example_accesstoken";
    String wssUrl = "wss://api.example.com/v2/ws/ivh/example_uri";
    
    // Example I (Accessing an API that requires appkey and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    Map<String, String> parameter = new TreeMap<>();
    parameter.put("appkey", "example_appkey");
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // parameter.put("timestamp", "1717639699");
    // It is recommended to use the following statement to generate the current timestamp:
    parameter.put("timestamp", String.valueOf(Instant.now().getEpochSecond()));
    String url = GenReqURL(parameter, accesstoken, baseUrl);
    // The output with the example timestamp should be as follows:
    // Example 1:https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D
    System.out.println("Example 1:" + url);
    
    /// Example II (Accessing an API that requires appkey, requestID and timestamp parameters):
    parameter.clear();
    parameter.put("appkey", "example_appkey");
    parameter.put("requestid", "example_requestid");
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // parameter.put("timestamp", "1717639699");
    // It is recommended to use the following statement to generate the current timestamp:
    parameter.put("timestamp", String.valueOf(Instant.now().getEpochSecond()));
    url = GenReqURL(parameter, accesstoken, wssUrl);
    // The output with the example timestamp should be as follows:
    // Example 2:wss://api.example.com/v2/ws/ivh/example_uri?appkey=example_appkey&requestid=example_requestid&timestamp=1717639699&signature=QVenICk0VHtHGYZKXM6IC%2BW1CjZC1joSr%2Fx0gfKKYT4%3D
    System.out.println("Example 2:" + url);
    }
    }
    
    #include<iostream>
    #include <map>
    #include<string>
    #include<vector>
    #include<algorithm>
    #include <ctime>
    #include <iomanip>
    #include <sstream>
    #include<openssl/hmac.h>
    #include<openssl/sha.h>
    
    using namespace std;
    
    static const string base64_chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";
    
    string url_encode(const string &value) {
    ostringstream escaped;
    escaped.fill('0');
    escaped<< hex;
    
    
    for (size_t i = 0; i< value.length(); ++i) {
    char c = value[i];
    if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
    escaped << c;
    } else {
    escaped<< uppercase;
    escaped << '%'<< setw(2)<< int((unsigned char) c);
    escaped<< nouppercase;
    }
    }
    
    
    return escaped.str();
    }
    
    
    string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
    string ret;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];
    while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;
    
    
    for(i = 0; (i <4) ; i++)
    ret += base64_chars[char_array_4[i]];
    i = 0;
    }
    }
    if (i)
    {
    for(j = i; j < 3; j++)
    char_array_3[j] = '\\0';
    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;
    for (j = 0; (j < i + 1); j++)
    ret += base64_chars[char_array_4[j]];
    while((i++ < 3))
    ret += '=';
    }
    return ret;
    }
    
    
    string GenSignature(const string& signingContent, const string& accessToken) {
    
    
    // Calculate the HMAC-SHA256 value.
    unsigned char hash[EVP_MAX_MD_SIZE];
    unsigned int hashLength;
    HMAC(EVP_sha256(), accessToken.c_str(), accessToken.length(), (unsigned char *) signingContent.c_str(), signingContent.length(), hash, &hashLength);
    
    
    // Encode the HMAC-SHA256 value in Base64.
    string hashInBase64 = base64_encode(hash, hashLength);
    
    
    // URL encode
    string encodeSign = url_encode(hashInBase64);
    
    
    // Concatenate the signature.
    string signature = "&signature=" + encodeSign;
    
    
    return signature;
    }
    
    
    string GenReqURL(const map<string, string>& parameter, const string& accessToken, const string& baseURL) {
    // Concatenate the string to be signed in alphabetical order.
    string signingContent;
    vector<string> pathKey;
    for (const auto& p : parameter) {
    pathKey.push_back(p.first);
    }
    sort(pathKey.begin(), pathKey.end());
    for (const auto& k : pathKey) {
    if (!signingContent.empty()) {
    signingContent += "&";
    }
    signingContent += k + "=" + parameter.at(k);
    }
    
    
    // Calculate the signature.
    string signature = GenSignature(signingContent, accessToken);
    
    
    // Concatenate the complete URL for accessing the API.
    return baseURL + "?" + signingContent + signature;
    }
    
    
    // During compilation, linking to the OpenSSL library is required. You can use the following command:
    // g++ presigned.cpp -o presigned -lcrypto
    
    
    int main() {
    string baseUrl = "https://api.example.com/v2/ivh/example_uri";
    string accesstoken = "example_accesstoken";
    string wssUrl = "wss://api.example.com/v2/ws/ivh/example_uri";
    
    
    // Example I (Accessing an API that requires appkey and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    map<string, string> parameter1 = {
    {"appkey", "example_appkey"},
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // {"timestamp" , "1717639699"},
    // It is recommended to use the following statement to generate the current timestamp:
    {"timestamp", to_string(time(NULL))}
    };
    string url = GenReqURL(parameter1, accesstoken, baseUrl);
    // The output with the example timestamp should be as follows:
    // Example 1:https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D
    cout << "Example 1:"<< url<< endl;
    
    
    /// Example II (Accessing an API that requires appkey, requestID and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    map<string, string> parameter2 = {
    {"appkey", "example_appkey"},
    {"requestid", "example_requestid"},
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // {"timestamp" , "1717639699"},
    // It is recommended to use the following statement to generate the current timestamp:
    {"timestamp", to_string(time(NULL))}
    };
    url = GenReqURL(parameter2, accesstoken, wssUrl);
    // The output with the example timestamp should be as follows:
    // Example 2:wss://api.example.com/v2/ws/ivh/example_uri?appkey=example_appkey&requestid=example_requestid&timestamp=1717639699&signature=QVenICk0VHtHGYZKXM6IC%2BW1CjZC1joSr%2Fx0gfKKYT4%3D
    cout << "Example 2:"<< url<< endl;
    
    
    return 0;
    }
    
    
    
    import hmac
    import hashlib
    import time
    import base64
    from urllib.parse import quote
    
    
    # Users can generate the timestamp within the function by providing appkey and accessToken to obtain all required common parameters and the corresponding signature for accessing the API.
    def GenSignature(signing_content, access_token):
    
    
    # Calculate the HMAC-SHA256 value.
    h = hmac.new(access_token.encode(), signing_content.encode(), hashlib.sha256)
    
    
    # Encode the HMAC-SHA256 value in Base64.
    hash_in_base64 = base64.b64encode(h.digest()).decode()
    
    
    # URL encode
    encode_sign = quote(hash_in_base64)
    
    
    # Concatenate the signature.
    signature = f"&signature={encode_sign}"
    
    
    return signature
    
    
    def GenReqURL(parameter, access_token, base_url):
    # Concatenate the string to be signed in alphabetical order.
    signing_content = '&'.join(f'{k}={parameter[k]}' for k in sorted(parameter.keys()))
    
    
    # Calculate the signature.
    signature = GenSignature(signing_content, access_token)
    
    
    # Concatenate the complete URL for accessing the API.
    return f'{base_url}?{signing_content}{signature}'
    
    
    
    
    def main():
    base_url = 'https://api.example.com/v2/ivh/example_uri'
    access_token = 'example_accesstoken'
    wss_url = 'wss://api.example.com/v2/ws/ivh/example_uri'
    
    
    # Example I (Accessing an API that requires appkey and timestamp parameters):
    # User fills in the required common parameters required to generate the signature as needed.
    parameter1 = {
    'appkey': 'example_appkey',
    # The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    # Example timestamp:
    # 'timestamp': '1717639699'
    # It is recommended to use the following statement to generate the current timestamp:
    'timestamp': int(time.time()) # Use the current timestamp (unit: second)
    }
    url1 = GenReqURL(parameter1, access_token, base_url)
    # The output with the example timestamp should be as follows:
    # Example 1:https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D
    print('Example 1:', url1)
    
    
    # Example II (Accessing an API that requires appkey, requestID and timestamp parameters):
    # User fills in the required common parameters required to generate the signature as needed.
    parameter2 = {
    'appkey': 'example_appkey',
    'requestid': 'example_requestid',
    # The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    # Example timestamp:
    # 'timestamp': '1717639699'
    # It is recommended to use the following statement to generate the current timestamp:
    'timestamp': int(time.time()) # Use the current timestamp (unit: second)
    }
    url2 = GenReqURL(parameter2, access_token, wss_url)
    # The output with the example timestamp should be as follows:
    # Example 2:wss://api.example.com/v2/ws/ivh/example_uri?appkey=example_appkey&requestid=example_requestid&timestamp=1717639699&signature=QVenICk0VHtHGYZKXM6IC%2BW1CjZC1joSr%2Fx0gfKKYT4%3D
    print('Example 2:', url2)
    
    
    if __name__ == '__main__':
    main()
    
    const crypto = require('crypto');
    // Users can generate the timestamp within the function by providing appkey and accessToken to obtain all required common parameters and the corresponding signature for accessing the API.
    function GenSignature(signingContent, accessToken) {
    // Calculate the HMAC-SHA256 value.
    const hmac = crypto.createHmac('sha256', accessToken);
    hmac.update(signingContent);
    
    
    // Encode the HMAC-SHA256 value in Base64.
    const hashInBase64 = hmac.digest('base64');
    
    
    // URL encode
    const encodeSign = encodeURIComponent(hashInBase64);
    
    
    // Concatenate the signature.
    const signature = `&signature=${encodeSign}`;
    
    
    return signature;
    }
    
    
    function GenReqURL(parameter, accessToken, baseURL) {
    // Concatenate the string to be signed in alphabetical order.
    let signingContent = '';
    const pathKey = Object.keys(parameter).sort();
    for (const k of pathKey) {
    if (signingContent !== '') {
    signingContent += '&';
    }
    signingContent += `${k}=${parameter[k]}`;
    }
    // Calculate the signature.
    const signature = GenSignature(signingContent, accessToken);
    // Concatenate the complete URL for accessing the API.
    return `${baseURL}?${signingContent}${signature}`;
    }
    
    
    
    
    function main() {
    const baseUrl = 'https://api.example.com/v2/ivh/example_uri';
    const accesstoken = 'example_accesstoken';
    const wssUrl = 'wss://api.example.com/v2/ws/ivh/example_uri';
    
    
    // Example I (Accessing an API that requires appkey and timestamp parameters):
    // User fills in the required common parameters required to generate the signature as needed.
    const parameter1 = {
    appkey: 'example_appkey',
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // timestamp: '1717639699',
    // It is recommended to use the following statement to generate the current timestamp:
    timestamp: Math.floor(Date.now() / 1000), // Use the current timestamp (unit: second)
    };
    const url1 = GenReqURL(parameter1, accesstoken, baseUrl);
    // The output with the example timestamp should be as follows:
    // Example 1:https://api.example.com/v2/ivh/example_uri?appkey=example_appkey&timestamp=1717639699&signature=aCNWYzZdplxWVo%2BJsqzZc9%2BJ9XrwWWITfX3eQpsLVno%3D
    console.log('Example 1:', url1);
    
    
    /// Example II (Accessing an API that requires appkey, requestID and timestamp parameters):
    const parameter2 = {
    appkey: 'example_appkey',
    requestid: 'example_requestid',
    /// The timestamp provided by the user should be in seconds, and the gap between it and the current time should not be more than five minutes.
    // Example timestamp:
    // timestamp: '1717639699',
    // It is recommended to use the following statement to generate the current timestamp:
    timestamp: Math.floor(Date.now() / 1000), // Use the current timestamp (unit: second)
    };
    const url2 = GenReqURL(parameter2, accesstoken, wssUrl);
    // The output with the example timestamp should be as follows:
    // Example 2:wss://api.example.com/v2/ws/ivh/example_uri?appkey=example_appkey&requestid=example_requestid&timestamp=1717639699&signature=QVenICk0VHtHGYZKXM6IC%2BW1CjZC1joSr%2Fx0gfKKYT4%3D
    console.log('Example 2:', url2);
    }
    
    
    main();
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support