Skip to main content

Advanced guide

Last updated 10/05/2026

1. Set user IDs​

By default, the SDK instance uses a random number as each user's distinct ID, which serves as the user's identifier while the user is not logged in. Note that the distinct ID changes when the user clears the cache or switches devices.

1.1 Set the distinct ID​

tip

In general, you don't need to customize the distinct ID. Make sure you understand the user identification rules before you set a distinct ID.

If your app has its own distinct ID management system for each user, you can call setDistinctId to set the distinct ID:

// Set the distinct ID to Thinker
TDAnalytics.setDistinctId("Thinker");

To get the current distinct ID, call getDistinctId:

//Return the distinct ID
let distinctId = TDAnalytics.getDistinctId();

If you need to set it, you must call this API before initialization

1.2 Set the account ID​

When a user logs in, you can call login to set the user's account ID. The AE platform uses the account ID as the identifier first. The account ID you set is saved, and calling login multiple times overwrites the previous account ID:

//The unique login identifier of the user, which corresponds to #account_id in the reported data. In this case, the value of #account_id is TA
TDAnalytics.login("TA");

Note that this method does not upload a user login event

1.3 Clear the account ID​

After a user logs out, you can call logout to clear the account ID. Until login is called again, the distinct ID is used as the identifier:

// Remove "#account_id" from the reported data. Subsequent data will not carry "#account_id"
TDAnalytics.logout();

Note that this method does not upload a user logout event

2. Send events​

2.1 Regular events​

You can call track directly to upload custom events. We recommend that you set the event properties and the conditions for sending events based on the document you prepared earlier. The following example uses purchasing a product:

TDAnalytics.track({
eventName: "product_buy", // Event name
properties: {
product_name: "Product Name"
} //Event properties
});
  • The track API has two parameters: the first is the event name, and the second is the event properties
  • The event name is a string. It must start with a letter and can contain digits, letters, and underscores "_". It can be up to 50 characters long and is case-insensitive.
  • The event properties are a JS object, and each element represents a property.
  • The name of an element is the property name. It must start with a letter and can contain digits, letters, and underscores "_". It can be up to 50 characters long and is case-insensitive.
  • The Value of an element is the property value. Supported types are String, Number, Boolean, Date, Object, and Array. The contents of an Object can be String, Number, Boolean, Date, or Array (with string contents). The contents of an Array can be Object and String

2.2 First events​

A first event is an event that is recorded only once for a given device or an ID of another dimension. For example, in some scenarios you may want to record the first event that occurs on a device; you can report this data as a first event.

TDAnalytics.trackFirst({
eventName: "device_activation",
properties: { key: "value" }
});

If you want to determine whether an event is the first one based on a dimension other than the device, you can set first_check_id for the first event. For example, to record the first event of an account, you can set the account ID as the first_check_id of the first event:

// Set the user ID as the first_check_id of the first event to track first-time user activation
TDAnalytics.trackFirst({
eventName: "account_activation",
firstCheckId: "TA",
properties: { key: "value" }
});

Note: Because the first-event check is performed on the server, first events are stored with a 1-hour delay by default.

2.3 Updatable events​

You can use updatable events to modify event data in specific scenarios. An updatable event requires an ID that identifies the event, which you pass in when you create the updatable event object. The AE backend determines which data to update based on the event name and event ID.

// Example: report an updatable event, assuming the event name is UPDATABLE_EVENT
// After reporting, the event property status is 3 and price is 100
TDAnalytics.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});

// After reporting, the event property status is updated to 5 and price is unchanged
TDAnalytics.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});

2.4 Overwritable events​

Overwritable events are similar to updatable events, except that an overwritable event completely overwrites historical data with the latest data. In effect, the previous record is deleted and the latest data is ingested. The AE backend determines which data to update based on the event name and event ID.

// Example: report an overwritable event, assuming the event name is OVERWRITE_EVENT
// After reporting, the event property status is 3 and price is 100
TDAnalytics.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});

// After reporting, the event property status is updated to 5 and the price property is deleted
TDAnalytics.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});

2.5 Super properties​

Some important properties, such as the user's device ID, source channel, and user status, need to be set in every event. In this case, you can set them as super properties, which are carried by every event. We recommend that you set super properties before sending events.

There are two types of super properties: event super properties and dynamic super properties. When an event is reported, super properties are inserted into the properties of the data. If a super property has the same key as a custom property set in the event, the value is determined by the following priority: Custom properties > Dynamic super properties > Static super properties > Preset properties

2.5.1 Static super properties​

Event super properties are static super properties. You can pass in only constants when you set them, so they're suitable for properties that stay stable. You can call setSuperProperties to set super properties. The format requirements of super properties are the same as those of event properties.

By property priority, custom properties take precedence over event super properties. Therefore, an event super property can also serve as the default value of a property: in the events where you need a different value, set a key with the same name to overwrite the default value.

// Set super properties. All data events will carry these properties
TDAnalytics.setSuperProperties({
channel: "Channel Name",
user_name: "User Name"
});

