Skip to main content

Uni-app App SDK User Guide

Tingyun uni app SDK, suitable for uni app app, not suitable for uni app x. Collect data and upload it to Tingyun Web product.

Support page, uni. request network requests, JavaScript errors, and user operation monitoring. Native network calls are collected by the corresponding native SDK. The Vue3 project supports Vue and nvue pages; Automatic operation requires the installation of the Tingyun compilation plugin. Please use the corresponding platform SDK for web and mini programs.

Uni.request supports two calling methods: callback and Promise: retaining the original RequestTask when passing in a function callback; When there is no function callback, you can continue to use await, . then(), and . match().

##Installation Wizard

1. Install SDK​

Execute in the root directory of the project:

npm install @tingyun-sdk/uniapp-app

2. Create initialization file​

When accessing SDK, two points need to be considered:

  • **Initialization Order ** : The statically imported module executes before the entry body, directly calling init() at the top of main. js or main. ts, which may be later than the request in the business module. Events that occurred before initialization cannot be replenished.
  • Configuration Maintenance: Centralize the management of SDK import, configuration, and initialization calls for easy searching and adjustment.

Therefore, it is recommended to place these codes in a separate 'tingyun/init.js', where TypeScript projects use' tingyun/init.ts' and import them first at the application entrance. The initialization file only relies on SDK and necessary configurations to avoid introducing business modules or circular dependencies.

The recommended locations are as follows:

Project sourceInitialization fileApplication portal
CLI creationsrc/tingyun/init.js or src/tingyun/init.tssrc/main.js or src/main.ts
HBuilderX createstingyun/init.js' or 'tingyun/init.ts'root directory' main. js' or 'main. ts'

Example of directory structure (using JavaScript as an example):

Projects created by CLI/
├── src/
│ ├── tingyun/
│ │ └── init.js # New: SDK initialization file
│ ├── main.js
│ ├── manifest.json
│ └── pages.json
└── package.json

Projects created by HBuilderX/
├── tingyun/
│ └── init.js # New: SDK initialization file
├── main.js
├── manifest.json
└── pages.json

The CLI project still uses its original directory and compilation dependencies even when opened in HBuilderX.

Retrieve the corresponding application's data upload address and token from the Tingyun Web Console, and fill in the initialization file:

import Tingyun from '@tingyun-sdk/uniapp-app'

Tingyun.init({
beacon: '<Data upload address containing protocol>',
token: '<Application Token>',
})

export default Tingyun

3. Load at the application entrance​

Vue2 and Vue3 projects are added at the top of 'main. js' or' main. ts', before importing other items:

// #ifdef APP
import './tingyun/init'
// #endif

If you have specific requirements for conditional compilation, please refer to the uni app official conditional compilation document.

4. Verify access​

Run the app again and search for '[tingyun uniapp]' in the running console of HBuilderX or in the running logs of connected devices. The following log indicates that the SDK has completed initialization (time is an example):

2026-09-16 10:00:00.000 +08:00 [tingyun-uniapp] [INFO] [init] SDK initialized

Open and switch the application page, wait for the report, and then view the corresponding page data in the Tingyun Web Console. When the compiled plugin has been connected, you can also click the existing '@ click' button on the page to verify user operation collection. The naming rules are described in the 'Event and Operation Names' section of the compiled plugin documentation.

##Optional configuration

###Vue3 user operation collection

The uni app Vue3 project can collect user operations such as button clicks, and requires cooperation with the Tingyun compilation plugin '@ tingyun common/cite plugin uniapp'. This plugin supplements the collection of information for page events during construction, and the integration steps can be found in the uni app Vite plugin usage guide.

Complete SDK initialization when only using page, request, error, and manual operation functions.

##SDK configuration

Pass in the configuration through 'Tingyun. init()' in the initialization file. The following lists the configuration types and default behaviors:

