11 KiB
11 KiB
TikTokApi - TikTok Marketing API Provider Service
Standalone microservice for TikTok advertising integration. Mirrors the GoogleApi/MetaApi architecture — the Gateway routes provider="tiktok" requests here via internal HTTP.
Architecture
Gateway ──(POST /internal/execute)──► TikTokApi ──(REST)──► TikTok Marketing API
X-Internal-Key auth │ business-api.tiktok.com
├── Emulated mode (default)
└── Real API mode (TikTok__EnableRealApi=true)
Platform Comparison
| Aspect | GoogleApi | MetaApi | TikTokApi |
|---|---|---|---|
| Parent entity | MCC (Manager) | Business Manager | Business Center (BC) |
| Child accounts | Customer ID | Ad Account (act_XXX) |
Advertiser ID (numeric) |
| Auth | OAuth refresh tokens | System User token | OAuth → long-lived token |
| Token expiry | Requires refresh | Never (if user active) | Never (unless revoked) |
| SDK | Google.Ads NuGet | HttpClient (Graph API) | HttpClient (REST) |
| Auth header | OAuth Bearer | query param | Access-Token header |
| Base URL | via SDK | graph.facebook.com | business-api.tiktok.com |
| API versioning | SDK version | URL path (/v21.0/) |
URL path (/v1.3/) |
| Hierarchy | Campaign→Ad Group→Ad | Campaign→Ad Set→Ad | Campaign→Ad Group→Ad |
| Status values | ENABLED/PAUSED | ACTIVE/PAUSED | ENABLE/DISABLE |
| Response format | gRPC via SDK | JSON {data} |
JSON {code,message,data} |
| Fund management | N/A | N/A | BC Transfer API |
Operations
| Operation | Description | Endpoint | Real API |
|---|---|---|---|
| Ping / TestPing | Health check | N/A | N/A |
| CreateCampaign | Create campaign | POST /campaign/create/ | ✅ |
| GetCampaign | Retrieve campaign | GET /campaign/get/ | ✅ |
| UpdateCampaign | Update name/budget | POST /campaign/update/ | ✅ |
| UpdateCampaignStatus | Enable/disable/delete | POST /campaign/status/update/ | ✅ |
| ListCampaigns | List with filters | GET /campaign/get/ | ✅ |
| GetReport | Performance metrics | POST /report/integrated/get/ | ✅ |
| CreateAdvertiser | Create ad account under BC | POST /bc/advertiser/create | ✅ |
| ListAdvertisers | List BC ad accounts | GET /bc/advertiser/get | ✅ |
| TransferFunds | Recharge/deduct ad account | POST /bc/transfer/ | ✅ |
Environment Variables
| Variable | Required | Description |
|---|---|---|
TIKTOK_INTERNAL_KEY |
Yes | Gateway→TikTokApi shared auth key |
TikTok__EnableRealApi |
No | false (default) = emulated responses |
TikTok__AppId |
For real API | App ID from TikTok Developer Portal |
TikTok__AppSecret |
For real API | App Secret from Developer Portal |
TikTok__AccessToken |
For real API | Long-lived token from OAuth flow |
TikTok__BusinessCenterId |
For real API | USIM's Business Center numeric ID |
TikTok__ApiVersion |
No | API version (default: v1.3) |
TikTok__ApiBaseUrl |
No | https://business-api.tiktok.com (prod) or https://sandbox-ads.tiktok.com (sandbox) |
TikTok Business Center & API Setup
Phase 1: Business Center Setup
-
Create TikTok For Business Account
- Go to https://www.tiktok.com/business/
- Sign up with a business email (use USIM company email)
- Complete business verification
-
Create Business Center
- Go to https://business.tiktok.com/
- Click "Create Business Center"
- Choose Agency type (not Advertiser — this is critical for managing client accounts)
- Enter USIM business details, complete verification
- Note the Business Center ID (numeric, visible in the URL)
-
Verify Business
- Business Center → Settings → Verification
- Upload required business documentation
- Verification typically takes 1-3 business days
- Required before creating ad accounts programmatically
Phase 2: Developer App Registration
-
Register as Developer
- Go to https://business-api.tiktok.com/portal
- Click "Become a Developer" (top right)
- Fill in developer application:
- Company name: USIM
- Website: your company URL
- Use case description: "Agency platform for managing client TikTok advertising campaigns programmatically via API. Creating and managing advertiser accounts, campaigns, ad groups, ads, and pulling performance reports."
- Submit and wait for approval (usually 1-2 business days)
-
Create App
- My Apps → Create New
- App Name: "USIM AdPlatform" (or similar)
- Description: "Multi-channel advertising management platform for SMB clients"
- Advertiser Redirect URL:
https://adptestapi.usimdev.com/auth/tiktok/callback(for OAuth flow) - Scope of Permissions — select all that apply:
- ✅ Ad Account Management (
ad_account_management) - ✅ Campaign Management (
campaign_management) - ✅ Ad Management (
ad_management) - ✅ Creative Management (
creative_management) - ✅ Reporting (
reporting) - ✅ Audience Management (
audience_management) - ✅ Business Center Management (
bc_management)
- ✅ Ad Account Management (
- Note your App ID and App Secret
-
App Review
- After creating the app, it goes through TikTok review
- Basic access is granted immediately (sandbox)
- For production access to campaign management, you may need additional review
Phase 3: Access Token Generation
-
Authorize the App
- Navigate to the Authorization URL (found in app details):
https://business-api.tiktok.com/portal/auth?app_id={APP_ID}&state=usim&redirect_uri={REDIRECT_URI} - Log in with the TikTok Business account that owns the Business Center
- Grant all requested permissions
- DO NOT close the redirect page — copy the
auth_codefrom the URL
- Navigate to the Authorization URL (found in app details):
-
Exchange Auth Code for Access Token
curl -X POST "https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/" \ -H "Content-Type: application/json" \ -d '{ "app_id": "YOUR_APP_ID", "secret": "YOUR_APP_SECRET", "auth_code": "AUTH_CODE_FROM_REDIRECT" }'Response:
{ "code": 0, "message": "OK", "data": { "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "advertiser_ids": ["7123456789012345678", "7123456789012345679"] } }Important: The access token does NOT expire unless the advertiser revokes authorization. Store it securely in Azure Key Vault.
-
Verify Token Works
curl "https://business-api.tiktok.com/open_api/v1.3/oauth2/advertiser/get/?app_id={APP_ID}&secret={APP_SECRET}" \ -H "Access-Token: YOUR_ACCESS_TOKEN"This should return the list of advertiser IDs you have access to.
Phase 4: Sandbox Testing (Recommended)
- Use Sandbox Environment First
- Sandbox URL:
https://sandbox-ads.tiktok.com - Set
TikTok__ApiBaseUrl=https://sandbox-ads.tiktok.comin env vars - Sandbox uses the same endpoints but with test data
- Create test campaigns, verify response formats
- Switch to production URL when ready
- Sandbox URL:
Phase 5: Deploy TikTokApi Container
-
Configure Azure Container Apps
# Create container az containerapp create \ --name usim-adp-tiktokapi \ --resource-group USIM-AdPlatform \ --environment usim-adp-env \ --image <registry>/usim-adp-tiktokapi:latest \ --target-port 5400 \ --ingress internal \ --env-vars \ TIKTOK_INTERNAL_KEY=secretref:tiktok-internal-key \ TikTok__EnableRealApi=false # Add secrets (when ready for real API) az containerapp secret set \ --name usim-adp-tiktokapi \ --resource-group USIM-AdPlatform \ --secrets \ tiktok-access-token=<token> \ tiktok-app-secret=<secret> -
Configure Gateway
- Add environment variables to Gateway container:
TIKTOK_PROVIDER_URL=https://usim-adp-tiktokapi.internal.<env>.azurecontainerapps.io TIKTOK_INTERNAL_KEY=<matching-key> - Gateway's
ExecutionService.GetProviderUrl()routesprovider="tiktok"toTIKTOK_PROVIDER_URL
- Add environment variables to Gateway container:
Phase 6: Database Setup
-
Add TikTok channel references (if not already present)
- Ensure
tbChannelConfighastiktokchannel entry - Create
vwTikTokAccountview (mirrors vwGoogleAccount pattern) - Create
vwTikTokCampaignview - Create
spTikTokAccountstored procedure for account linking
- Ensure
-
Gateway MultiChannel config
- Verify
appsettings.jsonMultiChannel section includes tiktok with StatusMappings:{ "tiktok": { "StatusMappings": { "ENABLE": "active", "DISABLE": "paused", "DELETE": "cancelled" } } }
- Verify
TikTok API Quick Reference
Response Envelope
All TikTok Marketing API responses follow this format:
{
"code": 0,
"message": "OK",
"data": { ... },
"request_id": "202502171234567890..."
}
code: 0= success- Non-zero = error (e.g., 40001 = auth error, 40002 = permission denied)
Key Endpoint Patterns
GET /open_api/v1.3/campaign/get/?advertiser_id=XXX
POST /open_api/v1.3/campaign/create/ (JSON body with advertiser_id)
POST /open_api/v1.3/campaign/update/ (JSON body)
POST /open_api/v1.3/campaign/status/update/ (separate from update)
POST /open_api/v1.3/report/integrated/get/ (reporting)
POST /open_api/v1.3/bc/advertiser/create (BC operations)
POST /open_api/v1.3/bc/transfer/ (fund management)
Common Error Codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 40001 | Authentication error (invalid/expired token) |
| 40002 | No permission for this operation |
| 40100 | Invalid parameter |
| 40700 | Rate limit exceeded |
| 50000 | Internal server error |
Project Structure
TikTokApi/
├── Configuration/
│ └── TikTokConfig.cs # Config + TikTokApiContext
├── Controllers/
│ └── InternalController.cs # /internal/execute + /internal/health
├── Models/
│ ├── OperationPayloads.cs # TikTok-specific payloads + enums
│ └── ProviderModels.cs # ProviderRequest/Response (Gateway contract)
├── Security/
│ └── InternalAuthFilter.cs # X-Internal-Key validation
├── Services/
│ ├── TikTokApiClient.cs # HTTP wrapper for business-api.tiktok.com
│ └── TikTokMarketingService.cs # Operation dispatcher (emulated/real)
├── Program.cs
├── appsettings.json
└── TikTokApi.csproj
Local Development
dotnet run --project TikTokApi
# → http://localhost:5400
# → Swagger: http://localhost:5400/swagger
Port Assignments
| Service | Port |
|---|---|
| Gateway | 5000 |
| GoogleApi | 5200 |
| MetaApi | 5300 |
| TikTokApi | 5400 |
| Creative | 5100 |