Skip to main content

🎵 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 reference
  • created_by (ObjectId) - User who performed the integration
  • token (Object) - OAuth token response object
    • data.access_token (String) - TikTok access token
    • data.expires_in (Number) - Token expiration in seconds
    • data.token_type (String) - "Bearer"
  • deleted (Date, TTL index 500s) - Soft delete timestamp
  • createdAt (Date) - Document creation timestamp
  • updatedAt (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 reference
  • advertiser_id (String) - TikTok advertiser account ID
  • advertiser_name (String) - TikTok advertiser account name
  • createdAt (Date) - Configuration creation timestamp
  • updatedAt (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 storage
  • shared/models/analytics-tiktokanalytics-userconfig.js - Advertiser config
  • shared/models/account.js - DashClicks accounts
  • shared/models/user.js - DashClicks users
  • shared/models/user-config.js - User notification preferences

🔐 Authentication & Configuration

Authentication Method: OAuth 2.0 Authorization Code Flow

Required Environment Variables:

VariableDescriptionRequired
TIK_TOK_CLIENT_IDTikTok app ID
TIKTOK_CLIENT_SECRETTikTok app secret
TIK_TOK_REDIRECT_URLOAuth callback URL
TIKTOK_BASE_URLTikTok Marketing API base URL
TIKTOK_VERSIONAPI version (e.g., v1.3)
APP_SECRETJWT state token signing secret

OAuth Flow:

  1. User initiates login → redirects to TikTok authorization
  2. TikTok redirects back with auth_code
  3. Exchange auth code for access token
  4. Store token in MongoDB with account association
  5. 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

MethodEndpointDescription
GET/auth/loginInitiate OAuth 2.0 flow
GET/auth/callbackHandle OAuth callback
POST/useranalyticsconfigSave advertiser account config
DELETE/authDisconnect integration
GET/accounts/advertisersList advertiser accounts
GET/campaignsList campaigns with pagination
GET/adgroupsList ad groups with pagination
GET/adsList ads with pagination
GET/reportsGenerate integrated analytics report

🔄 Integration Data Levels

TikTok Marketing API supports multiple reporting levels:

  • AUCTION_CAMPAIGN - Campaign-level metrics
  • AUCTION_ADGROUP - Ad group-level metrics
  • AUCTION_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 shown
  • clicks - Number of ad clicks
  • spend - Total ad spend
  • cpc - Cost per click
  • ctr - Click-through rate
  • conversion - Total conversions

Popular Dimensions:

  • campaign_id - Campaign identifier
  • adgroup_id - Ad group identifier
  • ad_id - Individual ad identifier
  • stat_time_day - Daily breakdown

See Analytics documentation for complete list of available metrics and dimensions.

🚨 Error Handling

Common Error Scenarios:

ErrorCauseSolution
KEYS_NOT_FOUNDNo token exists for accountRe-authenticate via OAuth flow
TOKEN_INVALIDATEDToken revoked or expiredRe-authenticate and get new token
Invalid Account IdAccount ID not provided/invalidCheck account access permissions
Code is missingOAuth callback without auth_codeRetry OAuth flow from beginning

Token Invalidation Detection:

  • API returns 401/403 status codes
  • API returns invalid_grant error
  • 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)

⚠️ Important Notes

  • 🔐 Token Storage: Access tokens stored with strict: false schema for flexibility
  • ♻️ Automatic Cleanup: Deleted tokens auto-expire after 500 seconds (TTL index)
  • 🔒 Single Connection: One token per account (upsert behavior)
  • 📊 Pagination: Uses page and page_size parameters
  • 🎯 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) and page_size parameters
  • Returns page_info object with total_number and 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
💬

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM