文档中心
ServerSideAPI 服务端 API
文档中心
体验 App
SDK 中心
API 中心
常见问题
代码市场
进入控制台
立即注册
登录
中文站 English
  • 文档中心
  • 服务端 API
  • 后台房间信令接口
  • 获取AccessToken

服务端 API 版块于4月16日至5月15日升级维护,期间暂停信息更新,如有任何疑问,请联系ZEGO技术支持。

获取Access Token

更新时间:2025-04-16 11:00

1 基础概念

access_token 是接口的全局唯一票据,接入方调用各接口时都需使用 access_token。
开发者需要妥善保存,access_token 的存储至少要保留 512 个字符空间。
access_token 的有效期目前为 2 个小时,需定时刷新。

接入方可以使用 app_id 和 ServerSecret 调用本接口来获取 access_token。

请注意:

  1. app_id 和 ServerSecret 需要从 ZEGO 控制台 获取。
  2. 调用所有接口时均需使用 https 协议。

2 请求说明

http请求方式: POST/JSON,需使用https。

服务环境 调用频率限制 请求示例
国内正式环境 1次/秒 curl -X POST https://liveroom{APPID}-api.zego.im/cgi/token -d 'json_str'
海外正式环境 1次/秒 curl -X POST https://liveroom{APPID}-api.zegocloud.com/cgi/token -d 'json_str'
国内测试环境 1次/秒 curl -X POST https://test2-liveroom-api.zego.im/cgi/token -d 'json_str'
海外测试环境 1次/秒
  • 2020年12月9日及之后接入的用户,使用:
    curl -X POST https://liveroom-mctest.zego.im/cgi/token -d 'json_str'
  • 2020年12月9日之前接入的用户,保持使用原域名:
    curl -X POST https://test2-liveroom-api.zegocloud.com/cgi/token -d 'json_str'

json_str 内容如下:

{
    "version": 1,
    "seq": 1,
    "app_id": 11,
    "biz_type": 0,
    "token": "TOKEN"
}

3 参数说明

参数名 类型 是否必须 说明
version Int 是 协议版本号,默认填 1
seq Int 是 协议序列号,每次请求必须唯一;建议使用时间戳(时间戳是唯一的)
app_id Int 是 第三方用户唯一凭证
biz_type Int 否 App 业务类型;0:live,2:rtv。(可以不填,默认为0)
token String 是 即构后台服务认证凭证

token 生成规则说明:

tokenInfo = '{
    "ver": 1,
    "hash": "adfdkjakka1213aa",
    "nonce": "1934892311",
    "expired": 1531393997 //单位:秒
}'
注意这里要先构造 JSON,再转成字符串

token = base64(tokenInfo)

tokenInfo 字段说明:

参数名 类型 说明
ver Int 版本号;默认填 1
hash String hash = md5sum(sprintf("%u%s%s%u",app_id,server_app_secret,nonce,expired)); md5sum最终结果为32字节小写hex编码
nonce String 随机串,16 bytes
expired Int token 失效时间,Unix 时间戳,单位:秒

tokenInfo 中的 hash 字段生成规则说明:

参数名 类型 说明
app_id Int App 唯一标识
server_app_secret String App 唯一凭证密钥,16 bytes,从 ZEGO 控制台 获取到的ServerSecret。

4 返回说明

正常情况下,会返回下述 JSON 数据包给调用方:

{
    "code": 0,
    "data": {
        "access_token": "c205dytwQTd4ZlZjSjBLTXY0V3FzYUtBY1Q9ZEo0eGFJcEt3WVBKSlFGeXh5aGZITjJWYnlBcT0",
        "expires_in": 7200
    },
    "message": "success"
}

返回参数说明:

参数名 类型 说明
code Int 返回码
message String 操作结果描述
access_token String 获取到的凭证
expires_in Int 凭证有效时间,单位:秒

错误时会返回错误码等信息,JSON 数据包示例如下(该示例为 server_app_secret 无效错误):

{
    "code": 40005,
    "message": "appsecret错误"
}

5 获取token示例代码

