1. SDK initialization parameters

ParameterTypeDefault ValueMeaningRemarks
nameStringsensorsA default global variable used by the SDK, registered in the App global function. In a Page, it can be used as app[name].track.
server_urlStringData receiving URL
  • Please add this URL in WeChat Official Account Platform → Development → Development Settings → Server Domain Names.
autoTrackObjectNoneWhether to enable automatic data collection
  • Six attribute parameters (appLaunch, appShow, appHide, pageShow, pageShare, mpClick, pageLeave), of which mpClick, pageLeave are false by default, and others are true. That is, by default, five events $MPLaunch, $MPShow, $MPHide, $MPViewScreen, $MPShare are collected (supported by SDK version 0.9 or higher), among which the $MPShare event is supported in version 1.9 or higher, the $MPPageLeave event is supported in version 1.14.20 or higher, and the $MPClick, $MPPageLeave events are not collected by default. For detailed introduction, please see predefined events.
  • WeChat, Alipay, Baidu Mini Program SDK support.
show_logBooleantrueWhether to print log
  • After setting true, the log will be printed in the simulator console, displaying the sent data. Set false to stop display.
send_timeoutNumber1000Request sending timeout (if a request is sent and there is no response after a certain time, the next data will be sent)
  • Unit is milliseconds;
  • Alipay Mini Program SDK support.
use_client_timeBooleanfalseWhether to use the client's time
  • Because the client's system time is inaccurate, it may cause incorrect event time. Therefore, the default value is false, indicating not to use the client's time but the server's time. If set to true, the client's system time will be used. If you add {$time: new Date()} in the attribute, note that it must be of type Date, then this data will use the time you passed in the attribute;
  • Starting from version 1.14.6, the SDK uses the client's time to send data by default, and no longer supports this configuration;
  • Only WeChat Mini Program SDK supports.
max_string_lengthNumber300Maximum length of the general string. Excess parts will be truncated and discarded (a long URL may cause data sending failure, so the length is limited).
allow_amend_share_pathBooleantrueAfter setting it to true, the path attribute in Page.onShareAppMessage will be automatically modified to add some parameters including the current user's Distinct ID.
  • If you want to automatically collect sharing information, this must be set to true, the default value is true.
  • Only WeChat Mini Program SDK supports.
batch_sendBooleantrueWhether to use batch data sending feature in the Mini Program.
  • Default enabled in WeChat Mini Program SDK 1.14.11 and above.
  • Supported in Alipay Mini Program SDK 1.1.2 and above.
  • Supported in Baidu Mini Program SDK 0.15.0 and above.
  • Supported in ByteDance Mini Program SDK 0.14.0 and above.
  • QQ Mini Program SDK 0.12.0 and above versions support;
  • Quick App SDK 0.8.0 and above versions support.
datasend_timeoutNumber3000Request sending cancellation time
  • Measured in milliseconds. If no result is returned within the specified time after the request is sent, the request will be canceled;
  • 1.12.9 and above versions support;
  • WeChat and Alipay Mini Program SDK support.
source_channelArrayNoneThe channel parameters to be parsed
  • By default, only the parameters utm_source, utm_content, utm_campaign, utm_medium, utm_term will be set in the pre-defined events. You can configure this parameter to parse other custom parameters, such as ['channel_code'], where the _channel_code attribute will be set as a pre-defined property of the events and the _latest_channel_code will be reported as a common property for all events;
  • 1.13.8 and above versions support;
  • WeChat, Baidu, ByteDance, and QQ Mini Program SDK support.
is_persistent_saveObjectNoneWhether to save the latest channel information to wxStorage
  • 1.13.9 and above versions are supported;
  • Two attribute parameters (utm, share) are optional and the default value is false;
  • Only WeChat mini program SDK is supported;

preset_properties

ObjectNoneConfigure to collect specified preset properties
  • Attribute parameter ( url_path);
  • WeChat mini program SDK supports configuring to collect url_path property;
autotrack_exclude_pageObjectNoneConfigure to exclude specific pages from tracking $MPViewScreen page view events
  • One parameter (pageShow);
  • For example: autotrack_exclude_page: { pageShow: ['pages/index/index'] }, after setting this, the SDK will not track the $MPViewScreen event for the page with the path 'pages/index/index'. Supported from version 1.14.2 and above;
  • Only WeChat mini program SDK is supported.
frameworkObjectNone

