npm package: @layers/expo-tiktok-business
Description: Expo module for TikTok Business SDK (AppMachina monorepo)
Author: AppMachina Team
Latest version: 3.0.2

# @layers/expo-tiktok-business

TikTok Business SDK for Expo/React Native. Ship reliable event tracking with a tiny, typed API. iOS + Android supported. Web is a debug-friendly stub.

## Compatibility

- Expo: 52 -- 54
- React Native: 0.76 -- 0.81
- React: 18 -- 19

## Install

**Managed Expo:**

```bash
npx expo install @layers/expo-tiktok-business
```

**Bare React Native:**

```bash
pnpm add @layers/expo-tiktok-business
npx expo prebuild   # first install
npx pod-install     # iOS
```

## Config Plugin

Add the plugin to your `app.json` / `app.config.ts` to automate native setup (SKAdNetwork IDs, `LSApplicationQueriesSchemes`, optional TikTok app ID in Info.plist / AndroidManifest):

```json
{
  "expo": {
    "plugins": [
      [
        "@layers/expo-tiktok-business/app.plugin.cjs",
        {
          "ios": {
            "tiktokAppId": "YOUR_IOS_TIKTOK_APP_ID",
            "urlSchemes": ["snssdk1233"]
          },
          "android": {
            "tiktokAppId": "YOUR_ANDROID_TIKTOK_APP_ID"
          }
        }
      ]
    ]
  }
}
```

The plugin automatically:

- Adds TikTok's SKAdNetwork ID (`22mmun2rn5.skadnetwork`) to Info.plist
- Adds `LSApplicationQueriesSchemes` for TikTok deep link detection (`tiktok`, `snssdk1233`, `snssdk1180`)
- Sets the `TikTokAppID` key in Info.plist (if `ios.tiktokAppId` is provided)
- Adds `com.tiktok.sdk.AppId` meta-data to AndroidManifest.xml (if `android.tiktokAppId` is provided)
- Supports custom `skAdNetworkIds` and `urlSchemes`

## Quickstart

```ts
import TiktokSDK, { TiktokEventName } from '@layers/expo-tiktok-business';

await TiktokSDK.initialize(
  // App bundle ID / package name (string or per-platform)
  { ios: 'com.myapp.ios', android: 'com.myapp.android' },
  // TikTok App ID from Business Center (string or per-platform)
  { ios: 'TT_IOS_APP_ID', android: 'TT_ANDROID_APP_ID' },
  // Options
  {
    accessToken: {
      ios: 'YOUR_IOS_ACCESS_TOKEN',
      android: 'YOUR_ANDROID_ACCESS_TOKEN'
    },
    debugMode: __DEV__
  }
);

// Track a standard event
await TiktokSDK.trackEvent(TiktokEventName.VIEW_CONTENT, {
  content_id: 'product-123',
  content_type: 'product'
});

// Convenience helpers
await TiktokSDK.trackSearch('wireless headphones');
await TiktokSDK.trackViewContent('product-123', 'product');
await TiktokSDK.trackCompletePurchase(99.99, 'USD', [
  { content_id: 'product-123', quantity: 1, price: 99.99 }
]);
```

> **Heads up:** TikTok issues unique identifiers and access tokens for each platform. Provide `{ ios, android }` entries for values that differ per platform, or pass a plain string when they are identical.

## Expo Router Integration

Automatically track screen views with the `useTiktokRouteTracking` hook. Place it in your root layout:

```tsx
// app/_layout.tsx
import TiktokSDK, {
  initExpoRouterTracking,
  useTiktokRouteTracking
} from '@layers/expo-tiktok-business';
import { Slot } from 'expo-router';
import { useGlobalSearchParams, usePathname } from 'expo-router';
import { useEffect } from 'react';

// Call once after SDK initialization
initExpoRouterTracking(TiktokSDK);

export default function RootLayout() {
  useTiktokRouteTracking(usePathname, useGlobalSearchParams);
  return <Slot />;
}
```

**How it works:**

1. Call `initExpoRouterTracking(TiktokSDK)` once (at module scope or in an effect) to wire the SDK instance.
2. `useTiktokRouteTracking(usePathname, useGlobalSearchParams?)` watches the current pathname and fires `trackRouteChange` on each navigation.
3. The second argument (`useGlobalSearchParams`) is optional -- if omitted, route params are sent as `{}`.

