RoomKit
  • iOS : Objective-C
  • Android
  • Web
  • Flutter
  • Introduction
  • Demo app
  • Sample codes
  • Client SDKs
    • SDK downloads
    • Release notes
  • Getting started
    • Integration
    • Start a room
  • Guides
    • Customize room parameters
    • Customize the room UI
    • Listen for room callbacks
    • Screen rotation support
    • Screen sharing
    • Manage rooms with Education Cloud Service
    • Use server event callbacks
  • Server APIs
  • Error codes
  • Documentation
  • RoomKit
  • Server APIs
  • RoomKit Server APIs
  • Authentication
  • Get server access token

Get server access token

Last updated:2022-02-25 17:04

1 Description

Gets the Roomkit access token for authenticating server-side requests to RoomKit's REST APIs.

2 Request method and endpoint

  • Request method: POST

  • Request endpoint:

    Service environment Rate limit Endpoint
    Production 10 requests/second https://roomkit-api.zego.im/auth/get_access_token
  • Transmission protocol: HTTPS

3 Request parameters

Parameter Type Required Example Description
token String Yes "CIE7hNPK6Y55DeUJBSDrInP" An authentication token generated using the algorithm mentioned below.
secret_id Int Yes 12580 The Secret ID assigned to your project by ZEGO, which can be obtained from the RoomKit Admin Console.

How to generate the token :

tokenInfo ='{
    "ver": 1,
    "hash": "adfdkjakka1213aa",
    "nonce": "1b9c42gh1k0ax19y",
    "expired": 1531446463
}'
Note: You will need to construct the JSON data first, then convert it into a string.

token = base64(tokenInfo)

Parameters used to generate the token :

Parameter Type Required Description
ver Int Yes Version number, set to 1 by default.
hash String Yes C: hash = md5sum(sprintf("%u%s%s%u",secret_id, secret_key, nonce, expired))
Python: md5("%d%s%s %d"%("secret_id", "secret_key".lower(), "nonce", expire\_second)))
Golang: fmt.Sprintf("%x", md5.Sum([]byte( fmt.Sprintf("%d%s%s%d",secret_id, strings.ToLower(secret_key), "nonce", expire\_second))))

The final result of md5sum is a hex value of 32 bytes in lowercase.
nonce String Yes A random string of 8 bytes.
expired Int Yes The token's expiration time, a Unix timestamp in seconds. (e.g., time.now().unix() + 3600, where 3600 is the number of seconds the token remains valid)

Parameters used to generate the hash value :

Parameter Type Is It Required Description
secret_id Int Yes The Secret ID assigned to your project by ZEGO, which can be obtained from the RoomKit Admin Console.
secret_key String Yes The Secret Key assigned to your project by ZEGO, which can be obtained from the RoomKit Admin Console.
nonce String Yes A random string of 8 bytes. It must be the same as the nonce used to generate the token.
expired Int Yes The token's expiration time, a Unix timestamp in seconds. It must be the same as the expired parameter used to generate the token.

4 Sample request

{
    "token": "CIE7hNPK6Y55DeUJBSDrInP",
    "secret_id": 12580
}

5 Response parameters

Parameter Type Example Description
ret Object - The returned status of the request.
ret.code Int 0 The returned code.
ret.msg String "succeed" The returned message.
ret.version String "1.0.0" Version number.
data Object - The returned data of the request.
data.access_token String "access_token_value" The access_token returned by the RoomKit server.
data.expires_in Int 3600 The access_token's expiration time (in seconds).

6 Sample response

{
    "ret": {
        "code": 0,
        "msg": "succeed",
        "version": "1.0.0"
    },
    "data": {
        "access_token": "access_token",
        "expires_in": 7200
    }
}

7 Sample code

7.1 Sample code in Python

import base64
import time
import hashlib
import json
import requests

# secret_id: the Secret ID (Integer) assigned to your project by ZEGO. 
# secret_key: the Secret Key assigned to your project by ZEGO. 
def get_access_token(secret_id, secret_key):
    nonce = 'asdasdss'
    expire_second = int(time.mktime(time.localtime(time.time()))) + 3600
    hashSrc = ("%d%s%s%d" % (secret_id, secret_key.lower(), nonce, expire_second))
    hash = hashlib.md5(hashSrc.encode()).hexdigest()
    tokeninfo1 = {"ver": 1, "hash": hash, "nonce": nonce, "expired": expire_second}
    tokeninfo = json.dumps(tokeninfo1)
    token = base64.b64encode(tokeninfo.encode()).decode()
    url = 'https://roomkit-api.zego.im/auth/get_access_token'
    data = {
        "token": token,
        "secret_id": secret_id
    }
    r = requests.post(url=url, json=data)
    respondStr = r.content.decode()
    access_token = json.loads(respondStr)["data"]["access_token"]
    return access_token

7.2 Sample code in Golang

import (
    "bytes"
    "crypto/md5"
    "encoding/base64"
    "encoding/json"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "testing"
    "time"
)