If you call setSuperProperties multiple times to set super properties, a later call overwrites the earlier value for fields with the same name, while fields with different names are kept.

To delete a super property, you can call unsetSuperProperty() to clear it. To clear all super properties, call clearSuperProperties(). To get all super properties, call getSuperProperties.

// Get static super properties
var superProperties = TDAnalytics.getSuperProperties();
// Clear one static super property, for example, the previously set 'channel' property. Subsequent data will not carry this property
TDAnalytics.unsetSuperProperty("channel");
// Clear all static super properties
TDAnalytics.clearSuperProperties();

2.5.2 Dynamic super properties​

Dynamic super properties run a function when an event is reported and add the return value to the event as the value of the dynamic super property. You can call the setDynamicSuperProperties API to set dynamic super properties. This API accepts a function as its parameter.

// Use dynamic super properties to report the UTC time as an event property
TDAnalytics.setDynamicSuperProperties(() => {
var localDate = new Date();
return {
utcTime: new Date(
localDate.getTime() + localDate.getTimezoneOffset() * 60000
)
};
});

The function must return a JS object, in which each element represents a property. The property format requirements are the same as those of event properties.

2.6 Track event duration​

You can call timeEvent to start timing and specify the name of the event you want to time. When you upload that event, the #duration property is automatically added to the event properties to indicate the recorded duration, in seconds.

//The following example measures how long a user stays on a product page
TDAnalytics.timeEvent({
eventName: "stay_shop"
});
/**do someting
.......
**/
//The user leaves the product page and timing ends. The "stay_shop" event will carry the #duration property that indicates the event duration
TDAnalytics.track({
eventName: "stay_shop",
properties: {
product_name: "Product Name"
}
});

3. User properties​

3.1 userSet​

For general user properties, you can call userSet to set them. Properties uploaded through this API overwrite the existing property values. If the user property does not exist yet, it is created

// username is TA
TDAnalytics.userSet({
properties: {
username: "TA"
}
});
//username is AE
TDAnalytics.userSet({
properties: {
username: "AE"
}
});

Property format requirements are the same as for event properties.

3.2 userSetOnce​

If a user property only needs to be set once, you can call userSetOnce to set it. If the property already has a value, this call is ignored.

//first_payment_time is 2018-01-01 01:23:45.678
TDAnalytics.userSetOnce({
properties: {
first_payment_time: "2018-01-01 01:23:45.678"
}
});
//first_payment_time is still 2018-01-01 01:23:45.678
TDAnalytics.userSetOnce({
properties: {
first_payment_time: "2018-12-31 01:23:45.678"
}
});

Property format requirements are the same as for event properties.

3.3 userAdd​

When you upload a numeric property, you can call userAdd to accumulate its value. If the property has not been set yet, it is assigned 0 before the calculation

//total_revenue is now 30
TDAnalytics.userAdd({
properties: {
total_revenue: 30
}
});
//total_revenue is now 678
TDAnalytics.userAdd({
properties: {
total_revenue: 648
}
});

The property key is a string, and the Value can only be a number.

3.4 userUnset​

When you need to clear a user's property value, you can call userUnset to clear the specified property. If the property has not been created in the cluster yet, userUnset does not create it

// Clear the value of the user property named userPropertykey for this user, that is, set it to NULL
TDAnalytics.userUnset({
property: "userPropertykey"
});

The value passed to userUnset is the Key of the property to clear.

3.5 userDelete​

To delete a user, you can call userDelete. After that, you can no longer query this user's user properties, but the events generated by the user can still be queried

TDAnalytics.userDelete();

3.6 userAppend​

You can call userAppend to append elements to user data of the Array (List) type.

TDAnalytics.userAppend({
properties: {
user_list: ["apple", "ball"]
}
});

Note: This feature requires AE platform 2.5 or later

3.7 userUniqAppend​

Starting from v2.1.0, you can call userUniqAppend to append elements to user data of the Array (List) type with deduplication.

//The value of user_list is now ["apple","ball"]
TDAnalytics.userAppend({
properties: {
user_list: ["apple", "ball"]
}
});
//The value of user_list is now ["apple","apple","ball","cube"]
TDAnalytics.userAppend({
properties: {
user_list: ["apple", "cube"]
}
});
//The value of user_list is now ["apple","ball","cube"]
TDAnalytics.userUniqAppend({
properties: {
user_list: ["apple", "cube"]
}
});

Note: This feature requires AE platform 3.6 or later

5. Other features​

5.1 Get the device ID​

You can call getDeviceId() to get the device ID. Due to the runtime environment, the device ID is stored in the local cache. Once the user deletes the cache, the device ID changes, so the device ID isn't guaranteed to stay the same

var deviceId = TDAnalytics.getDeviceId();

5.2 onComplete callback function​

APIs such as track, userSet, userSetOnce, userAdd, and userDelete support passing in an onComplete callback.

You can pass onComplete directly after the original parameter list, or use a parameter object. If you use a parameter object, it must contain onComplete; otherwise, a parameter error occurs.

The following example uploads an event:

