# TikTok Business API Setup Guide

This guide provides step-by-step instructions for setting up TikTok Business API integration for managing ad comments.

---

## Table of Contents

1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [TikTok Business Center Setup](#tiktok-business-center-setup)
4. [Environment Configuration](#environment-configuration)
5. [OAuth Redirect URI Configuration](#oauth-redirect-uri-configuration)
6. [Permissions & Scopes](#permissions--scopes)
7. [Development vs Production](#development-vs-production)
8. [Troubleshooting](#troubleshooting)

---

## Overview

**API Version:** Business API v1.3
**Base URL:** `https://business-api.tiktok.com/open_api/v1.3/`
**Auth Portal:** `https://business-api.tiktok.com/portal/auth`
**Token Endpoint:** `oauth2/access_token/`

### Features Supported
- Fetch advertisements (which act as "content")
- Read comments on advertisements
- Reply to ad comments

### ⚠️ Critical Limitations

> **Important:** This implementation **only supports Ad Comments (Paid Ads)**. TikTok's API does **NOT** support organic video comment management. You cannot:
> - Fetch comments on regular TikTok videos
> - Reply to organic video comments
> - Manage comments on non-ad content

This is a TikTok API limitation, not an application limitation.

---

## Prerequisites

- A TikTok account with access to [TikTok Business Center](https://business.tiktok.com/)
- Admin or Analyst access to a TikTok Ad Account
- An approved TikTok App in Business Center

---

## TikTok Business Center Setup

### Step 1: Access TikTok Business Center

1. Navigate to [TikTok Business Center](https://business.tiktok.com/)
2. Sign in with your TikTok account
3. If you don't have a Business Center, create one

> ⚠️ **Note:** This is **NOT** the same as the "TikTok for Developers" portal used for the Display API. You must use the Business Center.

### Step 2: Create or Access Your App

1. Go to **User Center** (top right) → **App Management** → **My Apps**
2. If you don't have an app, click **"Create App"**
3. Fill in the required details:
   - **App Name:** Your application name
   - **App Description:** Describe your use case
   - **Category:** Select "Business Tools" or similar
4. Submit for approval

### Step 3: Get App Credentials

Once your app is created/approved:

1. Go to **User Center** → **App Management** → **My Apps**
2. Select your app
3. Find the credentials:
   - **App ID** → This is your `TIKTOK_CLIENT_KEY`
   - **App Secret** → Click "View" to reveal → This is your `TIKTOK_CLIENT_SECRET`

> ⚠️ **Important:** Store these credentials securely. The App Secret is only shown once.

---

## Environment Configuration

### Django Settings (settings.py)

```python
# TikTok Business API Configuration
TIKTOK_CLIENT_KEY = 'your_app_id_here'
TIKTOK_CLIENT_SECRET = 'your_app_secret_here'
TIKTOK_REDIRECT_URI = 'https://yourdomain.com/social/callback/TT/'
```

### Environment Variables (.env)

```env
TIKTOK_CLIENT_KEY=your_app_id_here
TIKTOK_CLIENT_SECRET=your_app_secret_here
TIKTOK_REDIRECT_URI=https://yourdomain.com/social/callback/TT/
```

---

## OAuth Redirect URI Configuration

### Step 1: Configure Redirect URI in TikTok App

1. In your app settings, go to **App Settings** → **Login Kit** / **Redirect URI settings**
2. Add your callback URL:

**Development:**
```
http://127.0.0.1:8000/social/callback/TT/
http://localhost:8000/social/callback/TT/
```

> ⚠️ **Note:** TikTok often rejects `localhost` URLs. Use ngrok for local testing (see below).

**Production:**
```
https://yourdomain.com/social/callback/TT/
```

### Using ngrok for Local Development

TikTok may reject HTTP/localhost redirect URIs. Use ngrok:

```bash
# Install ngrok
npm install -g ngrok

# Create tunnel
ngrok http 8000

# Use the ngrok URL as your redirect URI
# Example: https://abc123.ngrok.io/social/callback/TT/

# Update settings.py
TIKTOK_REDIRECT_URI = 'https://abc123.ngrok.io/social/callback/TT/'
```

---

## Permissions & Scopes

The application requests the following OAuth scopes:

| Scope | Description | Required |
|-------|-------------|----------|
| `user.info.basic` | Basic user information | ✅ Yes |
| `ad.read` | Read advertisement data | ✅ Yes |
| `comment.manage` | Manage ad comments | ✅ Yes |

### Code Reference

```python
# apps/social/utils/tiktok.py
class TikTokConstants:
    BASE_URL = "https://business-api.tiktok.com/open_api/v1.3/"
    
    SCOPES = "user.info.basic,ad.read,comment.manage"
    
    ENDPOINTS = {
        "AUTH": "https://business-api.tiktok.com/portal/auth",
        "TOKEN": "oauth2/access_token/",
        "USER_INFO": "user/info/",
        "AD_LIST": "ad/get/",
        "COMMENT_LIST": "comment/list/",
        "COMMENT_REPLY": "comment/reply/",
    }
```

### Requesting Permissions

1. In TikTok Business Center, go to **App Management** → **Permissions**
2. Request permission for:
   - **Ads Management** (for `ad.read`)
   - **Comments Management** (for `comment.manage`)
3. Submit a use case explaining:
   > "We are building a Social Media Management Tool for managing ad comments. This allows advertisers to respond to user engagement on their TikTok advertisements from a centralized dashboard."

> ⚠️ **Note:** TikTok may reject generic requests. Be specific about your use case.

---

## Ad Account Access Requirements

### User Permissions

When connecting via OAuth, the authenticating user must have proper access to the Ad Account:

| Role | Can Sync Ads | Can Reply to Comments |
|------|--------------|----------------------|
| Admin | ✅ Yes | ✅ Yes |
| Analyst | ✅ Yes | ❌ No (read-only) |
| Operator | ✅ Yes | ✅ Yes |

### Granting Access

1. In TikTok Business Center, go to **Ad Accounts**
2. Select your ad account
3. Go to **User Permissions**
4. Add users with appropriate roles

---

## Development vs Production

### Development Setup

| Setting | Value |
|---------|-------|
| `TIKTOK_REDIRECT_URI` | `https://xxx.ngrok.io/social/callback/TT/` (via ngrok) |
| Protocol | HTTPS recommended (ngrok) |
| App Status | Sandbox/Testing mode |

### Production Setup

| Setting | Value |
|---------|-------|
| `TIKTOK_REDIRECT_URI` | `https://yourdomain.com/social/callback/TT/` |
| Protocol | **HTTPS required** |
| App Status | Approved/Production mode |

---

## Troubleshooting

### Common Error: "Invalid Redirect URI"

**Cause:** The redirect URI doesn't match TikTok's configuration.

**Solution:**
1. Verify exact URL in TikTok Business Center → App Settings → Redirect URI
2. Ensure HTTPS is used (or ngrok URL)
3. Check for trailing slashes
4. Wait a few minutes for changes to propagate

---

### Common Error: "Permission Denied for Ad Account"

**Cause:** User doesn't have access to the ad account.

**Solution:**
1. Verify user has Admin, Operator, or Analyst role
2. Check ad account permissions in Business Center
3. Ensure correct ad account is selected during OAuth flow

---

### Common Error: "Scope Not Authorized"

**Cause:** App hasn't been approved for requested permissions.

**Solution:**
1. Go to App Management → Permissions
2. Request required permissions with detailed use case
3. Wait for TikTok approval (can take several days)

---

### Common Error: "No Ads Found"

**Cause:** No active ads in the ad account, or ads don't have comments.

**Solution:**
1. Verify ads exist and are active in TikTok Ads Manager
2. Ensure ads have received comments
3. Check that ad account is properly linked

---

### Common Error: "API Rate Limit Exceeded"

**Cause:** Too many API requests.

**Solution:**
- TikTok Business API has rate limits (varies by endpoint)
- Implement exponential backoff
- Wait for limit to reset

---

### Common Error: "Cannot Reply to Comment"

**Cause:** User has Analyst role (read-only) or comment is deleted.

**Solution:**
1. Ensure user has Admin or Operator role
2. Verify the comment still exists
3. Check that the ad is still active

---

## API Rate Limits

| Endpoint | Rate Limit |
|----------|------------|
| Ad List | 10 requests/second |
| Comment List | 10 requests/second |
| Comment Reply | 10 requests/second |

The application implements rate limiting to stay within these bounds.

---

## API Endpoints Used

| Endpoint | Purpose |
|----------|---------|
| `oauth2/access_token/` | Exchange auth code for access token |
| `user/info/` | Get authenticated user information |
| `ad/get/` | Fetch advertisements for an advertiser |
| `comment/list/` | List comments on an advertisement |
| `comment/reply/` | Reply to a comment |

---

## Verification

After setup, verify the integration:

1. Navigate to `/social/` in your application
2. Click "Connect TikTok"
3. Authorize with TikTok Business account
4. Select your advertiser account
5. Verify ads are fetched
6. Check if comments on ads are loaded
7. Test replying to an ad comment

### Testing in Django Shell

```python
from apps.social.services.tiktok import TikTokService
from apps.social.models import SocialAccount

account = SocialAccount.objects.filter(platform='TT').first()

# Test getting ads
ads = TikTokService.fetch_ads(account)
print(f"Found {len(ads)} ads")

# Test getting comments
if ads:
    comments = TikTokService.fetch_comments(account, ads[0]['ad_id'])
    print(f"Found {len(comments)} comments")
```

---

## Important Notes

1. **Organic Content Not Supported:** TikTok's Business API only supports ad management. You cannot manage comments on organic (non-ad) videos.

2. **Advertiser ID Required:** You need a valid TikTok Advertiser ID with active ads to use this integration.

3. **App Approval:** TikTok may take several days to approve your app and permission requests.

4. **HTTPS Required:** Production redirect URIs must use HTTPS.

5. **Regional Availability:** TikTok Business API may not be available in all regions.

---

## Support Resources

- [TikTok Business API Documentation](https://ads.tiktok.com/marketing_api/docs)
- [TikTok Business Center](https://business.tiktok.com/)
- [TikTok Marketing API Forum](https://community.tiktok.com/)
- [TikTok Ads Manager](https://ads.tiktok.com/)

---

*Last Updated: February 2026*
*API Version: TikTok Business API v1.3*