5.1 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; //获取当前unix时间戳
        long expired_time = current_time+7200; //过期unix时间戳,单位:秒

        String appid = "000000000";  // 这里填写各自分配的appid
        String serverSecret = "00000000000000000000000000";  // 这里填写对应的ServerSecret
        String nonce = "xxxxxxxxx"; //自定义的随机数
        //System.out.println(current_time);
        //System.out.println(expired_time);

        // 待加密信息
        String originString = appid + serverSecret + nonce + Long.toString(expired_time);
        //待加密的信息
        //System.out.println(originString);
        //hash加密
        String hashString = getMD5(originString);
        //加密后的hash
        System.out.println("--hashString--:"+hashString);

        //定义一个tokeninfo json 
        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);
        //System.out.println("----------hashMap--------"+hashMap);
        //System.out.println("----------111--------"+tokeninfo);

        //Base64 加密
        final Base64.Encoder encoder = Base64.getEncoder();   //加密
        //final Base64.Decoder decoder = Base64.getDecoder();   //解密
        final byte[] textByte = tokeninfo.getBytes("UTF-8");

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

    //生成MD5
    public static String getMD5(String message) {
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");  // 创建一个md5算法对象
            byte[] messageByte = message.getBytes("UTF-8");
            byte[] md5Byte = md.digest(messageByte);              // 获得MD5字节数组,16*8=128位
            md5 = bytesToHex(md5Byte);                            // 转换为16进制字符串
        } catch (Exception e) {
            System.out.println("erro md5 creat!!!!");
            e.printStackTrace();
        }
        return md5;
    }

     // 二进制转十六进制
    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();
    }
}

/**
 * 最后,将生成的Token复制到以下curl -X POST替换掉其中的token,修改对应的app_id,然后取请求得到正确的"access_token"
 * 
 * */

// curl -X POST https://liveroom{app_id}-api.zego.im/cgi/token -d '{"version": 1,"seq": 1,"app_id": 000000000,"biz_type": 0,"token": token}'

5.2 php示例代码

<?php

$current_time = time(); //获取当前时间
$expired_time = $current_time + 7200; //过期时间,单位:秒

$app_id = 000000000; // Int类型,这里填写各自分配的appid
$server_app_secret = "00000000000000000000000000"; // 这里填写对应的ServerSecret
$nonce = "xxxxxxxxx"; //自定义的随机数

// 待加密信息
$origin = $app_id . $server_app_secret . $nonce . $expired_time;

//hash加密
$hash = md5($origin);

$token = [
    'ver' => 1,
    'hash' => $hash,
    'nonce' => $nonce,
    'expired' => $expired_time
];
//定义一个tokeninfo json 
$token = json_encode($token);

//Base64 加密
$encode_token = base64_encode($token);

echo $encode_token;

/**
 * 最后,将生成的Token复制到以下curl -X POST替换掉其中的token,修改对应的app_id,然后取请求得到正确的"access_token"
 * 
 * */

// curl -X POST https://liveroom{app_id}-api.zego.im/cgi/token -d '{"version": 1,"seq": 1,"app_id": 000000000,"biz_type": 0,"token": token}'

5.3 python示例代码

import time
import hashlib
import base64
import json


def buildToken():

    current_time = int(time.time()) # 当前unix时间戳
    expired_time = int(current_time + 7200) # 过期unix时间戳,单位:秒
    print("当前时间: " + str(int(current_time)))
    print("过期时间: " + str(int(expired_time)))

    appid = '123456789' # 分配给客户的appid
    serverSecret = '12345678123456781234567812345678' # 这里填写对应的ServerSecret
    nonce = '1234567812345678' # 建议使用随机串

    # 待加密信息
    aStr = appid + serverSecret + nonce + str(expired_time)
    print("未hash的串: " + aStr)
    # hash加密
    md5Obj = hashlib.md5()
    md5Obj.update(aStr.encode(encoding='utf-8'))
    # hashStr后的字符串
    hashStr = md5Obj.hexdigest()
    print("hashStr后的字符串: " + hashStr)

    # tokeninfo
    tokenInfo = {'ver':1,'hash':hashStr,"nonce":nonce,"expired":expired_time}
    tokenInfo = json.dumps(tokenInfo)

    token = base64.b64encode(bytes(tokenInfo,'ascii')).decode()
    print(token)
    return token


if __name__ == '__main__':
    buildToken()

#
# 最后,将生成的Token复制到以下curl -X POST替换掉其中的token,修改对应的app_id,然后取请求得到正确的"access_token"
# 

# curl -X POST https://liveroom{app_id}-api.zego.im/cgi/token -d '{"version": 1,"seq": 1,"app_id": 000000000,"biz_type": 0,"token": token}'
本篇目录
  • 免费试用
  • 提交工单
    咨询集成、功能及报价等问题
    电话咨询
    400 1006 604
    咨询客服
    微信扫码,24h在线

    联系我们

  • 文档反馈