interface InitConfig {
beacon: string//Required, including the data upload address of the protocol
token: string//Required, apply token
key? : string//Application key

//Turn off the log; Info basic log (default); Debug detailed diagnostic logs.
logging? : { level?: 'off' | 'info' | 'debug' }
//Native session waiting limit (milliseconds), default 5000, range 0-10000; 0 does not wait.
nativeContextWaitTimeout? : number

page? : {
enabled? : boolean//Page monitoring, default to true
autoEnabled? : boolean//Automatic page monitoring, default to true
}
jsError? : {
enabled? : boolean//Error monitoring, default to true
autoEnabled? : boolean//Automatic error monitoring, default to true
uploadEmptyFileErrors? : boolean//Collection without file name error, default to true
}
action? : {
enabled? : boolean//Operation monitoring, default to true
manualEnabled? : boolean//Manual operation, default to true
autoEnabled? : boolean//Automatic operation, default to true
}

//The five switches correspond to the URL, request header, request body, return header, and return body in sequence, and are all turned off by default.
//1. Enable full data collection, 0. Disable; If '00100' represents the complete collection request body. The rules for the fields below take effect independently.
collect_all_param? : string
//Specify the collection field, default empty; Collect orderId from the URL as [{type: 1, key: 'orderId'}].
opt_custom_param_rule? : Array<{
type: 1 | 2 | 3 | 4 | 5//Corresponding to URL, request header, request body, return header, return body in sequence
//Field name; URL、 Request and return bodies support nested paths, such as' order. type ',' items [0]. id '
key: string
}>
}

When the native interface returns normally but the session ID is not yet ready, the SDK continues to collect data, suspends self reporting, and attempts to read once per second. Release after obtaining a valid session; Timeout using SDK session release and stopping polling. Missing plugin or abnormal first call without waiting. The limited number of waiting configurations is limited to the above range, and other illegal values use default values; The waiting queue is still limited by a capacity of 100 entries, and new data will be discarded when it is full. The detailed process can be viewed by opening the debug log.

API Description​

SDK API calling method​

After successful SDK initialization, the page and business module can call the business API in the following three ways. Nvue recommends using public entrances; When using module import, it is recommended to import the initialization file created earlier.

The sdk in subsequent API examples refers to theuni. $tingyunApp that has been confirmed to be available.

Method 1: Call through public entrance (recommended)

After successful SDK initialization, provide uni. $tingyunApp. Through this entrance, you can directly use the initialized SDK, especially suitable for nvue pages, which can reduce the volume of duplicate packaged SDKs in page products.

**Before calling, it must be null **: When the SDK has not been initialized successfully or the public entrance is unavailable, 'uni. $tingyunApp' may be undefined. Use if (SDK) or optional chain SDK?.method(), Avoid affecting business execution.

JavaScript call example, taking setting user ID as an example:

const sdk = uni.$tingyunApp
//Confirm that the public entrance is available before calling.
if (sdk) {
sdk.setUid('user-001')
}

TypeScript call example, using type only import to provide type hints:

import type { TingyunApi } from '@tingyun-sdk/uniapp-app'

const sdk: TingyunApi | undefined = uni.$tingyunApp
sdk? .setUid('user-001')

Method 2: Import initialization file (recommended module import method)

Importing the previously created tingyun/init.js or tingyun/init.ts will first execute its initialization code, and then obtain the exported SDK. Taking setting a user ID as an example, @ points to the project source code directory:

import Tingyun from '@/tingyun/init'

Tingyun.setUid('user-001')

This approach ensures initialization is performed first through module dependencies. Importing this file on the nvue page may result in duplicate packaging of the SDK. It is recommended to use method one.

Method 3: Directly import SDK package

Directly importing only retrieves SDK APIs and does not execute project initialization files. Before use, it is necessary to ensure that the application portal has completed initialization and is suitable for code that already has unified initialization management. Call example:

import Tingyun from '@tingyun-sdk/uniapp-app'

Tingyun.setUid('user-001')

When the public entrance has been initialized, API calls will be forwarded to that entrance, sharing the same SDK state.

Public types can be imported from the package root through 'import type', including InitConfig, TingyunApi, operation types, ContextMap, error inputs, and page installation types.

Manual operation: newAction​

Manually create operations, record operation time, execution results, and associated requests.

type ActionContextValue =
| string
| number
| boolean
| null
| ActionContextValue[]
| { [key: string]: ActionContextValue }

type ActionContext = Record<string, ActionContextValue>

interface ActionOptions {
name: string//Operation name
op?: string//operation type
desc? : string//Operation description
context? : ActionContext//Additional information for this operation
}

interface ActionEndOptions {
status? : 'success' | 'fail'
context? : ActionContext
}

interface ActionHandle {
readonly id: string
readonly kind: 'manual' | 'interaction'
readonly name: string
end(options?: ActionEndOptions): void
fail(options?: ActionEndOptions): void
}

declare function newAction(options: ActionOptions): ActionHandle
const action = sdk.newAction({ name: 'custom-action' })

