Documentation
ZegoMiniGameEngine Mini Game Engine
Documentation
Demo APP
SDK Center
API Center
FAQ
Code Market
Console
Sign Up
Log In
中文站 English
  • Documentation
  • Mini Game Engine
  • Server APIs
  • Make API requests

Make API requests

Last updated:2024-07-05 16:04

Request structure

Endpoint

Developers need to specify the corresponding access address based on the geographical region of their server when sending requests to the ZEGOCLOUD server.

To ensure the quality of your business service access, please prioritize using the domain name of the geographical region where your server is located as the access address when sending requests to the ZEGOCLOUD server.

ZEGOCLOUD supports request access from the following geographical regions:

Region API base URL
Mainland China (Shanghai)
${PRODUCT}-api-sha.zego.im
Hong Kong, Macau and Taiwan (Hong Kong)
${PRODUCT}-api-hkg.zego.im
Europe (Frankfurt)
${PRODUCT}-api-fra.zego.im
Western United States (California)
${PRODUCT}-api-lax.zego.im
Asia-Pacific (Mumbai)
${PRODUCT}-api-bom.zego.im
Southeast Asia (Singapore)
${PRODUCT}-api-sgp.zego.im
Unified access address (regardless of region)
${PRODUCT}-api.zego.im

In this context, PRODUCT refers to different services provided by ZEGOCLOUD, and in this particular product, it is mini-game, for instance, mini-game-api.zego.im.

Protocol

All operations of the ZEGOCLOUD server API send requests over HTTPS. This ensures secure communications services.

Request methods

The operations of the ZEGOCLOUD server API support the following HTTP request methods:

  • GET
  • POST

All request parameters, including common parameters and business requests, are sent as a query string by using the GET method. Special and complex API parameters are added to the request body and sent by using the POST method.

Common parameters

This section describes the common parameters that are used when you call an operation of the ZEGOCLOUD server API, including common request parameters and common response parameters.

Common request parameters

Common request parameters must be included in all API requests. The following table describes the common request parameters.

Parameter Type Required Description
AppId
UINT32
Yes
The application ID, which is a unique credential assigned by ZEGOCLOUD for the request sender.
Signature
STRING
Yes
The signature. For more information about how to generate a signature, see the Signature method section of this topic.
SignatureNonce
STRING
Yes
A random number.
SignatureVersion
STRING
Yes
The version of the signature. Default value: 2.0.
Timestamp
INT64
Yes
The UNIX timestamp. Unit: seconds. The time deviation from the actual time must be within 10 minutes.

Sample request:

  • Request URL:

    https://mini-game-api.zego.im/?Action=DescribeGameLaunchCode
    &AppId=1234567890
    &SignatureNonce=15215528852396
    &Timestamp=1234567890
    &Signature=7a2c0f11145fb760d607a07b54825013
    &SignatureVersion=2.0
  • Request message body:

    {
        "RoomId": "room_123",
        "MiniGameId": "TinyLoveWar",
        "AnchorId": "anchor1",
        "Nickname": "anchor",
        "Avatar": "http://xxx",
        "Sex": 1
    }

Common response parameters

API responses are returned in the JSON format.

Every response returns common parameters regardless of whether the call is successful.

Parameter Type Description
Code
NUMBER
The return code.
Message
STRING
The message of the request result.
RequestId
STRING
The request ID.
Data
N/A
The response data.

Sample response:

{
    "Code": 0,
    "Message": "",
    "RequestId": "8411281679140263090",
    "Data": {
        "CurrencyBalance":102,
    }
}

Signature method

To ensure secure calls to API operations, the ZEGOCLOUD server authenticates each API request by using a signature. When you call an API operation, you must include a signature in the request.

A new signature must be generated each time you call an API operation.

1. Obtain the values of the AppID and ServerSecret parameters

A signature is used to authenticate the identity of the request sender by performing symmetric encryption based on the AppID and ServerSecret parameters. The AppID parameter is used to identify the request sender. The ServerSecret parameter is used to encrypt the signature string on the request sender side and verify the signature string on the ZEGOCLOUD server. Keep this information strictly confidential.

