全部產品
Search
文件中心

Intelligent Media Services:產生ARTC鑒權Token

更新時間:Aug 21, 2025

本文將為您介紹如何產生啟動通話所需的ARTC鑒權Token。

功能概述

AICallKit SDK提供的端側介面可直接發起智能體通話,該介面需要傳入一個鑒權Token。為此,您的商務服務器需要提供產生RTC鑒權Token的介面,以便您的用戶端在調用前提前訪問該介面擷取Token。

產生步驟

產生ARTC Token時,您需擷取音視頻ARTC應用的AppId和AppKey。

  1. 前往智能媒體控制台,單擊您建立好的智能體,進入智能體詳情頁面。

    image

  2. 單擊RTC AppID,前往ApsaraVideo for Live控制台,擷取AppId和AppKey。

    image

  3. 根據擷取的AppId和AppKey產生ARTC鑒權Token。Token的計算原理及方法如下,您可以根據如下方法計算Token。

    // 1. 拼接欄位:AppID+AppKey+ChannelID+UserID+Nonce+Timestamp
    // 2. 使用sha256Function Compute拼接欄位,產生token。
    token = sha256(AppID+AppKey+ChannelId+UserID+Nonce+timestamp)
    //樣本:
    AppID = "abc",AppKey="abckey",ChannelID="abcChannel",UserID="abcUser",Nonce="",Timestamp=1699423634
    token = sha256("abcabckeyabcChannelabcUser1699423634") = "3c9ee8d9f8734f0b7560ed8022a0590659113955819724fc9345ab8eedf84f31"

    參數名稱

    描述

    AppID

    即時音視頻應用ID和應用Key,在直播控制台建立即時音視頻應用後會自動產生,詳細請參見擷取應用開發參數

    AppKey

    ChannelID

    頻道ID,由使用者自訂,String類型,不能使用Long類型,支援數字、大小寫字母、短劃線(-)、底線(_),不超過64個字元。主播和連麥觀眾需使用同一個房間號。

    UserId

    使用者ID,由使用者自訂,String類型,不能使用Long類型,支援數字、大小寫字母、短劃線(-)、底線(_),長度不超過64個字元。

    Nonce

    Nonce字串可以為空白,這裡推薦為空白

    Timestamp

    到期時間戳記(秒級)。不能超過24小時,建議預設24小時。如果設定為24小時,則取當前秒數後再增加24*60*60。

    • 服務端產生Token:服務端產生Token範例程式碼如下:

      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)
      }
    • 用戶端內建Token:如果您在開發階段無法在AppServer上實現RTC Token的產生,可以選擇在用戶端本地進行簽發。此方式要求在您的用戶端內建RTC AppId及AppKey。產生用戶端內建的Token時,您需要將Token及計算所需的五個參數(AppID、ChannelID、Nonce、UserID和Timestamp)產生為JSON格式後進行Base 64編碼。隨後,請將產生的Base 64 Token通過字串形式傳遞至App側,同時在App側將Base 64 Token傳送至ARTC SDK,並附加用於排查問題的UserName欄位。

      重要

      該方法涉及內建的AppKey等敏感資訊,僅適用於體驗及開發階段,不得用於線上發布,以防止AppKey被盜取而導致安全事件的發生。