uni.request({
url: ' https://example.com/api ',
success: () => action.end(),
fail: () => action.fail(),
})

name is required, and the saved name must contain at least one non blank character. The maximum length of a name is 1024, and if it is excessively long, it will participate in the same name judgment after truncation. Opand desc are optional strings. Op, desc, and context do not have length limits set.

The top layer is a regular object, and members follow the recursive type mentioned above. Simultaneously validate finite numbers, regular objects, and circular references during runtime; Functions, undefined members, special objects, and property read failures are considered illegal parameters. SDK copies legitimate data, and subsequent modifications to the original object will not affect the operation data.

Multiple automatic operations and manual operations with different names can be associated with requests simultaneously, and each operation ends independently and is reported. The same name manual operation retains the name before ending and returns an empty handle by repeatedly creating it. Creating parameters that are illegal, SDK not initialized, or manually closing collection also returns an empty handle; Its id is an empty string, and end() and fail () can be safely called.

End() default success, can be specified as success or failthrough status; Fail () Fixed failure. The context provided at the end is merged according to the top-level attribute, and the attribute with the same name uses the new value. Illegal termination of parameters keeps the operation in its original state, and the caller can pass in valid parameters again to terminate. Repeat to maintain idempotency.

After the operation is completed, wait for the associated request to be completed before reporting; The success or failure of manual operation is specified by the caller.

Manual page monitoring: getPageMixin​

Only collect page monitoring data for pages that are connected to mixin.

interface PageMonitoringMixin {
onLoad?(query?: Record<string, string | undefined>): void
onShow?(): void
onReady?(): void
onUnload?(): void
}
declare function getPageMixin(): PageMonitoringMixin

Set page: {enabled: true, autoEnabled: false} during initialization, and then add the returned mixin to the target page:

export default {
mixins: [uni.$tingyunApp.getPageMixin()],
}

Please complete SDK initialization before loading the page. When SDK is not initialized, page monitoring is turned off, or automatic page monitoring is turned on, an empty object is returned. HookPage() is a historical interface, and since 1.1.0, calling it does not produce page monitoring effects.

Manual error reporting: captureException​

Manually report errors. Automatic error collection relies on the runtime environment to trigger callbacks uni. onError and uni. onUnhandledRefection; Errors that have not been notified to the SDK through these callbacks can be reported by calling this API.

type ErrorDetails = (
| { message: string; stack?: string }
| { message?: string; stack: string }
) & { fileName?: string; lineNumber?: number; columnNumber?: number }

declare function captureException(
error: Error | string | ErrorDetails,
options?: { category?: 'js' | 'other' },
): string | undefined

Error can be passed in as an Error object, an error object containing message/stack, or error text. Options. category can specify js (default) or other.

try {
JSON.parse('invalid JSON')
} catch (error) {
if (error instanceof Error || typeof error === 'string') {
sdk.captureException(error)
}
}

When recording normally, it returns a string error tracking ID. When not recording, it returns undefined, which does not indicate a successful upload. JsError. enabled needs to be enabled; When uploadEmptyFileErrors: fall , ignore the error of not being able to resolve the file name.

Set User ID: setUid​

Set up business user IDs to associate monitoring data with users, facilitating the identification of specific user issues.

declare function setUid(uid: string | number): void
sdk.setUid('user-001')

The number is first converted into a string, with a maximum length of 50 and truncated if it is too long. Save to local storage after setting up; Passing an empty string can clear it. No return value.

Setting and removing additional information: setContext/removeContext​

Add or remove custom additional information for subsequent reporting of monitoring data.

type ContextMap = Record<string, ActionContext>
declare function setContext(key: string, value: ActionContext): void
declare function setContext(contexts: ContextMap): void
declare function removeContext(key: string): void

Key is the string name (allowing empty strings),value is a regular object; You can also batch set an object. Each named value follows the JSON data rules of newAction.context, and strings, arrays, etc. must be placed in regular objects.

sdk.setContext('custom', { field: 'value' })

Delete when the information is no longer needed:

sdk.removeContext('custom')

Objects with the same name are shallowly merged according to the first layer properties. SDK copies valid context during setup, and subsequent modifications to input do not affect saved data. Illegal named values retain old values and stop this call; The previously successful items in the batch are still valid. The named values null and undefined passed in JavaScript calls will be ignored. To delete them, please use removeContext() .

The information is only retained during the current runtime, and the current value is read when grouping; Both methods have no return value. The manually operated context only applies to that operation.