## Event Names

Standard TikTok events are exported as the `TiktokEventName` enum:

| Enum Value          | Event Name       |
| ------------------- | ---------------- |
| `LAUNCH`            | Launch           |
| `APP_INSTALL`       | AppInstall       |
| `SEARCH`            | Search           |
| `VIEW_CONTENT`      | ViewContent      |
| `CLICK`             | Click            |
| `ADD_TO_WISHLIST`   | AddToWishlist    |
| `ADD_TO_CART`       | AddToCart        |
| `COMPLETE_TUTORIAL` | CompleteTutorial |
| `INITIATE_CHECKOUT` | InitiateCheckout |
| `ADD_PAYMENT_INFO`  | AddPaymentInfo   |
| `COMPLETE_PAYMENT`  | CompletePayment  |
| `PLACE_AN_ORDER`    | PlaceAnOrder     |
| `SUBSCRIBE`         | Subscribe        |
| `CONTACT`           | Contact          |
| `CUSTOM`            | Custom           |

```ts
import { TiktokEventName } from '@layers/expo-tiktok-business';

await TiktokSDK.trackEvent(TiktokEventName.ADD_TO_CART, {
  content_id: 'sku-456',
  value: 29.99,
  currency: 'USD'
});
```

## API Reference

### `TiktokSDK.initialize(appId, tiktokAppId, options)`

Initialize the SDK. Must be called before any tracking methods.

| Parameter                       | Type                                           | Description                                                                                           |
| ------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `appId`                         | `string \| { ios?: string; android?: string }` | App bundle ID / package name                                                                          |
| `tiktokAppId`                   | `string \| { ios?: string; android?: string }` | TikTok App ID from Business Center                                                                    |
| `options.accessToken`           | `string \| { ios?: string; android?: string }` | TikTok access token (required)                                                                        |
| `options.debugMode`             | `boolean`                                      | Enable debug logging (default: `false`). Must be set at initialization; cannot be changed at runtime. |
| `options.autoTrackAppLifecycle` | `boolean`                                      | Auto-track launch events (default: `true`)                                                            |
| `options.autoTrackRouteChanges` | `boolean`                                      | Enable route change tracking (default: `true`)                                                        |

### `TiktokSDK.trackEvent(eventName, params?)`

Track a standard or custom event. Returns `false` if the SDK is not initialized.

### `TiktokSDK.trackRouteChange(routeName, params?)`

Manually track a screen view. Prefer `useTiktokRouteTracking` for Expo Router apps.

### Convenience Methods

- `trackSearch(query, params?)` -- Sends a `Search` event
- `trackViewContent(contentId, contentType, params?)` -- Sends a `ViewContent` event
- `trackCompletePurchase(value, currency, contents, params?)` -- Sends a `CompletePayment` event

## Platform Notes

### iOS

- Run `npx pod-install` after installing.
- CocoaPods pulls `TikTokBusinessSDK`.
- The config plugin adds SKAdNetwork IDs and `LSApplicationQueriesSchemes` automatically.

### Android

- The library includes the JitPack repo and ProGuard rules; no manual Gradle edits required.
- `AD_ID` permission is declared for attribution. Review Play policy before publishing.

### Web

- Stub implementation for local debugging. No network calls are made.
- All methods resolve successfully, events are logged to console in debug mode.

## Troubleshooting

- **"Native module not found"** -- Run `npx expo prebuild` then `npx pod-install` (iOS).
- **Build flakiness after upgrades** -- Clean pods/DerivedData or `npx expo prebuild --clean`.
- **Events not showing in dev** -- Ensure `accessToken` is set and `debugMode` is on.

## License

MIT

## Credits & Contributions

This module builds on prior community work by [Lior Levy](https://github.com/Lioruby) from the original
[expo-tiktok-business-sdk](https://github.com/Lioruby/expo-tiktok-business-sdk) project.

We've extended and packaged it for Expo with:

- Platform-aware initialization and typed APIs
- Automatic lifecycle + Expo Router helpers
- Config plugin for automated native setup
- Comprehensive test suite