🎵 TikTok Ads Integration
🎯 Overview
TikTok for Business Marketing API integration providing programmatic access to advertising campaigns, ad groups, ads, and comprehensive performance analytics. Supports OAuth 2.0 authentication with automatic token management and reporting capabilities for campaign optimization.
Provider: TikTok for Business (https://ads.tiktok.com)
API Version: v1.3 (Marketing API)
Integration Type: OAuth 2.0 REST API
📖 Documentation Structure
This integration is organized into the following sections:
- Authentication - OAuth 2.0 flow, token management, and advertiser account setup
- Accounts - Advertiser account listing and management
- Campaigns - Campaign, ad group, and ad operations
- Analytics - Integrated reporting with custom dimensions and metrics
✨ Features
- ✅ OAuth 2.0 Authentication: Secure authorization with automatic token storage
- ✅ Advertiser Accounts: List and manage TikTok Business accounts
- ✅ Campaign Management: Access campaigns, ad groups, and individual ads
- ✅ Integrated Reporting: Custom analytics reports with multiple data levels
- ✅ Status Filtering: Filter by campaign/adgroup/ad status
- ✅ Pagination Support: Page-based pagination for large result sets
- ✅ Token Invalidation: Automatic detection and handling of revoked tokens
- ✅ Notifications: FCM, email, and in-app notifications for connection events
- ✅ Sub-account Support: Works with DashClicks parent/child accounts
🏗️ Architecture
sequenceDiagram
participant Client as DashClicks App
participant API as TikTok Controller
participant Provider as TikTok Provider
participant DB as MongoDB
participant TikTok as TikTok Marketing API
Client->>API: Request (JWT Auth)
API->>DB: Fetch access token
DB-->>API: Return token
API->>Provider: Call provider function
Provider->>TikTok: HTTP Request (Access-Token header)
TikTok-->>Provider: JSON Response
Provider-->>API: Formatted data
API-->>Client: Response with pagination
🗄️ MongoDB Collections
📚 Detailed Schema: See Database Collections Documentation
tiktok.tokens
Purpose: Store OAuth 2.0 access tokens for TikTok Marketing API access
Model: shared/models/tik-tok-token.js
Key Fields:
account_id(ObjectId, required, indexed) - DashClicks account referencecreated_by(ObjectId) - User who performed the integrationtoken(Object) - OAuth token response objectdata.access_token(String) - TikTok access tokendata.expires_in(Number) - Token expiration in secondsdata.token_type(String) - "Bearer"
deleted(Date, TTL index 500s) - Soft delete timestampcreatedAt(Date) - Document creation timestampupdatedAt(Date) - Last update timestamp
Indexes:
{ account_id: 1 }- Primary account lookup{ deleted: 1 }- TTL index for auto-cleanup (500 seconds)
Schema Type: strict: false - Allows flexible storage of TikTok API response
analytics_tiktokanalytics_userconfigs
Purpose: Store advertiser account configuration per DashClicks user
Model: external/models/analytics-tiktokanalytics-userconfig.js
Key Fields:
account_id(ObjectId, required, indexed) - DashClicks account referenceadvertiser_id(String) - TikTok advertiser account IDadvertiser_name(String) - TikTok advertiser account namecreatedAt(Date) - Configuration creation timestampupdatedAt(Date) - Last update timestamp
Indexes:
{ account_id: 1 }(unique) - Ensure one config per account
📁 Directory Structure
Source Code Location:
external/Integrations/TikTok/
├── Controllers/
│ ├── auth.js # OAuth authentication handlers
│ ├── accounts.js # Advertiser account operations
│ └── analytics.js # Campaign/ad reporting
├── Routes/
│ ├── auth.js # Auth endpoints
│ ├── accounts.js # Account endpoints
│ └── analytics.js # Analytics endpoints
├── Models/
│ └── keys.js # Token storage model wrapper
├── providers/
│ └── tiktok-analytics.js # TikTok Marketing API wrapper
├── validators/
│ └── index.js # Request validation schemas
├── constants/
│ └── constants.js # All available metrics/dimensions
└── index.js # Route registration & error handling
Shared Models Used:
shared/models/tik-tok-token.js- OAuth token storageshared/models/analytics-tiktokanalytics-userconfig.js- Advertiser configshared/models/account.js- DashClicks accountsshared/models/user.js- DashClicks usersshared/models/user-config.js- User notification preferences
🔐 Authentication & Configuration
Authentication Method: OAuth 2.0 Authorization Code Flow
Required Environment Variables:
| Variable | Description | Required |
|---|---|---|
TIK_TOK_CLIENT_ID | TikTok app ID | ✅ |
TIKTOK_CLIENT_SECRET | TikTok app secret | ✅ |
TIK_TOK_REDIRECT_URL | OAuth callback URL | ✅ |
TIKTOK_BASE_URL | TikTok Marketing API base URL | ✅ |
TIKTOK_VERSION | API version (e.g., v1.3) | ✅ |
APP_SECRET | JWT state token signing secret | ✅ |
OAuth Flow:
- User initiates login → redirects to TikTok authorization
- TikTok redirects back with
auth_code - Exchange auth code for access token
- Store token in MongoDB with account association
- Save advertiser account configuration
🚀 Quick Start
1. Configure Environment Variables
TIK_TOK_CLIENT_ID=your_app_id
TIKTOK_CLIENT_SECRET=your_app_secret
TIK_TOK_REDIRECT_URL=https://api.dashclicks.com/v1/integrations/tiktok/auth/callback
TIKTOK_BASE_URL=https://business-api.tiktok.com
TIKTOK_VERSION=v1.3
2. Initiate OAuth Flow
GET /v1/integrations/tiktok/auth/login?forward_url=https://app.dashclicks.com/integrations
Authorization: Bearer {jwt_token}
3. Save Advertiser Configuration
POST /v1/integrations/tiktok/useranalyticsconfig
Authorization: Bearer {jwt_token}
Content-Type: application/json
{
"advertiser_id": "1234567890",
"advertiser_name": "My Business Account"
}
4. List Campaigns
GET /v1/integrations/tiktok/campaigns?limit=10&page=1
Authorization: Bearer {jwt_token}
5. Get Analytics Report
GET /v1/integrations/tiktok/reports?data_level=AUCTION_CAMPAIGN&start_date=2025-09-01&end_date=2025-10-10&metrics=["impressions","clicks","spend"]&dimensions=["campaign_id"]
Authorization: Bearer {jwt_token}
📊 API Endpoints Summary
| Method | Endpoint | Description |
|---|---|---|
| GET | /auth/login | Initiate OAuth 2.0 flow |
| GET | /auth/callback | Handle OAuth callback |
| POST | /useranalyticsconfig | Save advertiser account config |
| DELETE | /auth | Disconnect integration |
| GET | /accounts/advertisers | List advertiser accounts |
| GET | /campaigns | List campaigns with pagination |
| GET | /adgroups | List ad groups with pagination |
| GET | /ads | List ads with pagination |
| GET | /reports | Generate integrated analytics report |
🔄 Integration Data Levels
TikTok Marketing API supports multiple reporting levels:
AUCTION_CAMPAIGN- Campaign-level metricsAUCTION_ADGROUP- Ad group-level metricsAUCTION_AD- Individual ad-level metrics
Each level provides different dimensions and metrics suitable for different analysis needs.
🎯 Common Metrics & Dimensions
Popular Metrics:
impressions- Number of times ads were shownclicks- Number of ad clicksspend- Total ad spendcpc- Cost per clickctr- Click-through rateconversion- Total conversions
Popular Dimensions:
campaign_id- Campaign identifieradgroup_id- Ad group identifierad_id- Individual ad identifierstat_time_day- Daily breakdown
See Analytics documentation for complete list of available metrics and dimensions.
🚨 Error Handling
Common Error Scenarios:
| Error | Cause | Solution |
|---|---|---|
KEYS_NOT_FOUND | No token exists for account | Re-authenticate via OAuth flow |
TOKEN_INVALIDATED | Token revoked or expired | Re-authenticate and get new token |
Invalid Account Id | Account ID not provided/invalid | Check account access permissions |
Code is missing | OAuth callback without auth_code | Retry OAuth flow from beginning |
Token Invalidation Detection:
- API returns 401/403 status codes
- API returns
invalid_granterror - Automatically marks token as invalidated in database
- Notifications sent to user about disconnection
📊 Monitoring & Notifications
Notification Events:
- Integration Connected: When TikTok account is successfully linked
- Integration Disconnected: When token is invalidated or manually removed
- Project Added: When advertiser config is saved
Notification Channels:
- 📱 FCM (Firebase Cloud Messaging): In-app notifications
- 📧 Email: Notification emails to account owner
- 🔔 Bell Notifications: In-app bell icon alerts
Notification Preferences: Controlled by user config (user-config.preferences.projects.notifications)
🔗 Related Documentation
- TikTok Marketing API Docs: https://ads.tiktok.com/marketing_api/docs
- OAuth 2.0 Setup: TikTok Developer Portal
- Integrated Reporting: Report API Reference
- DashClicks Collections: Database Schema Documentation
⚠️ Important Notes
- 🔐 Token Storage: Access tokens stored with
strict: falseschema for flexibility - ♻️ Automatic Cleanup: Deleted tokens auto-expire after 500 seconds (TTL index)
- 🔒 Single Connection: One token per account (upsert behavior)
- 📊 Pagination: Uses
pageandpage_sizeparameters - 🎯 Advertiser Required: Most operations require saved advertiser config
- ⚡ Status Filtering: Campaign/adgroup/ad status filtering requires separate API calls
- 🔄 Token Invalidation: Automatic detection on 401/403/invalid_grant errors
- 📬 Notifications: Honors user preferences for bell/email/browser notifications
🎨 API Limitations
Rate Limiting:
- TikTok enforces rate limits per app and per advertiser
- Specific limits documented in TikTok Marketing API docs
- Consider implementing request throttling for high-volume operations
Pagination:
- Uses
page(1-based) andpage_sizeparameters - Returns
page_infoobject withtotal_numberand pagination metadata - Default page size varies by endpoint
Reporting Constraints:
- Maximum 100 dimensions/metrics per report request
- Date range limitations apply
- Some metrics only available at specific data levels