TikTok for Developers

Docs

Development Stage

During this stage you will create your mini game file, integrate with necessary APIs, and test your configuration. Follow the steps outlined below to complete development of your mini game.

Build your mini game independently

Use a third-party game engine and integrated development environment (IDE) to develop your mini game. After you've finished developing your mini game, export your project to an HTML5 or web mobile-compatible file.

Note: Your finished mini game file must be HTML5 compatible. Therefore, you are advised to develop your mini game using a lightweight game engine that is mobile-friendly.

Technical standards for development

When building your mini game for TikTok, you should follow technical standards for mobile webpage development, with some constraints and extra capabilities. A complete mini game project file should include the following directory structure:

.
├── dist // Build output
│   ├── ...
│   ├── minigame.config.json  // [auto generated by CLI tool] Sync from ./minigame.config.json
├── src // Project source code
│   ├── ...
├── ...
├── minigame.config.json  // Declare mini game configurations, such as navigation color
└── package.json

Development restrictions

Make sure your mini game file abides by the following development restrictions:

  • Using the eval() function in JavaScript code is forbidden.
  • Using the Function constructor is forbidden.
  • Using string parameters in setTimeout() and setInterval() functions is forbidden.
  • In addition to introducing fonts, the src of script and CSS can only come from self resources.
  • Some web APIs are forbidden, such as clipboard, location, and vibration APIs.
  • Server request addresses must be registered as trusted domains in the Security configurations section of your app page.

Install command-line interface tool

After completing development of your mini game and exporting it as an HTML5-compatible file, install the command-line interface (CLI) tool to begin the debugging process:

npm install @ttmg/cli@latest -g

After installing the CLI tool, you can use the following CLI commands:

Usage: ttdx minigame [options] [command] 

Description: TikTok mini games relevant commands

Commands:
  init                                 initialize minigame.config.json
  build                                generate mini game dependent files to build product folder
  dev                                  start local debugging
  
Options:
  -h, --help                             display help for command

Next, initialize configuration of your mini game's JSON file by running the init command:

cd path/to/your/game/build
ttmg init --h5

Running the init command in the game product directory does the following three things:

  1. Automatically generates the minigame.config.json file in the mini game. You must fill in the requested information in minigame.config.json. Providing your app'sclient_key is required.
  1. Automatically injects Mini Games SDK initialization code in index.html. Mini Games SDK is the JavaScript toolkit that provides access to TikTok's client-side functionalities, including authentication from your web app to TikTok. You need to replace the client_Key passed in TTMinis.game() with a valid value.

Note: In the mini game index.html, introduce Mini Games SDK to the first script tag and call TTMinis.game.

Please call TTMinis.game after the script is imported, otherwise the SDK will not be injected and the call will fail.

<head>
  <script src="https://connect.tiktok-minis.com/game/sdk.js"></script> <!-- Must be the first line after <head> -->
  <script>
    TTMinis.game.init({
      clientKey: `${your_client_key}`,
    });
  </script>
</head>
  1. Automatically injects Console scripts in index.html.
// index.html
<head>
...
 <script src="https://connect.tiktok-minis.com/libs/eruda.js"></script>
 <script>
    eruda.init();
 </script>
</head>

JSON configuration parameters

The minigame.config.json file specifies global settings for your mini game, such as navbar colors and development configurations. Here’s an example configuration:

