X (Twitter) Ads Event Tracking: Setup Guide | OpsBlu Docs

X (Twitter) Ads Event Tracking: Setup Guide

X Ads (Twitter) Pixel event tracking for purchase conversions, audience building, and automated bidding optimization.

Overview

X (formerly Twitter) uses the X Pixel for conversion tracking, audience building, and campaign optimization. The platform tracks website events, app installs, and engagement actions to measure campaign performance and enable automated bidding strategies. X's real-time nature and conversation-focused audience make conversion tracking essential for brand awareness, performance marketing, and customer engagement campaigns.

Standard Events

X provides predefined events for common conversion actions:

Ecommerce Events

  • Purchase - Completed transaction
  • Add to Cart - Product added to shopping cart
  • Checkout Initiated - Checkout process started
  • Add to Wishlist - Product saved to wishlist
  • View Content - Product or content page viewed

Lead Generation Events

  • Sign Up - Account registration or newsletter signup
  • Lead - Lead form submission or contact request
  • Submit Application - Application submission
  • Subscribe - Paid subscription started

Engagement Events

  • Download - File, app, or content download
  • Search - Site search performed
  • Video Started - Video playback initiated
  • Video Completed - Video watched to completion
  • Click Button - Specific button or CTA clicked

App Events

  • Install - Mobile app installation
  • Tutorial Completed - App onboarding completed
  • Achievement Unlocked - In-app milestone reached
  • Level Completed - Game level or section completed
  • Rate - App or product rating submitted

General Events

  • Page View - Website page visit (automatically tracked)
  • Custom - Custom business-specific events

Custom Events

Creating Custom Events

Track business-specific actions with custom events:

// Custom event
twq('event', 'custom_event_name', {
  value: 25.00,
  currency: 'USD',
  description: 'Product comparison completed'
});

Event Parameters

Add custom parameters to any event:

twq('event', 'tw-purchase', {
  value: '99.99',
  currency: 'USD',
  num_items: '2',
  content_ids: ['SKU_123', 'SKU_456'],
  content_type: 'product',
  content_name: 'Blue Widget',
  // Custom parameters
  product_category: 'Widgets',
  customer_type: 'returning',
  shipping_method: 'express'
});

Dynamic Parameters

Pass dynamic values from page data:

twq('event', 'tw-purchase', {
  value: document.getElementById('order-total').textContent,
  currency: 'USD',
  order_id: getOrderId(),
  num_items: getCartCount()
});

Ecommerce Events

Purchase Tracking

Complete purchase implementation:

<!-- X Pixel Base Code (on all pages) -->
<script>
!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',
a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');
twq('config','YOUR_PIXEL_ID');
</script>

<!-- Purchase Event (on confirmation page) -->
<script>
twq('event', 'tw-purchase', {
  value: '149.99',
  currency: 'USD',
  num_items: '3',
  content_ids: ['SKU_123', 'SKU_456'],
  content_type: 'product',
  order_id: 'ORDER_12345'
});
</script>

Shopping Funnel Events

Track the complete customer journey:

// View Content (Product Page)
twq('event', 'tw-view-content', {
  content_ids: ['SKU_123'],
  content_type: 'product',
  content_name: 'Blue Widget',
  value: '99.99',
  currency: 'USD'
});

// Add to Cart
twq('event', 'tw-add-to-cart', {
  value: '99.99',
  currency: 'USD',
  content_ids: ['SKU_123'],
  content_type: 'product',
  num_items: '1'
});

// Initiate Checkout
twq('event', 'tw-initiate-checkout', {
  value: '149.99',
  currency: 'USD',
  num_items: '3',
  content_ids: ['SKU_123', 'SKU_456']
});

// Purchase
twq('event', 'tw-purchase', {
  value: '149.99',
  currency: 'USD',
  num_items: '3',
  order_id: 'ORDER_12345',
  content_ids: ['SKU_123', 'SKU_456']
});

Product Parameters

Pass detailed product information:

twq('event', 'tw-purchase', {
  value: '249.98',
  currency: 'USD',
  num_items: '2',
  order_id: 'ORDER_12345',
  content_ids: ['SKU_001', 'SKU_002'],
  content_type: 'product',
  content_name: 'Electronics Bundle',
  contents: [
    {
      content_id: 'SKU_001',
      content_name: 'Wireless Headphones',
      content_price: '149.99',
      num_items: '1'
    },
    {
      content_id: 'SKU_002',
      content_name: 'Smart Watch',
      content_price: '99.99',
      num_items: '1'
    }
  ]
});

Conversion Tracking

Implementation Methods

1. X Pixel (Browser-Side)

Standard JavaScript implementation:

