Title: WeChat Mini Program SDK Locale: en URL: https://sensorswave.com/en/docs/data-integration/client-sdks/wechatMini/ Description: WeChat Mini Program SDK integration guide and API reference The Sensors Wave WeChat Mini Program SDK is a data collection and A/B testing tool designed specifically for WeChat Mini Programs, helping you easily implement user behavior analysis, funnel analysis, retention analysis, and more. ## Core Features The WeChat Mini Program SDK provides the following core capabilities: - **Event Tracking**: Manually track custom events and user behaviors - **Auto-tracking**: Automatically collect mini program lifecycle events, page views, shares, clicks, and more - **User Identification**: Support for anonymous user and logged-in user identity association - **User Properties Management**: Complete user property operations (set, append, incremental updates, etc.) - **A/B Testing Integration**: Support for Feature Gates and experiment variable retrieval - **Batch Sending**: Optimize network request performance, batch send up to 10 events every 5 seconds - **Common Properties**: Support for static and dynamic common properties, automatically attached to all events - **Device Information Collection**: Automatically collect device brand, model, network type, and other preset properties ## Installation ### NPM Installation ```bash npm install @sensorswave/wechat-mini ``` ## Quick Start ### Basic Initialization Initialize the SDK in your mini program's `app.js`: ```javascript // app.js // Initialize SDK Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', // Data reporting endpoint debug: false, // Debug mode autoCapture: true // Enable auto-tracking }); ``` ### Send Your First Event After initialization, you can report events from any page: ```javascript // pages/index/index.js Page({ handleButtonClick() { // Track user button click Sensorswave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); } }); ``` ## Configuration Options The second parameter of the `init` method is a configuration object that supports the following options: | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiHost` | `string` | `''` | **Required**, API endpoint for data reporting, can be viewed in Pipeline | | `debug` | `boolean` | `false` | Whether to enable debug mode, outputs detailed logs to console when enabled | | `autoCapture` | `boolean` | `true` | Whether to enable auto-tracking, automatically collects mini program lifecycle and page events | | `enableClickTrack` | `boolean` | `false` | Whether to enable automatic click tracking (tracks main clickable elements) | | `batchSend` | `boolean` | `true` | Whether to use batch sending, sends up to 10 events every 5 seconds | | `enableAB` | `boolean` | `false` | Whether to enable A/B testing functionality | | `abRefreshInterval` | `number` | `600000` | A/B testing configuration refresh interval (milliseconds), default 10 minutes | ### Complete Configuration Example ```javascript // app.js Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', debug: false, // Disable debug in production autoCapture: true, // Enable auto-tracking enableClickTrack: true, // Enable click tracking batchSend: true, // Batch sending for performance enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Refresh A/B test data every 10 minutes }); ``` > **Tip**: In production environments, it's recommended to disable `debug` mode to avoid excessive console output. ## API Methods ### Event Tracking #### trackEvent - Track Custom Events Manually track custom events and their properties. **Parameters**: - `eventName` (string, required): Event name - `properties` (Object, optional): Event properties as key-value pairs **Example**: ```javascript // Track button click Sensorswave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); ``` **Real-world Scenario Examples**: ```javascript // E-commerce scenario: User views product Sensorswave.trackEvent('ProductView', { product_id: '12345', product_name: 'Wireless Bluetooth Headphones', category: 'Electronics', price: 299.00, currency: 'CNY' }); // E-commerce scenario: User adds to cart Sensorswave.trackEvent('AddToCart', { product_id: '12345', quantity: 1, price: 299.00 }); // Content platform: Article reading Sensorswave.trackEvent('ArticleRead', { article_id: 'article_001', title: 'WeChat Mini Program Performance Optimization Tips', category: 'Tech Blog', read_duration: 120 // Reading duration (seconds) }); ``` #### track - Advanced Event Tracking Send a complete event object with more fine-grained control. This method allows you to manually specify all event fields. **Parameters**: - `eventData` (SensorswaveSendEvent, required): Complete event object containing the following fields: - `event` (string, required): Event name - `properties` (Object, optional): Event properties - `time` (number, required): Timestamp (milliseconds) - `trace_id` (string, required): Request tracking ID - `anon_id` (string, optional): Anonymous user ID - `login_id` (string, optional): Logged-in user ID. Either login_id or anon_id must be provided; when both are provided, login_id takes priority - `user_properties` (Object, optional): User property operations **Example**: ```javascript Sensorswave.track({ event: 'UserSignup', properties: { signup_method: 'wechat', referral_code: 'FRIEND2024' }, time: Date.now(), trace_id: 'signup_67890', anon_id: 'anonymous-user-id', login_id: 'user_12345', user_properties: { $set: { signup_date: new Date().toISOString(), referral_source: 'friend' }, $set_once: { initial_campaign: 'spring_2024' } } }); ``` > **Note**: The `track` method is an advanced feature. For most scenarios, `trackEvent` is sufficient. ### User Identification #### identify - Set Logged-in User ID Set the logged-in user ID and send a binding event to associate anonymous behaviors with an identified user. **Parameters**: - `loginId` (string | number, required): Unique identifier for the user (e.g., user ID, phone number, email) **Example**: ```javascript // Set user ID after user login Sensorswave.identify('user_12345'); ``` **Complete Login Flow Example**: ```javascript // User login flow function handleUserLogin(code) { // Call login API wx.request({ url: 'https://your-api.com/login', method: 'POST', data: { code }, success: (res) => { const { userId } = res.data; // Set user ID and associate anonymous behaviors Sensorswave.identify(userId); }, fail: (error) => { console.error('Login failed:', error); } }); } ``` > **Important reminder**: If `loginId` contains sensitive information (such as phone numbers, email addresses, ID card numbers, etc.), please encrypt it before transmission to avoid reporting sensitive information in plain text. #### setLoginId - Set Login ID Only Set the logged-in user ID without sending a binding event. Use this method if you only want to identify users without associating them. **Parameters**: - `loginId` (string | number, required): Unique identifier for the user **Example**: ```javascript Sensorswave.setLoginId('user_12345'); ``` > **Important reminder**: If `loginId` contains sensitive information (such as phone numbers, email addresses, ID card numbers, etc.), please encrypt it before transmission to avoid reporting sensitive information in plain text. > **Usage recommendation**: In most cases, the `identify` method is recommended because it records user identity association events, which helps with subsequent analysis. #### getLoginId - Get Current Login ID Get the login ID of the currently identified user. **Returns**: string | number **Example**: ```javascript const loginId = Sensorswave.getLoginId(); console.log('Current login ID:', loginId); ``` #### getAnonId - Get Anonymous ID Get the current user's anonymous ID. This ID is automatically generated and persists across sessions. **Returns**: string **Example**: ```javascript const anonId = Sensorswave.getAnonId(); console.log('Anonymous user ID:', anonId); ``` ### User Properties User properties are used to describe user characteristics, such as membership level, registration time, preferences, etc. Unlike event properties, user properties are persistently stored and associated with the user. #### profileSet - Set User Properties Set user properties, overwriting them if they already exist. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```javascript // Set user properties after user completes registration Sensorswave.profileSet({ name: 'Zhang San', age: 30, plan: 'premium', city: 'Beijing' }); ``` #### profileSetOnce - Set Only Once Set user properties only if they don't exist. Existing properties will not be overwritten. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```javascript // Record user's first visit information (recorded only once, won't be overwritten later) Sensorswave.profileSetOnce({ first_visit_date: '2024-01-15', initial_referrer: 'search', initial_campaign: 'spring_sale' }); ``` #### profileIncrement - Increment Numeric Properties Increment or decrement numeric user properties. Only supports numeric properties. **Parameters**: - `properties` (Object, required): Properties to increment/decrement and their values **Example**: ```javascript // Increment single property Sensorswave.profileIncrement({ login_count: 1 }); // Increment multiple properties Sensorswave.profileIncrement({ login_count: 1, points_earned: 100, purchases_count: 1 }); ``` #### profileAppend - Append to Array Properties Append new values to array-type user properties without deduplication. **Parameters**: - `properties` (Object, required): Properties to append and their array values **Example**: ```javascript Sensorswave.profileAppend({ categories_viewed: ['Electronics', 'Phone Accessories'], tags: ['New User', '2024 Q1'] }); ``` #### profileUnion - Append to Set Properties (Deduplicated) Append new values to array-type user properties with automatic deduplication. **Parameters**: - `properties` (Object, required): Properties to append and their array values **Example**: ```javascript // First call Sensorswave.profileUnion({ interests: ['Technology', 'Gaming'] }); // Second call, 'Technology' will not be duplicated Sensorswave.profileUnion({ interests: ['Technology', 'Music'] // Only 'Music' will be added }); ``` #### profileUnset - Delete Specific Properties Set specified user properties to null. **Parameters**: - `propertyNames` (string[], required): Array of property names to set to null **Example**: ```javascript // Delete single property Sensorswave.profileUnset(['temporary_campaign']); // Delete multiple properties Sensorswave.profileUnset(['old_plan', 'expired_flag', 'temp_id']); ``` #### profileDelete - Delete All User Properties Delete all user properties for the current user. This operation cannot be undone. **Example**: ```javascript // Delete all user properties when user closes account Sensorswave.profileDelete(); ``` > **Warning**: `profileDelete` will delete all user properties. Use with caution. #### User Properties Usage Example **Membership Upgrade Scenario**: ```javascript function handleMembershipUpgrade(newPlan) { // Update membership level and upgrade time Sensorswave.profileSet({ plan: newPlan, upgrade_time: new Date().toISOString() }); // Increment upgrade count Sensorswave.profileIncrement({ upgrade_count: 1 }); // Track upgrade event Sensorswave.trackEvent('MembershipUpgrade', { from_plan: 'basic', to_plan: newPlan }); } ``` ### Common Properties Common properties are automatically added to all events, suitable for general information that needs to be included in every event. Supports both static properties (string values) and dynamic properties (function return values). #### registerCommonProperties - Register Common Properties Register static or dynamic common properties that will be automatically included in all events. **Parameters**: - `properties` (Record, required): Properties to register - Static properties: strings, numbers, booleans - Dynamic properties: functions (called when sending events) **Example**: ```javascript Sensorswave.registerCommonProperties({ // Static properties app_version: '1.0.0', environment: 'production', // Dynamic properties (called when sending events) current_time: () => new Date().toISOString(), user_session_id: () => getSessionId() }); ``` #### clearCommonProperties - Clear Common Properties Remove specified registered common properties. If no parameters are provided, all common properties will be cleared. **Parameters**: - `propertyNames` (string[], optional): Array of property names to remove **Example**: ```javascript // Clear specific properties Sensorswave.clearCommonProperties(['app_version', 'user_session_id']); // Clear all common properties Sensorswave.clearCommonProperties(); ``` > **Note**: Common properties increase the data size of each event. It's recommended to only add truly necessary common properties. ### A/B Testing The WeChat Mini Program SDK has built-in A/B testing support, allowing you to get feature flag status and experiment variables. #### Enable A/B Testing ```javascript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Configuration refresh interval (10 minutes) }); ``` #### checkFeatureGate - Check Feature Gate Check if a feature flag is enabled for the current user. Returns a Promise that resolves to a boolean value. **Parameters**: - `key` (string, required): Feature gate key **Returns**: Promise **Example**: ```javascript // Check if feature is enabled Sensorswave.checkFeatureGate('new_checkout_flow') .then(isEnabled => { if (isEnabled) { // Show new feature this.setData({ showNewCheckout: true }); } else { // Show old feature this.setData({ showNewCheckout: false }); } }); // Using async/await async function initFeature() { const isEnabled = await Sensorswave.checkFeatureGate('advanced_search'); if (isEnabled) { this.setData({ enableAdvancedSearch: true }); } } ``` #### getExperiment - Get Experiment Variables Get experiment variable data for the current user. Returns a Promise that resolves to an experiment configuration object. **Parameters**: - `key` (string, required): Experiment key **Returns**: Promise The returned object contains the experiment's variable configuration values (Record). **Example**: ```javascript // Get experiment configuration Sensorswave.getExperiment('homepage_layout') .then(experiment => { if (experiment) { // Apply experiment configuration this.setData({ layoutType: experiment.layout_type }); } }); // Using async/await async function initExperiment() { const experiment = await Sensorswave.getExperiment('pricing_display'); if (experiment) { const { price_format, discount_type } = experiment; this.setData({ priceFormat: price_format, discountType: discount_type }); } } ``` **Complete A/B Testing Example**: ```javascript // E-commerce homepage CTA button A/B test Page({ data: { buttonText: 'Buy Now', buttonColor: '#ff6600' }, async onLoad() { try { const experiment = await Sensorswave.getExperiment('homepage_cta_test'); if (experiment) { const { button_text, button_color, button_size } = experiment; this.setData({ buttonText: button_text || 'Buy Now', buttonColor: button_color || '#ff6600', buttonSize: button_size || '16px' }); } } catch (error) { console.error('Failed to get experiment variables:', error); // Use default configuration } } }); ``` > **Tip**: A/B testing functionality requires configuring experiments and feature gates in the Sensors Wave backend before use. ## Auto-tracking When auto-tracking is enabled, the SDK automatically collects the following event types: | Event Name | Description | Trigger Timing | |------------|-------------|----------------| | `$MPLaunch` | Mini program launch | Mini program initialization complete (App.onLaunch) | | `$MPShow` | Mini program show | Mini program brought to foreground (App.onShow) | | `$MPHide` | Mini program hide | Mini program switched to background (App.onHide) | | `$MPPageView` | Mini program page view | Page load complete (Page.onShow) | | `$MPPageLeave` | Mini program page leave | Page unload or switch (Page.onHide) | | `$MPShare` | Mini program share | Share function called (onShareAppMessage) | | `$MPClick` | Mini program element click | Click on interactive element (requires `enableClickTrack`) | ### $MPClick Event Details When `enableClickTrack` is enabled, the SDK automatically captures click events on elements. **Important notes:** - **Only elements with bound event handlers are tracked** — The SDK proxies Page/Component event functions, so elements must have `bindtap`/`catchtap` (or similar) handlers to be captured - **Supported event types**: `tap`, `longtap`, `longpress` ```xml Submit No event handler ``` ### Enable Auto-tracking ```javascript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', autoCapture: true, // Enable auto-tracking enableClickTrack: true // Enable automatic click tracking }); ``` ### Auto-tracking Use Cases - **`$MPLaunch`**: For analyzing mini program launch count, launch source scenarios, user activation, etc. - **`$MPShow` / `$MPHide`**: For analyzing mini program usage duration, session analysis, user stickiness, etc. - **`$MPPageView` / `$MPPageLeave`**: For analyzing page view paths, page stay duration, page popularity, etc. - **`$MPClick`**: For analyzing user interaction behaviors, feature usage, click heatmaps, etc. - **`$MPShare`**: For analyzing sharing behaviors, viral effects, fission analysis, etc. > **Tip**: Auto-tracking can significantly reduce manual coding work, but increases data volume. Enable selectively based on actual needs. ## Important Considerations ### Performance Optimization - Avoid calling `trackEvent` frequently in loops; consider merging events or using throttling - Batch sending is enabled by default, effectively reducing network requests - Auto-tracking adds some performance overhead; enable only when needed - Be mindful of mini program storage capacity limits (10MB) ### Data Security - Don't pass sensitive information in event properties (such as passwords, ID numbers, complete phone numbers) - Source Token should be kept secure; avoid exposure in public code repositories - Ensure the data reporting endpoint is configured as a valid domain in WeChat Public Platform ### Platform Limitations - **Network request domain whitelist**: Ensure the data reporting endpoint is configured in the mini program backend - **Maximum concurrent requests**: WeChat Mini Program has limits on concurrent requests; batch sending has been designed with this limitation in mind - **User privacy protection**: Comply with WeChat Mini Program user privacy protection guidelines and obtain necessary user authorizations ### Data Loss Risk - Client-side tracking may be affected by network environment, leading to data loss - For core business data, server-side tracking is recommended. See [Tracking Strategy Selection](../tracking-strategy.mdx) ## Debug Mode When debug mode is enabled, the SDK outputs detailed logs to the console: ```javascript Sensorswave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', debug: true // Enable debug mode }); ``` Debug logs will output: - SDK initialization information - Event tracking information - Error information ## FAQ ### Why is my data not being reported successfully? Check the following: 1. **Is the Source Token correct**: Confirm that the `sourceToken` parameter is correct 2. **Is the data reporting endpoint correct**: Confirm that the `apiHost` configuration is correct 3. **Network domain whitelist**: Confirm the data reporting endpoint is configured in the mini program backend 4. **Network connection**: Check the console for network request errors 5. **Debug mode**: Enable `debug: true` to view console logs ## Related Documentation - [Tracking Strategy Selection](../tracking-strategy.mdx): Understand the pros and cons of server-side vs. client-side tracking - [How to Properly Identify Users](../user-identification.mdx): Best practices for user identification - [Data Model](../data-model.mdx): Understand Sensors Wave's data structure - [Events and Properties](../events-and-properties.mdx): Event design guidelines and best practices - [Preset Events and Properties](../preset-events-and-properties.mdx): View detailed documentation of all preset events and properties --- **Last Updated**: April 7, 2026 **License**: Apache-2.0