{
  "

Below is list of JSON configuration parameters.

Parameters

required

Type

Description

orientation

YES

"VERTICAL" | "HORIZONTAL"

VERTICAL

Navbar

navbar

No

object

Configuration items related to mini game navigation bar

navbar.bgColorLight

No

string

Navigation bar background color in light mode

navbar.bgColorDark

No

string

Navigation bar background color in dark mode

Dev

dev

No

object

Local development configuration items

dev.host

No

string

  • Example: localhost
  • Default: localhost

dev.port


No

number

  • Example: 4000
  • Default: 3000

Build

build

No

object

Product build related configuration

build.outputDir


No

string

The folder name of the build product

  • Example: dist | build
  • Default: build

build.htmlEntry

No


string

The frontend project html entry

  • Example:index.html | public/index.html
  • Default:public/index.html

Access game loading state

When the main framework loads game resources, you must inform the main framework of the game loading progress through TTMinis.game.setLoadingProgress. If progress reaches a value of 1, the main framework will exit the loading page and display the mini game screen.

TTMinis.game.setLoadingProgress({
  progress: 1,
  success: () => {
  // Do something when succeeded
  },
  fail: (error) => {
  // Do something when failed
  }
  complete: () => {
  // Do something when completed
  }
})

Learn more about how to get started with Mini Games SDK.

Adapt the navigation bar

The UI module at the top of the mini game can use TTMinis.game.getMenuButtonBoundingClientRectto get the layout position of the menu button. It will use this value to align other operation buttons to the navigation bar at the top of the screen. This helps the navigation bar adapt to devices with Dynamic Island or a notch screen.

const res = TTMinis.game.getMenuButtonBoundingClientRect()
const { top, bottom, height } = result;

Integrate with authorization system for third parties

When developing your mini game, be sure to integrate with our third-party authorization system, which leverages the standard OAuth2.0 protocol to allow users to register or sign in to your mini game with their TikTok account credentials.

Invoking the Mini Games SDK Login function, trigger the following code after a user attempts to log in with their TikTok account:

TTMinis.game.login({
  success: (result) => {
  // The user has logged in and authorized the application
  // You can get the code and send it to the backend in exchange for open_id, access_token, and more
   let code = result.code;
  },
  fail: (error) => {
  // Other errors or deauthorization code is null
  },
  complete: () => {
   //  Both success and failure will trigger this callback
  }
});

The code received can be sent to your app server, so the server is able to exchange open_id and access_token through https://open.tiktokapis.com/v2/oauth/token/. Then the current user information can be retrieved through https://open.tiktokapis.com/v2/user/info/.

Note: The access token will expire after 24 hours after initial issuance. Users may also cancel the authorization process, which will render the access token invalid. Therefore, you should handle responses for all OpenAPI interactions with TikTok. If the returned HTTP code is 401, or not 200, your server should notify your front end to re-trigger the authorization screen.

The diagram below details the request sequence flow:

Note: Please be aware of the following caveats:

  • TTMinis.game.login method will attempt to open a browser popup which might be blocked by most browsers by default, so please only trigger it after the user click action. You can use the TTMinis.game.getLoginStatus method to check the current state of login process.
  • You should not store or send client_secret, access_token information through browsers for security purposes, requests to https://open.tiktokapis.com/v2/oauth/token/ and https://open.tiktokapis.com/v2/user/info/ should be triggered by your app server.
  • It is necessary to verify state from your app server to prevent CSRF attacks.

Integrate with TikTok's payment system

When developing your mini game, you can integrate with TikTok's payment system, which allows users to purchase items called Beans, which they can use to acquire products within your mini game.

Integration with TikTok's payment system requires a combination of two methods: Mini Games SDK and TikTok Minis Server API.

Combined recharge and payment flow

You are required to create a trade order through TikTok Minis Server API, and call the pay function from Mini Games SDK after the user chooses a product. If the user has an insufficient balance, TikTok will prompt them to complete an in-app purchase for more Beans automatically. This allows you to integrate with TikTok's payment system in as few steps as possible.

Listen to Beans redemption event through webhooks

General instructions for using TikTok for Developers webhooks can be found in our webhook documentation overview. For each webhook you receive, you are responsible for doing the following:

  1. Immediately respond with a 200 HTTP status code to acknowledge the receipt of the event notification.
  2. Verify if this webhook is legal as described in our webhook verification documentation.

In general, a webhook request will look like this:

Webhook structure

Request Body

Key

Type

Description

client_key

string

The unique identification key is provided to the partner

event

string

Event name

create_time

int64

The time in which the event occurred. UTC epoch time is in seconds.

user_openid

string

The TikTok user's unique identifier; obtained through /oauth/access_token/

content

string

A serialized JSON string of event information.

Events

The following events for mini games are available, as well as their corresponding definitions of content.

minis.trade_order.redeem.success

Indicates that the order payment has been successfully completed.

Content

Key

Type

Description

trade_order_id

string

The trade_order_id you got in response when you were calling the /trade_order/create/ API

order_id


string


The order_id you used as input when you were calling the /trade_order/create/ API

Example payload

{
    "client_key": "your_client_key",
    "event": "minis.trade_order.redeem.success",
    "create_time": 1615338610,
    "user_openid": "",
    "content": "{\"trade_order_id\":\"TOID667700996\",\"order_id\":\"order_id_as_in_your_system\"}"
}

Note: After implementing a functional API to receive webhook, please send the detailed URL to your point of contact from TikTok, and let them register this URL for you.

minis.trade_order.redeem.refund_traceback

Indicates that the order amount initiated by the user in the store for a refund was partially recovered, and the refund_amount value is the amount that was recovered.

Content

Key

Type

Description

trade_order_id

string

The trade_order_id you got in response when you were calling the /trade_order/create/ API

order_id


string


The order_id you used as input when you were calling the /trade_order/create/ API

Example payload

{
  "client_key": "your_client_key",
  "event": "minis.trade_order.redeem.refund_traceback",
  "create_time": 1744946518,
  "user_openid": "",
  "content": "{\"trade_order_id\":\"TOID2157c5ba03\",\"order_id\":\"order_id_as_in_your_system\",\"is_sandbox\":true,\"refund_amount\":80}"
}

Obtain additional data

Note that TikTok user-specific data must obtained through TikTok Minis Server API according to the standard OAuth2.0 protocol, or through the APIs listed within Mini Games SDK.

If your project requires details about a user's environment, like language and operating system, you can obtain the data using standard browser capabilities. For example:

  • obtain language:
const currentLang = navigator.language || navigator.userLanguage;
  • obtain OS:
function getOS() {
    const userAgent = navigator.userAgent || navigator.vendor || window.opera;

Run the build command

After developing and generating production code (always by npm run build), execute ttdx minigame build:after to generate mini game dependency files to the production code folder.

cd path/to/your/game/build

Please ensure that the real production code folder name is consistent with the name declared in the minis.config.json file's build.folderName field.

The execution will do the following:

  • Synchronize the minigame.config.json file in the root directory to the build product folder.
  • Create a minigame.manifest.json to describe the resource list for the TikTok Minis service to resolve. Refer to the following example:
{
  "name": "minigame.manifest.json",
  "resource_list": [
    {
      "type": "file",
      "name": "404.html"
    },
    {
      "type": "file",
      "name": "android-chrome-192x192.png"
    },
    {
      "type": "file",
      "name": "safari-pinned-tab.svg"
    },
    {
      "type": "folder",
      "name": "static",
      "children": [
        {
          "type": "folder",
          "name": "css",
          "children": [
            {
              "type": "file",
              "name": "main.ec164663.css"
            },
            {
              "type": "file",
              "name": "main.ec164663.css.map"
            }
          ]
        },
        {
          "type": "folder",
          "name": "js",
          "children": [
            {
              "type": "file",
              "name": "main.eca09dd8.js"
            },
            {
              "type": "file",
              "name": "453.d855a71b.chunk.js"
            }
          ]
        }
      ]
    },
    {
      "type": "file",
      "name": "index.html"
    }
  ]
}

Debug locally

Start local debugging using the CLI tool:

 ~ ttdx minigame debug
  • Code scanning will be performed when debugging begins. Please refer to development restrictions for specific rules.
  • After passing verification, the debugging window will open through the default browser using the dev parameter configuration of minigame.config.json. At this time, the mini app can be previewed through the browser.
  • The debug window supports the following tools:
    • Dark mode
    • Language env
    • Device

Test mini game in sandbox (optional)

If you are using a sandbox environment, you can test your mini game after you've completed configurations. Make sure you've added test users to your sandbox.

Once your sandbox shows Ready for testing, then go to the Code assets section. Then click the View button next to the version of your mini game that you want to view.

Scan the QR code with the TikTok app to view the mini game. Make sure you are using the a TikTok account in your sandbox's test user list.

Next step: Publication stage

After you have completed development and testing, you are ready to publish your mini game.

Was this document helpful?
TikTok for Developers