<!-- Universal Website Tag (all pages) -->
<script>
!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',
a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');
twq('config','YOUR_PIXEL_ID');
</script>

<!-- Event-Specific Tracking -->
<script>
twq('event', 'tw-purchase', {
  value: '99.99',
  currency: 'USD'
});
</script>

2. Google Tag Manager

Deploy X Pixel via GTM:

Base Tag:

// GTM Custom HTML Tag - All Pages
<script>
!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',
a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');
twq('config','{{X Pixel ID}}');
</script>

Event Tags:

// Purchase Event via GTM
<script>
twq('event', 'tw-purchase', {
  value: {{Transaction Value}},
  currency: 'USD',
  order_id: {{Transaction ID}},
  num_items: {{Item Count}}
});
</script>

3. Conversions API

Server-side conversion tracking:

// Node.js example
const axios = require('axios');
const crypto = require('crypto');

function hashData(data) {
  return crypto.createHash('sha256').update(data.toLowerCase().trim()).digest('hex');
}

const conversionEvent = {
  event_id: 'ORDER_12345_' + Date.now(),
  event_time: new Date().toISOString(),
  identifiers: [
    {
      twclid: 'click_id_from_url',  // X click ID
      hashed_email: hashData('user@example.com'),
      hashed_phone_number: hashData('+15551234567')
    }
  ],
  conversions: [
    {
      conversion_event: 'tw-purchase',
      conversion_time: new Date().toISOString(),
      event_metadata: {
        value: '99.99',
        currency: 'USD',
        order_id: 'ORDER_12345',
        num_items: '2',
        content_ids: ['SKU_123', 'SKU_456']
      }
    }
  ]
};

const response = await axios.post(
  'https://ads-api.twitter.com/11/measurement/conversions/YOUR_PIXEL_ID',
  conversionEvent,
  {
    headers: {
      'Authorization': `Bearer YOUR_ACCESS_TOKEN`,
      'Content-Type': 'application/json'
    }
  }
);

4. Mobile App Events

For app conversion tracking via X SDK:

iOS (Swift):

import TwitterKit

TWTRTwitter.sharedInstance().logPurchase(
  withPrice: NSDecimalNumber(string: "99.99"),
  currency: "USD",
  success: { () in
    print("Purchase tracked")
  },
  failure: { (error) in
    print("Error: \(error)")
  }
)

Android (Java):

import com.twitter.sdk.android.tweetcomposer.TweetComposer;

Twitter.getInstance().logPurchase(
  new BigDecimal("99.99"),
  "USD"
);

Advanced Matching

Improve conversion attribution with user data:

// Enhanced matching
twq('config', 'YOUR_PIXEL_ID', {
  email_address: hashEmail('user@example.com'),  // SHA256 hash
  phone_number: hashPhone('+15551234567')
});

function hashEmail(email) {
  return CryptoJS.SHA256(email.toLowerCase().trim()).toString();
}

Event Deduplication

Prevent duplicate events:

// Use order_id for deduplication
twq('event', 'tw-purchase', {
  value: '99.99',
  currency: 'USD',
  order_id: 'ORDER_12345'  // Prevents duplicate conversions
});

Offline Conversions

Conversions API for Offline Events

Upload offline conversions via API:

import requests
import hashlib
import time

def hash_value(value):
    return hashlib.sha256(value.lower().strip().encode()).hexdigest()

# Offline conversion
conversion_data = {
    "event_id": f"OFFLINE_{int(time.time())}",
    "event_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    "identifiers": [{
        "hashed_email": hash_value("customer@example.com"),
        "hashed_phone_number": hash_value("+15551234567")
    }],
    "conversions": [{
        "conversion_event": "tw-purchase",
        "conversion_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "event_metadata": {
            "value": "149.99",
            "currency": "USD",
            "order_id": "OFFLINE_ORDER_12345"
        }
    }]
}

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

response = requests.post(
    f"https://ads-api.twitter.com/11/measurement/conversions/{pixel_id}",
    json=conversion_data,
    headers=headers
)

CRM Integration

Connect CRM for automated offline conversions:

Implementation:

  1. Capture X click ID (twclid parameter) from URL
  2. Store in CRM with lead/customer record
  3. Export conversions with twclid or hashed identifiers
  4. Upload via Conversions API

Attribution

Attribution Windows

Configure attribution settings:

Default Windows:

  • Post-engagement: 30 days from X engagement
  • Post-view: 1 day from ad impression

Customizable Options:

  • 1, 7, 14, 30, 60, or 90 days post-engagement
  • 1 or 7 days post-view

Configure in: X Ads Manager > Tools > Events Manager > Attribution Settings

Attribution Models