If using the Taro framework to develop the mini program, the element click event will be triggered multiple times. After configuring Taro parameters, it will only be tracked once

  • An attribute parameter (taro);
  • Configurable as framework: {taro: Taro}.
preset_eventsObjectNoneCustom control for preset events
  • Two attribute parameters (moments_page, collect_element), supported in version 1.14.12 and above;
  • moments_page supports controlling whether to enable data collection for WeChat Moments single page. Default is false, set to true to send data for the single page;
  • collect_element triggers this function when the user clicks on an element, and returns click event information to determine whether to collect the current element, return true to collect, return false to not collect;
  • Only supported by WeChat Mini Program SDK.


2. Full track collection logic

Event NameLifecycleCollection TimingDescription
$MPLaunch (Mini Program Launch)App.onLaunchTriggered when the Mini Program process is killed and reopened
  • Triggered once when the Mini Program is initialized globally;
$MPShow (mini-program display)App.onShowMini-program start or enter the foreground from the background
  • When the mini-program starts;
$MPHide (mini-program enters the background)App.onHideClicking the exit button in the upper right corner of the mini-program, WeChat entering the background, phone being locked, or the mini-program process being killed
  • When the mini-program enters the background from the foreground;
$MPViewScreen (mini-program page view)Page.onShowTriggered when opening a page in the mini-program, opening a page within the mini-program, or entering the foreground from the background
  • Called every time a page is opened;
  • WeChat, Alipay, and Baidu mini-program SDK support;
$MPShare (mini-program sharing)Page.onShareAppMessageTriggered when the share button is clicked after setting this function
  • Currently can only obtain the user-triggered sharing and cannot listen to feedback on whether the sharing was successful;
  • Only WeChat mini-program SDK support;
$MPClick (mini-program element click)
Collect when the event handling function defined in Page is triggered
  • Currently, only tap/longtap/longpress events are supported;
  • WeChat, Alipay, and Baidu mini-program SDK are supported;
$MPAddFavorites (mini-program favorites)page.onAddToFavoritesTriggered when the mini-program favorites button is clicked
  • Only WeChat mini-program SDK is supported;
$MPPageLeave (mini-program page leave)page.onHide or page.onUnloadTriggered when the mini-program page is hidden or unloaded
  • Only WeChat mini-program SDK is supported;

3. Set event common properties

3.1. Set event static common properties

All mini-program SDKs support setting common properties that all events have through the registerApp interface. After importing the sensorsdata.min.js file in the app.js file, you can use the init method to call the registerApp method to set common properties before calling the init method.

// 注册事件公共属性。 var sensors = require('/dist/wechat/sensorsdata.cjs.js'); sensors.setPara({ 	name: 'sensors', 	server_url: '数据接收地址' }); sensors.registerApp({ 	userLever: 'VIP3', 	userSex: '男' }); sensors.init();
JS

3.2. Set event dynamic common properties

Version requirements

WeChat mini-program SDK 1.13.27, Alipay mini-program SDK 1.1.3 and above versions, other mini-program SDKs are not supported yet.

When setting dynamic common properties, functions should be used as the property values, and the return value of the functions should be a type supported by Sensors Analytics, please refer to theData format, otherwise they will be filtered out.

