TikTok for Developers

Docs

Development Stage

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

Build your mini app locally

Develop your mini app locally, making sure to abide by the technical standards and development restrictions listed below.

Technical standards for app development

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

.
├── dist // Build output
│   ├── ...
│   ├── minis.config.json  // [auto generated by CLI tool] sync from ./minis.config.json
│   ├── ...
├── ...
├── minis.config.json  // declare TikTok Minis configurations, such as navigation color
└── package.json

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.
  • iframe is not supported.
  • 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 app, install the command-line interface (CLI) tool to generate config files and debug.

npm install @tiktok-minis/cli@latest -g

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

Usage: ttdx minis [options] [command] 

Description: TikTok Minis relevant commands

Commands:
  init                                   initialize minis.config.json
  build:after                            generate minis dependent files to build product folder
  debug                                  start local debugging
  
Options:
  -h, --help                             display help

Next, initialize configuration of your TikTok Minis JSON file by running the init command:

cd path/to/your/game/build
ttdx minis init

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

  1. Automatically generates the minis.config.json file in the mini app. You must fill in the requested information in minis.config.json. Providing your app'sclient_key is required.
  2. Automatically injects TikTok Minis SDK initialization code in index.html. TikTok Minis 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() with a valid value.

Note: In the TikTok Minis index.html, introduce TikTok Minis SDK to the first script tag and call TTMinis.

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


// index.html
<head>
<script src="https://connect.tiktok-minis.com/drama/sdk.js"></script>
<script>
  TTMinis.init({
    clientKey: `${your_client_key}`,
  });
</script>
</head>
  1. Automatically injects VConsole scripts in index.html.
// index.html
<head>
...
<script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script><script>

JSON configuration parameters

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

{
  "navbar": {
    "lightModeBgColor": "#ffffff",
    "darkModeBgColor": "#000000"
  },
  "dev": {
    "port": "3000",
    "host": "localhost"
  },
  "build": {
    "htmlEntry": "index.html" or "public/index.html"
    "output": "build" or "dist"
  }
}

Below is list of TikTok Minis JSON configuration parameters.

Parameters

required

Type

Description

Navbar

navbar

No

object

Configuration items related to TikTok Minis 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

domain

domain.trustedDomains

Yes

string[]

Allowed API Request List

Example

// minis.config.json
{
  "navbar": {
    "lightModeBgColor": "#ffffff",
    "darkModeBgColor": "#000000",
  },
  "dev": {
    "port": "3000",
    "host": "localhost"
  },
  "build": {
    "outputDir": "build",
    "htmlEntry": "public/index.html"
  },
  "domain": {
    "allowList": ["https://www.xxx.com"]
  }
}

Integrate with authorization system for third parties

When developing your mini app, 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 app with their TikTok account credentials. more about login/authorize()

Option 1: Silent login

(no authorization popup)

TTMinis.login(function(response){
  if (response.authResponse?.code) {
    let code = response.authResponse.code;
    // Use the code to make a backend API request to ultimately obtain the user's open_id
  } else {
    // If it fails, the game can handle different cases based on the specific error_code
  }
});

Option 2:Explicit authorization

We don't recommend calling TTMinis.authorize to pop up an authorization box as soon as Minis starts, as it may easily lead to users refusing and affect conversion. It is suggested to first complete the basic login (get open_id), and then request users to authorize more permissions (such as obtaining user information, phone numbers, etc.) when necessary, and trigger authorization through buttons to avoid users' resentment.

TTMinis.authorize(function(response) {
  if (response.authResponse?.code) {
    // 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, etc.
    let code = response.authResponse.code;
  } else {
    // Handle other errors or user deauthorization cases (response.authResponse is null)
  }
}, {
  scope: "user.info.basic" // The scope of permissions requested, example is basic user information
});


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

TTMinis.login(
  function (res) {
    if (res.authResponse?.code) {
      const code = res.authResponse.code;
      // do something
    } else {
       //       // do something
    }
  },
  {
    scope: "user.info.basic",
  }
);

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:

Integrate with TikTok's payment system

When developing your mini app, 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 app.

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

There are two options for payment fulfillment, described below.

Option 1: Recharge and payment combined (recommended)

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

Option 2: Recharge and pay separately

For this option, you will check the user's balance to see if they have enough Beans for a transaction, then retrieve information about the available tiers the user can purchase. The user can then recharge their Beans, and choose a product. The third party will then generate a trade order, and call the pay function from TikTok Minis SDK.

This option requires the third party to complete more steps but also offers more control over the recharge process.

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 TikTok Minis 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 TikTok Minis 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 minis build:after to generate TikTok Minis 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 minis.config.json file in the root directory to the build product folder.
  • Create a minis.manifest.json to describe the resource list for the TikTok Minis service to resolve. Refer to the following example:
{
  "name": "minis.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"
    }
  ]
}

Test TikTok Minis in sandbox (optional)

If you are using a sandbox environment, you can test your mini app 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 app that you want to view.

Scan the QR code with the TikTok app to view the mini app. 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 TikTok Minis.


Was this document helpful?
TikTok for Developers