TDAnalytics.track({
eventName: "test", // Required
properties: { testkey: 123 }, // Optional
time: new Date(),
onComplete: res => {
console.log(res);
}
});

The parameter res of onComplete is of the object type and has two properties: code and msg.

res.code is of the int type and is defined as follows:

  • 0: Success
  • -1: Invalid data format
  • -2: Invalid APP ID
  • -3: Network or server error

In Debug mode, the codes are defined as follows:

  • 0: Success
  • -1: A parameter or permission validation issue
  • 1: A basic field error. The detailed error fields and reasons are returned
  • 2: The entire record is invalid
  • -3: Network or server error

res.msg is the text description of res.code.

5.3 Set up event cache reporting​

Starting from v2.2.0, you can enable event cache reporting during initialization.

// AE SDK configuration object
var config = {
appId: "YOU-APP-ID", // APP ID of the project
serverUrl: "https://youserverurl.com", // Data reporting URL
enableBatch: true, // Whether to enable batch reporting of cached events. true = enabled, false = disabled
  batchConfig: {
size: 5, // Number of cached events per report
interval: 5000 // Reporting interval for cached events (milliseconds)
}
};
// Initialize
TDAnalytics.init(config);

6. Channel SDK compatibility​

6.1 Tencent Ads​

6.1.1 Solution overview​

After you integrate the TDAnalytics SDK, you don't need to integrate the Tencent Ads SDK separately. Once you complete the TDAnalytics initialization method, the Tencent Ads SDK is initialized automatically. When you report key events such as registration and payment, the system automatically sends these events to Tencent Ads based on your configuration.

6.1.2 Integration steps​

  1. Download the Tencent Ads SDK. Version 1.5.4 is currently used, but you can also switch to another version.

Put dn-sdk-minigame.cjs.js in the same directory as the TDAnalytics SDK.

  1. Initialize
note

The TDAnalytics SDK version must be >= 3.0.4

TDAnalytics.init({
appId: 'AppId',
serverUrl: 'ServerUrl',
tgaInitParams: {
user_action_set_id: 100001,// Data source ID, number, required
secret_key: '5e853xxxxxxd57a690xxxxxxxxxx',// Encryption key, required
appid: 'wx123xyz123xyz123x',//WeChat mini game APPID, starting with wx, required
},
reportingToTencentSdk: 2,//1 Report only to Tencent 2 Report to both Tencent and AE 3 Report only to AE
debugMode: 'debug'// In debug mode, the local debug logs of the Tencent Ads SDK are printed
})
  1. Set the user ID
  • setOpenId

The openid is usually obtained asynchronously by calling a backend API (How to get the openid). After you get the openid, call the sdk.setOpenId() method to set it. You can set only one of openid and unionid, and openid takes precedence.

wx.request({
url: 'URL of the backend API that gets the openid and checks whether the user is registered',
success: function(res){
if(res.openid){
// Set the opneid. You must set the openid before reporting the registration behavior. setOpenId is a synchronous method, so you can report the registration behavior immediately after setting it.
TDAnalytics.login(res.openid);

//Report the registration behavior. The backend API determines whether the user is a registered user
if(res.isRegisterUser){
TDAnalytics.track({
eventName: "REGISTER"
});
}
}
}
});
  • setUnionId

The unionid is usually obtained asynchronously by calling a backend API (How to get the unionid). After you get the unionid, call the sdk.setUnionId() method to set it. Use this method to set the unionid only when there is no openid.

wx.request({
url: 'URL of the backend API that gets the openid and checks whether the user is registered',
success: function(res){
if(res.unionid){
// Set the unionid. Use the openid first. Set the unionid only when there is no openid or the backend uses the unionid throughout.
TDAnalytics.setDistinctId(res.unionid);

//Report the registration behavior. The backend API determines whether the user is a registered user
if(res.isRegisterUser){
TDAnalytics.track({
eventName: "REGISTER"
});
}
}
}
});
  1. Report behaviors
TDAnalytics.track({
eventName: "product_buy", // Event name
properties: {
product_name: "Product Name"
} //Event properties
});

For the following specific events, report the specified event names

EventEvent nameEvent properties (must include these keys)

Mini game launch

START_APP

None

Payment

PURCHASE

{

value: 600

}

Registration

REGISTER

Reactivation

RE_ACTIVE

{

backFlowDay: 30

}

Add the mini game to favorites

ADD_TO_WISHLIST

{

type: 'default',

}

Share the mini game

SHARE

{

target: 'APP_MESSAGE'

}

Create a character

CREATE_ROL

{

name: 'SuperMan'

}

Complete the tutorial

TUTORIAL_FINISH

None

Level up

UPDATE_LEVEL

{

level: 2,

power: 85,

}

View the mall page

VIEW_CONTENT

{

// Key scene visit: Mall

item: 'Mall',

}

View game activities

VIEW_CONTENT

{

// Key scene visit: Activity

item: 'Activity',

}

For example, report the level-up event

TDAnalytics.track({
eventName: "UPDATE_LEVEL",
properties: {
level: 2,
power: 85,
}
});
Was this page helpful?