@alvie-tech/react-native-tiktok-business-sdk

中文文档
1.7.2发布于 2026/11/05MITTypeScriptESM + CJS零依赖近 30 天下载 9404

A React Native bridge for the TikTok Business SDK

原始使用文档
文档目录28 节
  1. ✨ Features
  2. Installation
  3. Expo / Continuous Native Generation
  4. iOS Setup
  5. Android Setup
  6. Usage
  7. Importing the Library
  8. Initialize the SDK
  9. Identify a User
  10. Logout
  11. Track a Standard Event
  12. Track a Content Event
  13. Track a Custom Event
  14. Track Ad Revenue Events
  15. Flush Events
  16. API Reference
  17. Available Methods
  18. Types
  19. Enums
  20. Complete Import Example
  21. Error Handling
  22. Requirements
  23. ProGuard (Android)
  24. Troubleshooting
  25. Common Issues
  26. Contributing
  27. License
  28. Changelog

@alvie-tech/react-native-tiktok-business-sdk

npm version Build Status npm downloads License

Fork of react-native-tiktok-business-sdk by Matias Tebele, published under the @alvie-tech scope with an added Expo config plugin.

A React Native bridge for the TikTok Business SDK

This library provides a modern, promise-based interface for the TikTok Business SDK, enabling JavaScript apps to initialize the SDK, identify users, and track various events (standard, content, and custom events) with full TypeScript support and comprehensive error handling.

✨ Features

  • 📱 Cross-platform - iOS and Android support
  • 🎯 Promise-based API - Modern async/await support
  • 🔒 TypeScript - Full type safety and IntelliSense
  • 🧪 Comprehensive testing - 100% test coverage with 100+ tests
  • 📊 Event tracking - Standard, content, custom events, and ad revenue tracking
  • 🛡️ Error handling - Robust error handling with specific error codes
  • 🎨 Developer friendly - Simple API with detailed documentation

Installation

Install the package using npm (or yarn):

npm install @alvie-tech/react-native-tiktok-business-sdk

yarn add @alvie-tech/react-native-tiktok-business-sdk

Expo / Continuous Native Generation

If your app uses Expo (managed or with Continuous Native Generation), add the bundled config plugin to app.json / app.config.ts to automate the required native edits at prebuild time:

{
  "expo": {
    "plugins": [
      [
        "@alvie-tech/react-native-tiktok-business-sdk",
        {
          "ios": {
            "tiktokAppId": "YOUR_IOS_TIKTOK_APP_ID",
            "skAdNetworkIds": ["abc1234567.skadnetwork"],
            "userTrackingPermission": "This identifier will be used to deliver personalized ads to you."
          },
          "android": {
            "tiktokAppId": "YOUR_ANDROID_TIKTOK_APP_ID"
          }
        }
      ]
    ]
  }
}