var i=0 sensors.registerApp({ index: function() { return ++i; // 返回数字 }, istrue: function() { return i<10 ? true : false; // 返回bool }, isEmptyString: function() { return ""; // 返回字符串 }, isDate: function() { return new Date('December 17, 1995 03:24:00'); // 返回日期类型 }, isArrayOfStr: function() { return ["1","2","3"] // 返回元素是字符串的数组 } })
JS

In addition, if the function returns a value in an asynchronous callback, this case will also be filtered out.

sensors.registerApp({ num:function(){ setTimeout(()=>{ return 100 },500) } })
JS

The registerApp() method needs to be called before the App is instantiated to complete the registration of common properties. Otherwise, some data may not be collected for registered common properties.

4. Attribute Pluginization

Version Requirements

mini program version 0.12.0 and above is required for mini library

Attribute Pluginizationis an advanced feature used to modify the attributes of buried point events. Users can add, modify, and delete attributes for specified events (or all events) through the Attribute Pluginization function.

4.1. Interface Introduction

The SDK provides the registerPropertyPlugin method, which allows users to pass in a custom attribute plugin object to add, modify, or delete attributes for specified events.

Introduction to custom attribute plugin objects:

Method NameDescriptionExample
properties(data)

Used to modify attributes, where data is the complete data before sending.

Data includes all data types collected by the SDK:

profile_set,

profile_set_once,

track,

track_signup.


This method can be configured to add, delete, or modify attributes of the data to be sent in the data parameter.


{ 	properties:function(data){ 	 // 添加 	 // data.properties.hello = 'world' 	 	 // 修改 	 // data.properties.$title = 'new title' 	 	 // 删除 	 // delete data.properties.$screen_width		 	} }
JS


isMatchedWithFilter(data)

Used for filtering data, where data is the complete data before sending.

Same as above, data includes all data types.


If this method is configured, the properties method will only be executed when this method returns true.


If this method is not configured, the properties method will always be executed.


{ 	isMatchedWithFilter:function(data){ 		// 筛选事件名为 $SignUp 的事件 		if(data.event === '$SignUp'){ 			return true; 		} 		// 筛选在页面标题为 home 的事件 		if(data.properties.$title === 'home'){ 			return true; 		} 		 		// 其他事件不会执行 properties 方法 		return false; 	} }
JS


4.2. Example

  • Common Method: Modify the $url attribute under the $MPViewScreen event name

    sensors.registerPropertyPlugin({ isMatchedWithFilter:function(data){ 	return data.event === "$MPViewScreen"; } properties:function(data){ 	data.properties['$url'] = 'http://xxx'; } });
    JS


  • Common Method: Remove the platform attribute from all events

    sensors.registerPropertyPlugin({ isMatchedWithFilter:function(data){ 	return data.type === 'track'; } properties:function(data){ 	delete data.properties['platform']; } });
    JS


  • Note: Filtering events should be done before modifying properties as profile data can also be modified.

    sensors.registerPropertyPlugin({ isMatchedWithFilter:function(data){ 	return data.type.slice(0, 7) === 'profile'; } properties:function(data){ 	delete data.properties['aaa'] = 'bbb'; } });
    JS


  • For all data types, modify attribute values. Note: This usage is generally incorrect and can lead to unexpected situations where all data (including profiles) is modified.

    sensors.registerPropertyPlugin({ properties:function(data){ 	data.properties['aaa'] = 'bbb'; } });
    JS


  • Directly filtering and modifying properties within properties is also possible.

    sensors.registerPropertyPlugin({ properties:function(data){ 	if(data.event === '$MPViewScreen'){ 		data.properties['$url'] = 'http://xxxx'; 	} } });
    JS


5. User property setting

5.1. Retain primary attribute

You can use attributes that are valid only when set for the first time, such as the user's first recharge amount and first set nickname setOnceProfile the interface records. With setProfile  the difference is that if the set user property already exists, the record is ignored and does not overwrite the existing data, and if the property does not exist, it is automatically created.

// 设置用户属性 subscribers 为 7277 sensors.setOnceProfile({ 	email:'xxx@xx', 	favoriteFruits: ['苹果', '油桃'], 	subscribers: 7277 }); // 再次设置用户属性 subscribers 为 7278 不生效,属性值仍然是 7277 sensors.setOnceProfile({ subscribers: 7278 }); 
JS

5.2. Numeric attribute accumulation

For some numerical attributes, such as total consumption, user points and other attributes, we can use incrementProfile the original value is added, and the value after the sum is calculated and saved automatically.

// 设置用户订阅次数属性 sensors.incrementProfile({ 	subscribers: 5 }); // 对用户订阅次数进行累加,此时在神策系统中查询 subscribers 属性值为 10 sensors.incrementProfile({ 	subscribers: 5 });
JS

5.3. Append list attribute

对于List type User attributes, such as the user's favorite fruit or the user's favorite movie, can be invokedappendProfile the interface appends some new values.

// 设置用户喜爱的水果属性 sensors.appendProfile({ 	favoriteFruits: ['葡萄', '香蕉'] }); // 对用户喜爱的水果属性追加新值 sensors.appendProfile({ 	favoriteFruits: ['苹果', '桃子'] });
JS

6. Custom anonymous ID

By default, the SDK generates an anonymous ID and can ensure that the ID is unique. If you need to replace the anonymous ID assigned by default, you can do so after configuring the initial SDK parameters(initBefore interface call) identify method replacement.

// 自定义匿名 ID sensors.identify('自定义匿名 ID', true);
JS

7. Associated login ID

By default, the events triggered in the small program are identified by the UUID generated by the SDK, which can be invoked by the developer login api, pass the business ID, associated with the anonymous ID.

// 关联登录 ID sensors.login('登录 ID');
JS

8. Get preset properties

In some cases, you may need to obtain the SDK preset properties on the front end. The SDK supports thisgetPresetProperties method obtain the preset properties of some events.

// 获取事件预置属性 sensors.getPresetProperties();
JS
  • This interface is only supported by wechat mini program SDK

9. Switch back to anonymous ID

SDK provideslogout The interface switches back to the call login the previous anonymous ID of the interface.

// 切换回匿名 ID sensors.logout();
JS

10. Clear public attribute

The SDK provides public properties that are set by calling registerApp clearAppRegister interface clears these attributes.

// 清除设置的 current_url 和 referrer 公共属性 sensors.clearAppRegister(['current_url', 'referrer']);
JS

11. Example Set the anonymous ID to OpenID

WeChat Mini Program SDK provides the bindOpenid interface to set the anonymous ID as OpenID.

wx.request({ 	url: '获取 OpenID 的后端接口', 	success: function(res){ 		sensors.bindOpenid(res.openid); 	}, 	complete: function(){ 		sensors.init(); 	} });
JS
  • This interface is only supported under the following two conditions! Those who do not meet the following conditions can use the identify('openid', true) interface;
  • bindOpenid is only supported in ID-Mapping 3.0. Please confirm if the SA backend supports ID-Mapping 3.0 before using it;
  • bindOpenid requires WeChat Mini Program SDK version v1.18.3 or higher.

12. Get anonymous ID

The Mini Program SDK provides the getAnonymousID interface to get anonymous ID.

sensors.getAnonymousID();
JS

13. Collect the duration of Mini Program page visits

The Mini Program SDK can automatically collect by enabling the $MPPageLeave preset event.

  1. WeChat Mini Program SDK version 1.14.20 and above are supported
  2. Alipay Mini Program SDK version 1.1.7 and above are supported
sensors.setPara({ 	autoTrack: { 		pageLeave: true // 默认不开启,为 false 	} }); // $MPPageLeave 预置事件中会采集 event_duration 预置属性来记录页面浏览时长,单位为秒
JS

14. Local storage encryption function

The information saved in the SDK in local storage currently includes user information and attribute information set by register. The data in storage can be deeply encrypted to ensure security.

Version requirements

  • WeChat Mini Program SDK 1.14.9 and above versions

14.1. Function configuration

 // app.js var sensors = require('/dist/wechat/sensorsdata.cjs.js'); sensors.setPara({ 	name: 'sensors', 	server_url: '数据接收地址', 	encrypt_storage : true // 是否开启本地加密存储 });
JS

15. Encryption of tracking data

In order to enhance the security of tracking data, Sensormind supports encrypting tracking data and storing and sending it in ciphertext form.

  • This feature requires cooperation from the server side. You can contact the Senseu customer success manager/project manager to assist in enabling the server-side decryption function.
  • Considerations when the encryption plugin is discontinued:
    • When the main SDK version is rolled back to a version number greater than or equal to 1.14.27, only the encryption plugin is discontinued.
    • When the main SDK version needs to be rolled back to a version below 1.14.27, the encryption plugin needs to be discontinued. You need to modify the configuration "storage_prepare_data_key".


sensors.setPara({ storage_prepare_data_key:''//本地存储 key 值,字符串格式 })
JS
  • After enabling encryption, if the server does not support decryption, the data cannot be stored in the database and will be lost. There will be no error in the event management.

Version requirements

  • WeChat Mini Program SDK v.14.27 and above
  • Edge v0.3.0 and above
  • SDF 2.3 and above

15.1. Enable encryption on the SDK side

Refer to the plugin encryption track data encryption

16. Support dynamic disable/enable API

// 禁用 API 执行 sensors.disableSDK() // 恢复 API 执行 sensors.enableSDK()
CODE

Note: This must be called after the init function. Please refer to disableSDK for more details.

  • This interface is only supported by the WeChat Mini Program SDK.

17. Customize encryption for sent data

If you need to customize the encryption format for sent data, such as national standard cryptographic algorithms, you can use the custom encryption plugin.

  • This interface is only supported by the WeChat Mini Program SDK.