After you create a project in the ZEGOCLOUD console, you can obtain the values of the AppID and ServerSecret parameters. For more information, see How to view project information.

2. Generate a signature

  1. Signature parameters
Parameter Description
AppId
The application ID. After you create a project in the ZEGO console, you can obtain the value of the AppID parameter from the project information. For more information, see How to view project information.
SignatureNonce
A random number. The value must be the same as that of the SignatureNonce parameter in the common request parameters. For more information about how to generate a random number, see the "Signature example" section of this topic.
ServerSecret
The secret key. After you create a project in the ZEGO console, you can obtain the value of the ServerSecret parameter from the project information. For more information, see How to view project information.
Timestamp
The UNIX timestamp. Unit: seconds. For more information about how to generate a timestamp, see the "Signature example" section of this topic. The time deviation from the actual time must be within 10 minutes.

The values of the SignatureNonce and Timestamp parameters used to generate a signature must be the same as the values of the SignatureNonce and Timestamp parameters in the common request parameters.

  1. Signature generation algorithm

Signature = md5(AppId + SignatureNonce + ServerSecret + Timestamp)

  1. Signature string format

The signature is a hexadecimal string of 32 characters in lowercase.

3. Signature example

ZEGOCLOUD provides signature examples of multiple programming languages. You can refer to the examples based on your business requirements.

Go Python Java PHP Node.js
import (
   "crypto/md5"
   "crypto/rand"
   "encoding/hex"
   "fmt"
   "log"
   "time"
)
// Signature=md5(AppId + SignatureNonce + ServerSecret + Timestamp)
func GenerateSignature(appId uint32, signatureNonce string, serverSecret string, timestamp int64) (Signature string){
   data := fmt.Sprintf("%d%s%s%d", appId, signatureNonce, serverSecret, timestamp)
   h := md5.New()
   h.Write([]byte(data))
   return hex.EncodeToString(h.Sum(nil))
}
func main() {
   /*Generate a random hexadecimal string of 16 characters. */
   nonceByte := make([]byte, 8)
   rand.Read(nonceByte)
   signatureNonce := hex.EncodeToString(nonceByte)
   log.Printf(signatureNonce)
   appId := 12345       // Use your AppId
   serverSecret := "9193cc662a4c0ec135ec71fb57194b38"    // Use your  ServerSecret
   timestamp := time.Now().Unix()
   /* appId:12345
      signatureNonce:4fd24687296dd9f3
      serverSecret:9193cc662a4c0ec135ec71fb57194b38
      timestamp:1615186943      2021/03/08 15:02:23
      signature:43e5cfcca828314675f91b001390566a
    */
   log.Printf("signature:%v", GenerateSignature(uint32(appId), signatureNonce, serverSecret, timestamp))
}
# -*- coding: UTF-8 -*-
import secrets
import string
import hashlib
import time
#Signature=md5(AppId + SignatureNonce + ServerSecret + Timestamp)
def GenerateSignature(appId, signatureNonce, serverSecret, timestamp):
    str1 = str(appId) + signatureNonce + serverSecret + str(timestamp)
    hash = hashlib.md5()
    hash.update(str1.encode("utf8"))
    signature = hash.hexdigest()
    return signature

def main():
    # Generate a random hexadecimal string of 16 characters. 
    signatureNonce = secrets.token_hex(8)

    # Use the application ID and server secret of your project.
    appId = 12345
    serverSecret = "9193cc662a4c0ec135ec71fb57194b38"
    # Obtain a 10-digit UNIX timestamp.
    timestamp = int(time.time())
    print(GenerateSignature(appId,signatureNonce,serverSecret,timestamp))