The plugin automatically:

  • Appends 22mmun2rn5.skadnetwork (TikTok's SKAdNetwork identifier) to SKAdNetworkItems in Info.plist
  • Appends tiktok, snssdk1233 and snssdk1180 to LSApplicationQueriesSchemes in Info.plist
  • Writes the TikTokAppID key in Info.plist when ios.tiktokAppId is provided
  • Writes NSUserTrackingUsageDescription when ios.userTrackingPermission is provided — omit it if expo-tracking-transparency already manages it for your app
  • Adds the com.tiktok.sdk.AppId <meta-data> entry to AndroidManifest.xml when android.tiktokAppId is provided

All mods are idempotent: running expo prebuild multiple times will not duplicate entries. After updating the configuration, regenerate the native projects with npx expo prebuild --clean.

iOS Setup

  1. Run pod install in your ios directory:
cd ios && pod install
  1. The SDK will automatically link the TikTok Business SDK dependency.

  2. iOS 14+ — App Tracking Transparency: The TikTok SDK requires user tracking permission to report install and other automatic events. Add the following key to your ios/<YourApp>/Info.plist:

<key>NSUserTrackingUsageDescription</key>
<string>This identifier will be used to deliver personalized ads to you.</string>

Customize the string to match your app's use case. Without this entry, the install event and other automatic tracking may not function correctly on iOS 14+.

Android Setup

  1. The SDK dependency is automatically included via Gradle.

  2. Add ProGuard rules to prevent code obfuscation (see ProGuard section below).

Usage

Below are examples of how to use the various methods exposed by the library.

Importing the Library

The package exposes a main object, TikTokBusiness, that aggregates all the methods and enums. For example:

import { TikTokBusiness } from '@alvie-tech/react-native-tiktok-business-sdk';

Initialize the SDK

Before using any event tracking methods, you must initialize the SDK. You can call initializeSdk with your appId, tiktokAppId, accessToken, and optionally set debug mode.

Single TikTok App ID

async function initializeTikTokSDK() {
  try {
    await TikTokBusiness.initializeSdk(
      'YOUR_APP_ID',         // Your app ID (e.g., Android package name or iOS bundle ID)
      'YOUR_TIKTOK_APP_ID',  // Your TikTok App ID from TikTok Events Manager
      'YOUR_ACCESS_TOKEN',   // Your access token from TikTok Events Manager (REQUIRED)
      true                   // Enable debug mode (optional, defaults to false)
    );
    console.log('TikTok SDK initialized successfully!');
    // SDK is now initialized, and tracking is active.
  } catch (error) {
    console.error('Error initializing TikTok SDK:', error);
    // Handle initialization errors (network issues, invalid credentials, etc.)
  }
}

initializeTikTokSDK();

Multiple TikTok App IDs

Starting from SDK v1.3.1, you can track events with multiple TikTok App IDs by passing an array:

async function initializeTikTokSDKWithMultipleAppIds() {
  try {
    await TikTokBusiness.initializeSdk(
      'YOUR_APP_ID',
      ['TIKTOK_APP_ID_1', 'TIKTOK_APP_ID_2', 'TIKTOK_APP_ID_3'],  // Array of TikTok App IDs
      'YOUR_ACCESS_TOKEN',
      true
    );
    console.log('TikTok SDK initialized with multiple App IDs!');
  } catch (error) {
    console.error('Error initializing TikTok SDK:', error);
  }
}

Alternatively, you can still use comma-separated string format:

await TikTokBusiness.initializeSdk(
  'YOUR_APP_ID',
  '11,22,33',  // Comma-separated App IDs (no spaces)
  'YOUR_ACCESS_TOKEN',
  true
);

Important Validation Rules:

  • App IDs must be numeric strings
  • No spaces allowed in comma-separated format
  • No trailing or leading commas
  • Array format is recommended for better readability and type safety
  • All TikTok App IDs must match your App ID (SDK requirement)

Disabling Automatic Tracking Events

By default, the TikTok SDK automatically reports install, launch, 2D-retention, and in-app purchase events. You can disable any of these at initialization time by passing an optional options object:

import { TikTokBusiness } from '@alvie-tech/react-native-tiktok-business-sdk';
import type { TikTokSdkConfig } from '@alvie-tech/react-native-tiktok-business-sdk';

// Disable all automatic events
await TikTokBusiness.initializeSdk(
  'YOUR_APP_ID',
  'YOUR_TIKTOK_APP_ID',
  'YOUR_ACCESS_TOKEN',
  false,
  { disableAutoTracking: true }
);

// Or disable specific events
const options: TikTokSdkConfig = {
  disableInstallTracking: true,       // Don't report install event
  disableLaunchTracking: true,        // Don't report app launch event
  disableRetentionTracking: true,     // Don't report 2D-retention event
  disablePaymentTracking: true,       // Don't report automatic IAP event
  disableSKAdNetworkSupport: true,    // iOS only: disable automatic SKAdNetwork support
};

await TikTokBusiness.initializeSdk(
  'YOUR_APP_ID',
  'YOUR_TIKTOK_APP_ID',
  'YOUR_ACCESS_TOKEN',
  false,
  options
);

Note: All existing calls without the options argument continue to work unchanged.

Identify a User

Call the identify method to report user information. All parameters are required.

async function identifyUser() {
  try {
    await TikTokBusiness.identify(
      'user_12345',           // External user ID (required)
      'john_doe',             // External user name (required)
      '+1234567890',          // Phone number (required)
      '[email protected]'      // Email address (required)
    );
    console.log('User identified successfully!');
  } catch (error) {
    console.error('Error identifying user:', error);
    // Handle identification errors
  }
}

Logout

Log out the user with the logout method:

async function logoutUser() {
  try {
    await TikTokBusiness.logout();
    console.log('User logged out successfully!');
  } catch (error) {
    console.error('Error logging out:', error);
    // Handle logout errors
  }
}

Track a Standard Event

Use trackEvent to report standard events. You can optionally pass an event ID and additional properties.

import { TikTokBusiness, TikTokEventName } from '@alvie-tech/react-native-tiktok-business-sdk';

async function trackStandardEvent() {
  try {
    // Simple event tracking
    await TikTokBusiness.trackEvent(TikTokEventName.REGISTRATION);
    
    // Event with custom ID and properties
    await TikTokBusiness.trackEvent(
      TikTokEventName.SEARCH,
      'search_001',                    // Optional event ID
      {                               // Optional properties
        query: 'coffee',
      }
    );
    
    console.log('Standard event tracked successfully!');
  } catch (error) {
    console.error('Error tracking standard event:', error);
  }
}

Track a Content Event

For events that require content details (e.g., "ADD_TO_CART", "CHECK_OUT", etc.), use trackContentEvent. The method accepts an event type string and a parameters object.

import { 
  TikTokBusiness, 
  TikTokContentEventName, 
  TikTokContentEventParameter, 
  TikTokContentEventContentsParameter 
} from '@alvie-tech/react-native-tiktok-business-sdk';

async function trackContentEvent() {
  try {
    await TikTokBusiness.trackContentEvent(TikTokContentEventName.PURCHASE, {
      [TikTokContentEventParameter.CURRENCY]: 'USD',
      [TikTokContentEventParameter.VALUE]: '29.99',
      [TikTokContentEventParameter.CONTENT_TYPE]: 'product',
      [TikTokContentEventParameter.DESCRIPTION]: 'Premium coffee purchase',
      [TikTokContentEventParameter.CONTENTS]: [
        {
          [TikTokContentEventContentsParameter.CONTENT_ID]: 'coffee_001',
          [TikTokContentEventContentsParameter.CONTENT_NAME]: 'Premium Coffee',
          [TikTokContentEventContentsParameter.BRAND]: 'Coffee Brand',
          [TikTokContentEventContentsParameter.PRICE]: 29.99,
          [TikTokContentEventContentsParameter.QUANTITY]: 1,
        },
      ],
    });
    
    console.log('Content event tracked successfully!');
  } catch (error) {
    console.error('Error tracking content event:', error);
  }
}

Track a Custom Event

If you need to report an event that isn't standard, use trackCustomEvent and pass the event name and a properties object.

async function trackCustomEvent() {
  try {
    await TikTokBusiness.trackCustomEvent('user_achievement', {
      description: 'Level Completed!',
    });
    
    console.log('Custom event tracked successfully!');
  } catch (error) {
    console.error('Error tracking custom event:', error);
  }
}

Track Ad Revenue Events

Track impression-level ad revenue data using the trackAdRevenueEvent method. This is useful for monetization tracking with ad networks like AdMob, Unity, IronSource, etc.

import { TikTokBusiness, trackAdRevenueEvent } from '@alvie-tech/react-native-tiktok-business-sdk';
import type { AdRevenueData } from '@alvie-tech/react-native-tiktok-business-sdk';

async function trackAdRevenue() {
  try {
    const adRevenueData: AdRevenueData = {
      revenue: 0.05,              // Revenue amount
      currency: 'USD',            // Currency code
      adNetwork: 'AdMob',         // Ad network name
      adUnit: 'banner_main',      // Ad unit identifier
      adFormat: 'banner',         // Ad format (banner, interstitial, rewarded)
      placement: 'home_screen',   // Placement in your app
      country: 'US',              // Country code
      precision: 'exact',         // Precision level
    };

    // Track ad revenue with optional event ID
    await trackAdRevenueEvent(adRevenueData, 'ad-revenue-001');
    
    console.log('Ad revenue tracked successfully!');
  } catch (error) {
    console.error('Error tracking ad revenue:', error);
  }
}

// Alternative: Use standard event tracking
async function trackImpressionEvent() {
  try {
    await TikTokBusiness.trackEvent(TikTokEventName.IMPRESSION_LEVEL_AD_REVENUE);
    console.log('Impression event tracked successfully!');
  } catch (error) {
    console.error('Error tracking impression event:', error);
  }
}

Flush Events

Manually flush pending events to TikTok's servers. This is useful when you want to ensure events are sent immediately, such as before the app terminates.

async function flushEvents() {
  try {
    await TikTokBusiness.flush();
    console.log('Events flushed successfully!');
  } catch (error) {
    console.error('Error flushing events:', error);
  }
}

Note: Events are normally sent automatically at regular intervals. Only use flush when you need immediate synchronization.

API Reference

Available Methods

All methods return promises and support async/await pattern:

// Initialize SDK (required before any other calls)
initializeSdk(appId: string, ttAppId: string | string[], accessToken: string, debug?: boolean): Promise<string>

// User management
identify(externalId: string, externalUserName: string, phoneNumber: string, email: string): Promise<string>
logout(): Promise<string>

// Event tracking
trackEvent(eventName: TikTokEventName, eventId?: string, properties?: object): Promise<string>
trackContentEvent(eventName: TikTokContentEventName, properties?: object): Promise<string>
trackCustomEvent(eventName: string, properties?: object): Promise<string>
trackAdRevenueEvent(adRevenueData: AdRevenueData, eventId?: string): Promise<string>

// Other
flush(): Promise<string>

Types

AdRevenueData Interface

interface AdRevenueData {
  revenue?: number;        // Revenue amount in specified currency
  currency?: string;       // Currency code (e.g., 'USD', 'EUR')
  adNetwork?: string;      // Ad network name (e.g., 'AdMob', 'Unity', 'IronSource')
  adUnit?: string;         // Ad unit identifier
  adFormat?: string;       // Ad format (e.g., 'banner', 'interstitial', 'rewarded')
  placement?: string;      // Placement identifier in your app
  country?: string;        // Country code where ad was shown
  precision?: string;      // Precision level of revenue data
  [key: string]: string | number | boolean | undefined; // Additional custom properties
}

Enums

The library exports the following enums to ensure consistency when reporting events:

  • TikTokEventName – Standard event names (LOGIN, REGISTRATION, PURCHASE, etc.)
  • TikTokContentEventName – Content event names (ADD_TO_CART, VIEW_CONTENT, etc.)
  • TikTokContentEventParameter – Parameters for content events (CURRENCY, VALUE, etc.)
  • TikTokContentEventContentsParameter – Parameters for content items (CONTENT_ID, PRICE, etc.)

Complete Import Example

import {
  TikTokBusiness,
  trackAdRevenueEvent,
  TikTokEventName,
  TikTokContentEventName,
  TikTokContentEventParameter,
  TikTokContentEventContentsParameter,
} from '@alvie-tech/react-native-tiktok-business-sdk';
import type { AdRevenueData } from '@alvie-tech/react-native-tiktok-business-sdk';

Error Handling

The SDK provides comprehensive error handling with specific error codes:

try {
  await TikTokBusiness.initializeSdk(appId, ttAppId, accessToken, debug);
} catch (error) {
  switch (error.code) {
    case 'INIT_ERROR':
      console.error('Failed to initialize SDK:', error.message);
      break;
    case 'IDENTIFY_ERROR':
      console.error('Failed to identify user:', error.message);
      break;
    case 'TRACK_EVENT_ERROR':
      console.error('Failed to track event:', error.message);
      break;
    default:
      console.error('Unknown error:', error.message);
  }
}

Requirements

  • React Native 0.60+
  • iOS 11.0+
  • Android API level 16+

ProGuard (Android)

If you're using ProGuard for code obfuscation, add these rules to your proguard-rules.pro:

-keep class com.tiktok.** { *; }
-keep class com.android.billingclient.api.** { *; }
-keep interface com.android.billingclient.api.* { *; }
-keep class androidx.lifecycle.** { *; }
-keep class com.android.installreferrer.** { *; }

Troubleshooting

Common Issues

  1. "TikTokBusinessModule.initializeSdk got X arguments, expected Y"

    • Ensure you're passing all required parameters including the new accessToken
    • Check that you're using the latest version of the library
  2. "The package doesn't seem to be linked"

    • Run npx react-native clean and rebuild your project
    • For iOS: cd ios && pod install && cd ..
    • For Android: cd android && ./gradlew clean && cd ..
  3. Events not appearing in TikTok Events Manager

    • Verify your accessToken is correct and has proper permissions
    • Check that your app ID and TikTok App ID are correctly configured
    • Enable debug mode to see detailed logging

Contributing

See the contributing guide to learn how to contribute to the repository and our development workflow.

License

MIT


Changelog

See CHANGELOG.md for detailed release notes and version history.

版本与发布记录

@alvie-tech/react-native-tiktok-business-sdk 共发布 3 个版本,首次发布于 2026/06/02;过去 12 个月发布了 3 个版本。

版本发布日期距今
1.7.2latest2026/11/05今天
1.7.12026/09/022 个月前
1.6.22026/06/025 个月前

关于 @alvie-tech/react-native-tiktok-business-sdk 的常见问题

@alvie-tech/react-native-tiktok-business-sdk 是什么?

A React Native bridge for the TikTok Business SDK

如何安装 @alvie-tech/react-native-tiktok-business-sdk?

在项目目录运行 npm install @alvie-tech/react-native-tiktok-business-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(*)、react-native(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@alvie-tech/react-native-tiktok-business-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alvie-tech/react-native-tiktok-business-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@alvie-tech/react-native-tiktok-business-sdk 可以商用吗?

@alvie-tech/react-native-tiktok-business-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@alvie-tech/react-native-tiktok-business-sdk 的下载量有多少?

根据 npm 官方下载统计,@alvie-tech/react-native-tiktok-business-sdk 在 2026/10/06 – 2026/11/04 这 30 天内被下载 9,404 次,日均约 313 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alvie-tech/react-native-tiktok-business-sdk 还在维护吗?

最新版本 1.7.2 发布于 2026/11/05(今天);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/06/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。