TikTok Ads Integrations Overview
TikTok Ads offers robust integration options to connect your marketing stack, eCommerce platform, and analytics tools. These integrations enable seamless tracking, campaign optimization, and data synchronization across your digital ecosystem.
TikTok Pixel
What is TikTok Pixel?
The TikTok Pixel is a JavaScript snippet that tracks user behavior on your website after clicking or viewing TikTok ads. It powers conversion tracking, audience building, and campaign optimization.
Key Capabilities
| Feature | Description |
|---|---|
| Conversion Tracking | Track purchases, signups, and custom events |
| Audience Building | Create retargeting and lookalike audiences |
| Campaign Optimization | Optimize delivery to users likely to convert |
| Attribution | Measure ad impact with configurable windows |
| Advanced Matching | Improve match rates with hashed user data |
Basic Pixel Implementation
<!-- TikTok Pixel Base Code -->
<script>
!function (w, d, t) {
w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
ttq.load('YOUR_PIXEL_ID');
ttq.page();
}(window, document, 'ttq');
</script>
Advanced Matching
Enhance match quality by passing hashed user identifiers:
// Hash user data before sending
function hashData(data) {
// Use SHA256 hashing
return CryptoJS.SHA256(data.toLowerCase().trim()).toString();
}
// Identify user
ttq.identify({
email: hashData('user@example.com'),
phone_number: hashData('+15551234567'),
external_id: 'USER_12345'
});
// Track event
ttq.track('CompletePayment', {
value: 99.99,
currency: 'USD'
});
Multiple Pixels
For managing multiple business units or brands:
// Load multiple pixels
ttq.load('PIXEL_ID_1');
ttq.load('PIXEL_ID_2');
// Fire events to all pixels
ttq.page();
// Fire to specific pixel
ttq.instance('PIXEL_ID_1').track('AddToCart', {
value: 29.99,
currency: 'USD'
});
TikTok Events API
What is the Events API?
The TikTok Events API enables server-side event tracking, providing more reliable measurement than browser-based pixels, especially with ad blockers and privacy restrictions.
Benefits
- Browser-independent tracking - Not affected by ad blockers
- Improved data accuracy - Direct server-to-TikTok connection
- Better attribution - Server-side data less prone to loss
- Enhanced privacy - Control what data is shared
- Event deduplication - Combine with Pixel for complete coverage
Events API Implementation
Node.js Example
const axios = require('axios');
const crypto = require('crypto');
function hashSHA256(data) {
return crypto.createHash('sha256')
.update(data.toLowerCase().trim())
.digest('hex');
}
async function sendTikTokEvent(eventData) {
const payload = {
pixel_code: process.env.TIKTOK_PIXEL_ID,
event: 'CompletePayment',
event_id: `ORDER_${eventData.orderId}_${Date.now()}`,
timestamp: new Date().toISOString(),
context: {
user_agent: eventData.userAgent,
ip: eventData.ipAddress,
page: {
url: eventData.pageUrl,
referrer: eventData.referrer
},
user: {
email: hashSHA256(eventData.email),
phone_number: hashSHA256(eventData.phone),
external_id: eventData.userId,
ttp: eventData.ttpCookie // From _ttp browser cookie
}
},
properties: {
value: eventData.value,
currency: eventData.currency,
content_type: 'product',
contents: eventData.items.map(item => ({
content_id: item.sku,
quantity: item.quantity,
price: item.price
}))
}
};
const response = await axios.post(
'https://business-api.tiktok.com/open_api/v1.3/event/track/',
{
event_source: 'web',
event_source_id: process.env.TIKTOK_PIXEL_ID,
data: [payload]
},
{
headers: {
'Access-Token': process.env.TIKTOK_ACCESS_TOKEN,
'Content-Type': 'application/json'
}
}
);
return response.data;
}
Python Example
import requests
import hashlib
import time
from datetime import datetime
def hash_sha256(data):
return hashlib.sha256(data.lower().strip().encode()).hexdigest()
def send_tiktok_event(event_data):
payload = {
"pixel_code": os.environ['TIKTOK_PIXEL_ID'],
"event": "CompletePayment",
"event_id": f"ORDER_{event_data['order_id']}_{int(time.time())}",
"timestamp": datetime.utcnow().isoformat(),
"context": {
"user_agent": event_data['user_agent'],
"ip": event_data['ip_address'],
"page": {
"url": event_data['page_url'],
"referrer": event_data.get('referrer', '')
},
"user": {
"email": hash_sha256(event_data['email']),
"phone_number": hash_sha256(event_data['phone']),
"external_id": event_data['user_id'],
"ttp": event_data.get('ttp_cookie', '')
}
},
"properties": {
"value": event_data['value'],
"currency": event_data['currency'],
"content_type": "product",
"contents": [
{
"content_id": item['sku'],
"quantity": item['quantity'],
"price": item['price']
}
for item in event_data['items']
]
}
}
headers = {
'Access-Token': os.environ['TIKTOK_ACCESS_TOKEN'],
'Content-Type': 'application/json'
}
response = requests.post(
'https://business-api.tiktok.com/open_api/v1.3/event/track/',
json={
'event_source': 'web',
'event_source_id': os.environ['TIKTOK_PIXEL_ID'],
'data': [payload]
},
headers=headers
)
return response.json()
Event Deduplication
Prevent duplicate counting when using both Pixel and Events API:
// Browser-side (Pixel)
const eventId = `ORDER_${orderId}_${Date.now()}`;
ttq.track('CompletePayment', {
value: 99.99,
currency: 'USD',
event_id: eventId // Deduplication key
});
// Server-side (Events API) - Use same event_id
const payload = {
event_id: eventId, // Matches browser event
// ... rest of event data
};
Partner Integrations
Shopify Integration
TikTok offers native integration with Shopify for seamless eCommerce tracking.
Setup Steps
Install TikTok App
- Go to Shopify App Store
- Search "TikTok"
- Click "Add app"
Connect Accounts
- Log in with TikTok Business account
- Select or create TikTok Ads account
- Authorize connection
Configure Pixel
- Pixel automatically installs on all pages
- Standard events auto-configured:
- ViewContent (Product pages)
- AddToCart
- InitiateCheckout
- CompletePayment
Sync Product Catalog
- Products sync to TikTok Catalog
- Enable TikTok Shopping
- Create dynamic product ads
Benefits
- Automatic pixel installation - No coding required
- Product catalog sync - Real-time inventory updates
- Order tracking - Automatic purchase events
- TikTok Shopping - In-app checkout
- Dynamic ads - Retarget with product catalogs
Advanced Configuration
// Add custom Shopify tracking
// theme.liquid or custom script
// Track cart additions with product data
{% if template contains 'product' %}
<script>
ttq.track('ViewContent', {
content_type: 'product',
content_id: '{{ product.id }}',
content_name: '{{ product.title | escape }}',
price: {{ product.price | money_without_currency }},
currency: '{{ shop.currency }}',
content_category: '{{ product.type }}'
});
</script>
{% endif %}
BigCommerce Integration
Setup Process
Install TikTok App
- BigCommerce App Marketplace
- Install "TikTok for BigCommerce"
Configure Integration
- Connect TikTok Ads account
- Authorize data sharing
- Map product attributes
Enable Features
- Auto-install pixel
- Sync product catalog
- Enable order tracking
Catalog Mapping
| BigCommerce Field | TikTok Field |
|---|---|
| Product ID | content_id |
| Product Name | content_name |
| Category | content_category |
| Price | price |
| Image URL | image_link |
| Product URL | link |
WooCommerce Integration
Plugin Installation
- Install "PixelYourSite" or "TikTok for WooCommerce" plugin
- Enter TikTok Pixel ID in settings
- Configure event tracking options
- Enable enhanced eCommerce tracking
Manual Implementation
// functions.php
// Add TikTok Pixel to header
add_action('wp_head', 'add_tiktok_pixel');
function add_tiktok_pixel() {
?>
<script>
!function (w, d, t) {
// TikTok Pixel base code
ttq.load('<?php echo get_option('tiktok_pixel_id'); ?>');
ttq.page();
}(window, document, 'ttq');
</script>
<?php
}
// Track purchase on order received page
add_action('woocommerce_thankyou', 'tiktok_track_purchase');
function tiktok_track_purchase($order_id) {
$order = wc_get_order($order_id);
$items = array();
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = array(
'content_id' => $product->get_sku(),
'content_name' => $product->get_name(),
'quantity' => $item->get_quantity(),
'price' => $product->get_price()
);
}
?>
<script>
ttq.track('CompletePayment', {
value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $order->get_currency(); ?>',
content_type: 'product',
contents: <?php echo json_encode($items); ?>,
order_id: '<?php echo $order_id; ?>'
});
</script>
<?php
}
Magento Integration
Extension Installation
- Download TikTok Pixel extension
- Upload to Magento installation
- Enable module:
bin/magento module:enable TikTok_Pixel - Configure in Admin > Stores > Configuration > TikTok
Event Tracking Configuration
- ViewContent - Product pages
- AddToCart - Cart additions
- InitiateCheckout - Checkout start
- CompletePayment - Order success
TikTok Marketing API
API Overview
The TikTok Marketing API enables programmatic campaign management, reporting, and audience management.
Authentication
Access Token Generation
- Create TikTok for Business account
- Navigate to TikTok for Business > Marketing API
- Create app and generate access token
- Store token securely
// API authentication example
const axios = require('axios');
const tiktokAPI = axios.create({
baseURL: 'https://business-api.tiktok.com/open_api/v1.3/',
headers: {
'Access-Token': process.env.TIKTOK_ACCESS_TOKEN,
'Content-Type': 'application/json'
}
});
Campaign Management
Create Campaign
async function createCampaign() {
const response = await tiktokAPI.post('campaign/create/', {
advertiser_id: 'YOUR_ADVERTISER_ID',
campaign_name: 'Q1 Product Launch',
objective_type: 'CONVERSIONS',
budget_mode: 'BUDGET_MODE_TOTAL',
budget: 10000.00,
operation_status: 'ENABLE'
});
return response.data;
}
Fetch Campaign Performance
async function getCampaignStats(campaignId) {
const response = await tiktokAPI.get('reports/integrated/get/', {
params: {
advertiser_id: 'YOUR_ADVERTISER_ID',
report_type: 'BASIC',
data_level: 'AUCTION_CAMPAIGN',
dimensions: ['campaign_id'],
metrics: [
'spend',
'impressions',
'clicks',
'ctr',
'conversions',
'cost_per_conversion'
],
start_date: '2025-01-01',
end_date: '2025-01-31',
filtering: [{
field: 'campaign_id',
operator: 'EQUALS',
value: campaignId
}]
}
});
return response.data;
}
Audience Management
Create Custom Audience
async function createCustomAudience(userList) {
const response = await tiktokAPI.post('dmp/custom_audience/create/', {
advertiser_id: 'YOUR_ADVERTISER_ID',
custom_audience_name: 'Email List - Q1 2025',
file_paths: ['path/to/uploaded/file'],
id_type: 'EMAIL',
is_hashed: true,
operation_status: 'ENABLE'
});
return response.data;
}
Upload User Data
const crypto = require('crypto');
function hashEmail(email) {
return crypto.createHash('sha256')
.update(email.toLowerCase().trim())
.digest('hex');
}
async function uploadAudienceData(emails) {
const hashedEmails = emails.map(hashEmail);
const response = await tiktokAPI.post('dmp/custom_audience/file/upload/', {
advertiser_id: 'YOUR_ADVERTISER_ID',
calculate_type: 'ID',
file_content: hashedEmails.join('\n')
});
return response.data;
}
Reporting API
Fetch Ad Performance
import requests
import os
from datetime import datetime, timedelta
def get_ad_performance(advertiser_id, start_date, end_date):
url = 'https://business-api.tiktok.com/open_api/v1.3/reports/integrated/get/'
headers = {
'Access-Token': os.environ['TIKTOK_ACCESS_TOKEN'],
'Content-Type': 'application/json'
}
params = {
'advertiser_id': advertiser_id,
'report_type': 'BASIC',
'data_level': 'AUCTION_AD',
'dimensions': ['ad_id', 'stat_time_day'],
'metrics': [
'spend',
'impressions',
'clicks',
'ctr',
'cpm',
'cpc',
'conversions',
'cost_per_conversion',
'conversion_rate'
],
'start_date': start_date,
'end_date': end_date,
'page_size': 1000
}
response = requests.get(url, params=params, headers=headers)
return response.json()
# Example usage
performance = get_ad_performance(
advertiser_id='1234567890',
start_date='2025-01-01',
end_date='2025-01-31'
)
Google Tag Manager Integration
Container Setup
Create TikTok Pixel Variable
- Variables > New > Constant
- Name: "TikTok Pixel ID"
- Value: Your pixel ID
Create Base Pixel Tag
Create Event Tags
- Tags > New > Custom HTML
- Add event tracking code
- Trigger: Based on page or dataLayer events
DataLayer Integration
// Push to dataLayer on purchase
window.dataLayer = window.dataLayer || [];
dataLayer.push({
'event': 'purchase',
'transactionId': 'ORDER_12345',
'transactionTotal': 199.98,
'transactionProducts': [
{
'sku': 'SKU_123',
'name': 'Blue Widget',
'price': 99.99,
'quantity': 2
}
]
});
GTM Event Tag
<script>
ttq.track('CompletePayment', {
value: {{Transaction Total}},
currency: 'USD',
order_id: {{Transaction ID}},
contents: {{Transaction Products}}
});
</script>
Best Practices
Integration Strategy
- Start with TikTok Pixel for browser-based tracking
- Add Events API for server-side backup
- Implement deduplication with event_id
- Use platform integrations where available
- Test thoroughly before going live
Data Quality
- Hash all PII before sending (email, phone)
- Pass complete event parameters for optimization
- Match content_id to product catalog exactly
- Include currency for all monetary values
- Use external_id for user identification
Privacy & Compliance
- Implement consent management for GDPR/CCPA
- Update privacy policy to disclose TikTok tracking
- Honor user opt-outs through platform controls
- Use Limited Data Use flag when required
- Audit data sharing regularly
Performance Optimization
- Load pixel asynchronously to avoid blocking
- Minimize custom events (prefer standard events)
- Batch API calls when possible
- Monitor Event Quality Score in Events Manager
- Test integrations with TikTok Pixel Helper
Troubleshooting
Pixel Not Loading
- Verify pixel ID is correct
- Check for JavaScript errors in console
- Ensure script loads before events fire
- Test without ad blockers
Events Not Tracking
- Wait 15-30 minutes for processing
- Verify event names (case-sensitive)
- Check Events Manager for errors
- Validate event parameters
API Errors
- Verify access token is valid
- Check request format against API docs
- Review rate limits
- Validate required fields included
Integration Issues
- Verify platform connection status
- Check catalog sync settings
- Review product mapping
- Test with single product first