if __name__ == '__main__': main()
import java.security.MessageDigest;
import java.security.SecureRandom;
public class Md5{
    /**
     * Converts the byte array to a hexadecimal string.
     * @param bytes The byte array to be converted.
     * @return  The generated hexadecimal string.
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        // Convert each byte of the array to a hexadecimal string and concatenate all the generated hexadecimal strings into an MD5 string.
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString();
    }
    // Signature=md5(AppId + SignatureNonce + ServerSecret + Timestamp)
    public static String GenerateSignature(long appId, String signatureNonce, String serverSecret, long timestamp){
        String str = String.valueOf(appId) + signatureNonce + serverSecret + String.valueOf(timestamp);
        String signature = "";
        try{
            // Create an object that provides the message-digest algorithm, and initialize the object as an MD5 algorithm object.
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Obtain a byte array after calculation.
            byte[] bytes = md.digest(str.getBytes("utf-8"));
            // Convert each byte of the array to a hexadecimal string and concatenate all the generated hexadecimal strings into an MD5 string.
            signature = bytesToHex(bytes);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return signature;
    }


    public static void main(String[] args){
        // Generate a random hexadecimal string of 16 characters.
        byte[] bytes = new byte[8];

        // Obtain a cryptographically strong random number generator by using the `SecureRandom` class.
        SecureRandom sr = new SecureRandom();

        sr.nextBytes(bytes);
        String signatureNonce = bytesToHex(bytes);
        long appId = 12345L;       // Use the application ID and server secret of your project. Append an "L" or "l" to the application ID to indicate that the application ID is of the LONG type.
        String serverSecret = "9193cc662a4c0ec135ec71fb57194b38";
        long timestamp = System.currentTimeMillis() / 1000L;
        System.out.println(GenerateSignature(appId,signatureNonce,serverSecret,timestamp));
    }
}
<?php
function GenerateSignature($appId, $signatureNonce, $serverSecret, $timestamp)
{
    $str = $appId.$signatureNonce.$serverSecret.$timestamp;
    $signature = md5($str);
    return $signature;
}

// Generate a random hexadecimal string of 16 characters.
$signatureNonce = bin2hex(random_bytes(8));
// Use the application ID and server secret of your project.
$appId = 12345;
$serverSecret = "9193cc662a4c0ec135ec71fb57194b38";
$timestamp = time();
$signature = GenerateSignature($appId, $signatureNonce, $serverSecret, $timestamp);
echo $signature;
?>
const crypto = require('crypto'); 
//Signature=md5(AppId + SignatureNonce + ServerSecret + Timestamp)
function GenerateUASignature(appId, signatureNonce, serverSecret, timeStamp){
    const hash = crypto.createHash('md5'); // Use the MD5 hash algorithm.
    var str = appId + signatureNonce + serverSecret + timeStamp;
    hash.update(str);
    //hash.digest('hex') indicates that the output is in the hexadecimal format.
    return hash.digest('hex');
}

var signatureNonce = crypto.randomBytes(8).toString('hex');
// Use the application ID and server secret of your project.
var appId = 12345;
var serverSecret = "9193cc662a4c0ec135ec71fb57194b38";
var timeStamp = Math.round(Date.now()/1000);
console.log(GenerateUASignature(appId, signatureNonce, serverSecret, timeStamp));

Signature failures

The following table describes the codes that may be returned upon a signature failure. You can troubleshoot issues based on your actual scenarios.

Return code Description
100000004 The signature expires.
100000005 The signature is invalid.

Identity authentication

If you receive a callback from the ZEGO server, we recommend that you authenticate the identity of the callback sender by using a signature. The signature is generated by calculating an MD5 value of the AppId, SignatureNonce, CallbackSecret, and Timestamp parameters.

The CallbackSecret parameter value must be kept strictly confidential. For more information about how to obtain the CallbackSecret parameter value, see How to view project information.

The callback from the ZEGO server carries the signature_nonce, timestamp, and signature parameters. You can use the following formula to calculate a signature to authenticate the identity of ZEGO:

Signature = MD5(AppId + SignatureNonce + CallbackSecret + Timestamp)

The signature is a hexadecimal string of 32 characters in lowercase.

Page Directory
  • Free trial
  • 提交工单
    咨询集成、功能及报价等问题
    电话咨询
    400 1006 604
    Get Consulting
    Scan Wechat QR code