Generate the ARTC authentication token that the AICallKit SDK requires to start a call.
How it works
The AICallKit SDK initiates AI agent calls from the client. Your app server must generate the authentication token and expose an endpoint for the client to fetch it before each call.
Procedure
To generate an ARTC authentication token, you need the App ID and AppKey of your ARTC application.
-
Go to the IMS console and click your AI agent to open its details page.
On the Basic Information tab, find the Workflow Configuration section and note the RTC App ID listed under ARTC application.
-
Click the RTC App ID to open the ApsaraVideo Live console and get the App ID and AppKey.
On the Application Management page, click your application name, go to the Basic Information tab, and copy the App ID and AppKey.
-
Use the App ID and AppKey to generate the ARTC authentication token. The token is computed as follows.
// 1. Concatenate the fields: AppID+AppKey+ChannelID+UserID+Nonce+Timestamp // 2. Use the SHA-256 algorithm to hash the concatenated string and generate the token. token = sha256(AppID+AppKey+ChannelId+UserID+Nonce+timestamp) // Example: AppID = "abc",AppKey="abckey",ChannelID="abcChannel",UserID="abcUser",Nonce="",Timestamp=1699423634 token = sha256("abcabckeyabcChannelabcUser1699423634") = "3c9ee8d9f8734f0b7560ed8022a0590659113955819724fc9345ab8eedf84f31"Parameter
Description
AppID
The ID and key of your ARTC application. They are generated when you create an ARTC application in the ApsaraVideo Live console. For more information, see Get application development parameters.
AppKey
ChannelId
The channel ID, which you define. The value must be a string and cannot be a Long. The channel ID can contain digits, uppercase letters, lowercase letters, hyphens (-), and underscores (_), and cannot exceed 64 characters in length. The host and co-streaming guests must use the same channel ID.
UserID
The user ID, which you define. The value must be a string and cannot be a Long. The user ID can contain digits, uppercase letters, lowercase letters, hyphens (-), and underscores (_), and cannot exceed 64 characters in length.
nonce
The nonce can be an empty string. We recommend leaving it empty.
timestamp
The expiration timestamp in seconds. We recommend setting the expiration to 24 hours. To set a 24-hour expiration, add 86,400 (24 * 60 * 60) to the current timestamp in seconds.
-
Server-side token generation: Generate a token on your app server with one of these samples.
Java
package com.example; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Calendar; import org.json.JSONObject; public class App { public static String createBase64Token(String appid, String appkey, String channelid, String userid) { // Calculate the expiration timestamp (24 hours from now) Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR_OF_DAY, 24); long timestamp = calendar.getTimeInMillis() / 1000; // Concatenate the strings String stringBuilder = appid + appkey + channelid + userid + timestamp; // Calculate the SHA-256 hash String token = sha256(stringBuilder); // Create the JSON object JSONObject base64tokenJson = new JSONObject(); base64tokenJson.put("appid", appid); base64tokenJson.put("channelid", channelid); base64tokenJson.put("userid", userid); base64tokenJson.put("nonce", ""); base64tokenJson.put("timestamp", timestamp); base64tokenJson.put("token", token); // Convert the JSON object to a string and encode it in Base64 String jsonStr = base64tokenJson.toString(); String base64token = Base64.getEncoder().encodeToString(jsonStr.getBytes(StandardCharsets.UTF_8)); return base64token; } private static String sha256(String input) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); StringBuilder hexString = new StringBuilder(); for (byte b : hash) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static void main(String[] args) { String appid = "your_appid"; String appkey = "your_appkey"; String channel_id = "your_channel_id"; String user_id = "your_user_id"; String base64token = createBase64Token(appid, appkey, channel_id, user_id); System.out.println("Base64 Token: " + base64token); } }Python
#!/usr/bin/env python # -*- coding: UTF-8 -*- import hashlib import datetime import time import base64 import json def create_base64_token(app_id, app_key, channel_id, user_id): expire = datetime.datetime.now() + datetime.timedelta(days=1) timestamp = int(time.mktime(expire.timetuple())) h = hashlib.sha256() h.update(str(app_id).encode('utf-8')) h.update(str(app_key).encode('utf-8')) h.update(str(channel_id).encode('utf-8')) h.update(str(user_id).encode('utf-8')) h.update(str(timestamp).encode('utf-8')) token = h.hexdigest() jsonToken = {'appid': str(app_id), 'channelid': str(channel_id), 'userid':str(user_id), 'nonce':'', 'timestamp':timestamp, 'token':str(token) } base64Token = base64.b64encode(json.dumps(jsonToken).encode()) return base64Token def main(): app_id = 'your_appid' app_key = 'your_appkey' channel_id = 'your_channel_id' user_id = 'your_user_id' base64Token = create_base64_token(app_id, app_key, channel_id, user_id) print(base64Token) if __name__ == '__main__': main()Go
package main import ( "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "time" ) func createBase64Token(appid, appkey, channelID, userID string) (string, error) { // Calculate the expiration timestamp (24 hours from now) timestamp := time.Now().Add(24 * time.Hour).Unix() // Concatenate the strings stringBuilder := appid + appkey + channelID + userID + fmt.Sprintf("%d", timestamp) // Calculate the SHA-256 hash hasher := sha256.New() hasher.Write([]byte(stringBuilder)) token := hasher.Sum(nil) // Convert the hash to a hexadecimal string using encoding/hex tokenHex := hex.EncodeToString(token) // Create the JSON object tokenJSON := map[string]interface{}{ "appid": appid, "channelid": channelID, "userid": userID, "nonce": "", "timestamp": timestamp, "token": tokenHex, } // Convert the JSON object to a string and encode it in Base64 jsonBytes, err := json.Marshal(tokenJSON) if err != nil { return "", err } base64Token := base64.StdEncoding.EncodeToString(jsonBytes) return base64Token, nil } func main() { appid := "your_appid" appkey := "your_appkey" channelID := "your_channel_id" userID := "your_user_id" token, err := createBase64Token(appid, appkey, channelID, userID) if err != nil { fmt.Println("Error creating token:", err) return } fmt.Println("Base64 Token:", token) } -
Client-side token generation: During development, you can generate tokens on the client instead of the server. Build a JSON object with the calculated token and five parameters: App ID, channel ID, nonce, user ID, and timestamp. Base64-encode the JSON object and pass it to the ARTC SDK. Include a UserName field for troubleshooting.
ImportantThis method embeds your AppKey and other sensitive information in the application. Use it for testing and development only. Do not use this method in production. Exposing your AppKey on the client side poses a serious security risk and can lead to its theft.
-