SDK API (Mini Program)
|
Collect
1. SDK initialization parameters
Parameter | Type | Default Value | Meaning | Remarks |
---|---|---|---|---|
name | String | sensors | A 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_url | String | Data receiving URL |
| |
autoTrack | Object | None | Whether to enable automatic data collection |
|
show_log | Boolean | true | Whether to print log |
|
send_timeout | Number | 1000 | Request sending timeout (if a request is sent and there is no response after a certain time, the next data will be sent) |
|
use_client_time | Boolean | false | Whether to use the client's time |
|
max_string_length | Number | 300 | Maximum 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_path | Boolean | true | After 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. |
|
batch_send | Boolean | true | Whether to use batch data sending feature in the Mini Program. |
|
datasend_timeout | Number | 3000 | Request sending cancellation time |
|
source_channel | Array | None | The channel parameters to be parsed |
|
is_persistent_save | Object | None | Whether to save the latest channel information to wxStorage |
|
preset_properties | Object | None | Configure to collect specified preset properties |
|
autotrack_exclude_page | Object | None | Configure to exclude specific pages from tracking $MPViewScreen page view events |
|
framework | Object | None | 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 |
|
preset_events | Object | None | Custom control for preset events |
|
2. Full track collection logic
Event Name | Lifecycle | Collection Timing | Description |
---|---|---|---|
$MPLaunch (Mini Program Launch) | App.onLaunch | Triggered when the Mini Program process is killed and reopened |
|
$MPShow (mini-program display) | App.onShow | Mini-program start or enter the foreground from the background |
|
$MPHide (mini-program enters the background) | App.onHide | Clicking 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 |
|
$MPViewScreen (mini-program page view) | Page.onShow | Triggered when opening a page in the mini-program, opening a page within the mini-program, or entering the foreground from the background |
|
$MPShare (mini-program sharing) | Page.onShareAppMessage | Triggered when the share button is clicked after setting this function |
|
$MPClick (mini-program element click) | Collect when the event handling function defined in Page is triggered |
| |
$MPAddFavorites (mini-program favorites) | page.onAddToFavorites | Triggered when the mini-program favorites button is clicked |
|
$MPPageLeave (mini-program page leave) | page.onHide or page.onUnload | Triggered when the mini-program page is hidden or unloaded |
|
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();
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"] // 返回元素是字符串的数组 } })
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) } })
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 Name | Description | Example |
---|---|---|
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. |
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. |
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'; } });
JSCommon Method: Remove the platform attribute from all events
sensors.registerPropertyPlugin({ isMatchedWithFilter:function(data){ return data.type === 'track'; } properties:function(data){ delete data.properties['platform']; } });
JSNote: 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'; } });
JSFor 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'; } });
JSDirectly 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 });
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 });
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: ['苹果', '桃子'] });
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);
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');
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();
- 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();
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']);
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(); } });
- 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();
13. Collect the duration of Mini Program page visits
The Mini Program SDK can automatically collect by enabling the $MPPageLeave preset event.
- WeChat Mini Program SDK version 1.14.20 and above are supported
- Alipay Mini Program SDK version 1.1.7 and above are supported
sensors.setPara({ autoTrack: { pageLeave: true // 默认不开启,为 false } }); // $MPPageLeave 预置事件中会采集 event_duration 预置属性来记录页面浏览时长,单位为秒
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 // 是否开启本地加密存储 });
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 值,字符串格式 })
- 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()
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.
Note: The content of this document is a technical document that provides details on how to use the Sensors product and does not include sales terms; the specific content of enterprise procurement products and technical services shall be subject to the commercial procurement contract.