// secretId: the Secret ID (an Integer) assigned to your project by ZEGO. 
// secretKey: the Secret Key (a String of 32 characters) assigned to your project by ZEGO. 
func GetAccessToken(secretId int, secretKey string) (accessToken string, err error) {
    nonce := "asdasdss"
    expired := time.Now().Unix() + 3600

    m := md5.New()
    m.Write([]byte(fmt.Sprintf("%d%s%s%d", secretId, strings.ToLower(secretKey), nonce, expired)))
    hash := fmt.Sprintf("%x", m.Sum(nil))

    var tokenInfo struct{
        Ver     int     `json:"ver"`
        Hash     string    `json:"hash"`
        Nonce     string    `json:"nonce"`
        Expired int     `json:"expired"`
    }
    tokenInfo.Hash = hash
    tokenInfo.Expired = int(expired)
    tokenInfo.Ver = 1
    tokenInfo.Nonce = nonce
    tokenInfoStr, _ := json.Marshal(tokenInfo)

    var reqStruct struct{
        SecretId     int     `json:"secret_id"`
        Token         string    `json:"token"`
    }
    reqStruct.SecretId = secretId
    reqStruct.Token = base64.StdEncoding.EncodeToString(tokenInfoStr)
    reqBody, _ := json.Marshal(reqStruct)

    req, err := http.NewRequest(http.MethodPost, "https://roomkit-api.zego.im/auth/get_access_token", bytes.NewBuffer(reqBody))
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    var resp *http.Response
    resp, err = client.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()

    var respBody []byte
    respBody, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        return
    }

    var ret struct{
        Ret struct{
            Code     int     `json:"code"`
            Msg     string    `json:"msg"`
            Version string    `json:"version"`
        }                    `json:"ret"`
        Data struct{
            AccessToken     string    `json:"access_token"`
            ExpiresIn        int     `json:"expires_in"`
        }
    }

    err = json.Unmarshal(respBody, &ret)
    if err != nil {
        return
    }
    if ret.Ret.Code != 0 {
        return "", errors.New(ret.Ret.Msg)
    }

    return ret.Data.AccessToken, nil
}

7.3 Sample code in Java

package demo;

import java.io.UnsupportedEncodingException;
import java.security.*; 
import java.util.*;

import com.alibaba.fastjson.*;

public class tokenTest {

    public static void main(String[] args) throws UnsupportedEncodingException {
        long current_time = System.currentTimeMillis()/1000; // Get the Unix timestamp of the current time
        long expired_time = current_time+3600; //The Unix timestamp of the expiration time in second

        String secretId = "1000000";  // The Secret ID (an Integer) assigned to your project by ZEGO. 
        String secretKey = "123456abcdefghijklmnopqrstuvwxyz";  // The Secret Key (a String of 32 characters) assigned to your project by ZEGO. 
        String nonce = "xxxxxxxxx"; // Random string

        // The information to be encrypted
        String originString = secretId + secretKey + nonce + Long.toString(expired_time);

        //Perform hash encryption
        String hashString = getMD5(originString);

        //Define a tokeninfo in json formaat
        LinkedHashMap  hashMap = new LinkedHashMap();

        hashMap.put("ver",1);
        hashMap.put("hash",hashString);
        hashMap.put("nonce",nonce);
        hashMap.put("expired",expired_time);
        String  tokeninfo= JSON.toJSONString(hashMap);

        //Base64 encryption
        final Base64.Encoder encoder = Base64.getEncoder();   
        final byte[] textByte = tokeninfo.getBytes("UTF-8");

        final String encodeToken = encoder.encodeToString(textByte);
        System.out.println("--token--:"+encodeToken);
    }

    //Hash encryption function
    public static String getMD5(String message) {
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");  // Create a MD5 object
            byte[] messageByte = message.getBytes("UTF-8");
            byte[] md5Byte = md.digest(messageByte);              // Get MD5 byte arrary, 16*8=128 bits
            md5 = bytesToHex(md5Byte);                            // Convert b to Hex string
        } catch (Exception e) {
            System.out.println("erro md5 creat!!!!");
            e.printStackTrace();
        }
        return md5;
    }

     // Convert byte[] to Hex string
    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
             if(num < 0) {
                 num += 256;
            }
            if(num < 16){
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString();
    }
}

/**
 * Finally, send the following request with your secret Id and the token generated above to obtain the "access_token" 
 * 
 * */

// curl -X POST https://roomkit-api.zego.im/auth/get_access_token -d '{"secretId": 1000000,"token": encode_token}'

7.4 Sample code in PHP

<?php

$current_time = time(); //Get the current time 
$expired_time = $current_time + 3600; //The expiration time, in seconds

$secretId = 1000000; // The Secret ID (an Integer) assigned to your project by ZEGO. 
$secretKey = "123456abcdefghijklmnopqrstuvwxyz"; // The Secret Key (a String of 32 characters) assigned to your project by ZEGO. 
$nonce = "xxxxxxxxx"; //Random string

// The information to be encrypted
$origin = $secretId . $secretKey . $nonce . $expired_time;

//Perform hash encryption
$hash = md5($origin);

$token = [
    'ver' => 1,
    'hash' => $hash,
    'nonce' => $nonce,
    'expired' => $expired_time
];
//Define a tokeninfo in json format
$token = json_encode($token);

//Base64 encryption
$encode_token = base64_encode($token);

echo $encode_token;


/**
  * Finally, send the following request with your secret Id and the token generated above to obtain the "access_token" 
 * 
 * */

// curl -X POST https://roomkit-api.zego.im/auth/get_access_token -d '{"secretId": 1000000,"token": encode_token}'
?>
Page Directory