X uses last-touch attribution:

  • Last X engagement (click, like, retweet, reply) gets credit
  • Post-view attribution for impressions
  • Cross-device attribution for logged-in users

Engagement Attribution

Unique to X, track conversions from various engagements:

Tracked Engagements:

  • Ad clicks
  • Retweets
  • Likes
  • Replies
  • Profile visits
  • Follows

All engagements within attribution window can drive conversions.

Mobile App Attribution

For app install campaigns:

Partners:

  • AppsFlyer
  • Adjust
  • Kochava
  • Branch
  • Singular

Metrics:

  • App installs
  • Post-install events
  • In-app purchases
  • Re-engagement actions

Debugging & Validation

X Pixel Helper

Browser extension for pixel validation:

  1. Install X Pixel Helper Chrome extension
  2. Visit page with X Pixel
  3. Review:
    • Pixel ID detected
    • Events fired
    • Event parameters
    • Errors or warnings

Test Events

Generate test events in Events Manager:

  1. Navigate to Tools > Events Manager
  2. Select your pixel
  3. Click Test Events
  4. Enter test event code
  5. Generate events on your site
  6. View real-time event data

Events Manager

Monitor pixel health:

X Ads Manager > Tools > Events Manager:

  • Pixel status (active/inactive)
  • Events received (last 7, 28 days)
  • Event types breakdown
  • Top converting events

Browser Console Testing

Verify pixel in browser console:

// Check if twq is loaded
if (typeof twq !== 'undefined') {
  console.log('X Pixel loaded');
  console.log('Pixel queue:', twq.queue);
} else {
  console.error('X Pixel not found');
}

// Fire test event
twq('event', 'tw-purchase', {
  value: '1.00',
  currency: 'USD',
  order_id: 'TEST_' + Date.now()
});

Common Issues

Pixel not loading:

  • Verify Pixel ID is correct
  • Check script loads before events fire
  • Ensure no JavaScript errors in console
  • Test without ad blockers

Events not tracking:

  • Wait 15-30 minutes for processing
  • Verify event name format (e.g., 'tw-purchase')
  • Check required parameters included
  • Review Events Manager for errors

Low match rates:

  • Implement advanced matching with hashed data
  • Use Conversions API for server-side tracking
  • Include email and phone hashes
  • Verify hashing uses SHA256

Best Practices

Implementation

  1. Install X Pixel on all pages for complete funnel tracking
  2. Use both pixel and Conversions API for redundancy
  3. Implement advanced matching with hashed identifiers
  4. Use GTM for easier pixel management
  5. Include order_id for purchase deduplication

Event Strategy

  1. Track full funnel (ViewContent, AddToCart, Purchase)
  2. Use standard event names (tw-event-name format)
  3. Track engagement events (video views, downloads)
  4. Create separate pixels for different business units
  5. Monitor micro-conversions for audience building

Data Quality

  1. Pass value and currency for all revenue events
  2. Use consistent content_id format
  3. Include num_items for ecommerce events
  4. Send order_id for deduplication
  5. Hash PII using SHA256 before sending

Privacy & Compliance

  1. Implement consent management for GDPR/CCPA
  2. Hash all PII (email, phone) before transmission
  3. Update privacy policy to disclose X tracking
  4. Honor user opt-outs via platform controls
  5. Use X's privacy features for compliant tracking

Optimization

  1. Use conversion optimization for purchase campaigns
  2. Optimize to valuable events not just volume
  3. Create tailored audiences from converters
  4. Exclude converted users from acquisition
  5. Test different attribution windows based on sales cycle

Creative Best Practices

  1. Use native X content style (conversational, authentic)
  2. Include video for higher engagement
  3. Add clear CTAs within creative
  4. Test Conversation Ads for direct response
  5. Leverage trending topics and hashtags

Real-Time Marketing

  1. Monitor trending conversations for relevance
  2. React quickly to cultural moments
  3. Track engagement metrics alongside conversions
  4. Use X for customer service conversions
  5. Test different post times for audience reach

Testing

  1. Use X Pixel Helper to verify implementation
  2. Generate test events before launch
  3. Verify events in Events Manager within 30 minutes
  4. Test deduplication with order IDs
  5. Monitor pixel health for first 48 hours

Reporting

  1. Break down by placement (timeline vs search vs profiles)
  2. Segment by device and operating system
  3. Track engagement-driven conversions separately
  4. View post-view vs post-engagement attribution
  5. Export data for custom analysis

Audience Engagement

  1. Track replies and retweets as engagement events
  2. Build audiences from video viewers
  3. Create lookalikes from high-value converters
  4. Test Follower Campaigns for brand building
  5. Measure brand lift alongside direct response