API Usage

Complete guide for using the Tandem Beam API for custom integrations and server-side event tracking. Learn authentication, endpoints, request formats, and error handling.

Developer Guide
REST API
v1.0

Technical Requirements

  • Active API token for your advertiser account
  • HTTP client capable of making POST requests with JSON payloads
  • Understanding of REST API concepts and JSON data formats
  • Server-side programming environment (Node.js, PHP, Python, etc.)

Step 1: Authentication Setup

The Tandem Beam API uses Bearer token authentication. All requests must include your API token in the Authorization header.

1.1

Obtain API Token

Navigate to your advertiser dashboard and generate an active API token from the API Tokens section. Copy the token value for use in your API requests.

1.2

Set Authorization Header

Include your API token in the Authorization header with the Bearer scheme:

Authorization Header Format:

Authorization: Bearer your_api_token_here
Security: Never expose your API token in client-side code or public repositories. Store tokens securely in environment variables or secret management systems.

Step 2: Base URL Configuration

Production

Live Environment

https://api.tandembeam.com

Use for production tracking with real customer data

Development

Testing Environment

https://dev.tandembeam.com

Use for testing and development workflows

2.1

CNAME Configuration (Optional)

For better tracking reliability and first-party context, configure a CNAME record pointing to the API domain:

Benefits:

  • • First-party context (API calls from your domain)
  • • Reduced ad-blocker interference
  • • Better cookie handling (first-party cookies)
  • • No CORS complexity

Example CNAME:

beam.yourdomain.com → CNAME → api.tandembeam.com

Step 3: Track Event Endpoint

3.1

Endpoint Overview

POST
/api/track

Primary endpoint for tracking all event types. Accepts JSON payloads with event data and returns confirmation with event ID.

3.2

Request Format

All requests must be POST with JSON content type:

Required Headers:

Content-Type: application/json
Authorization: Bearer your_api_token_here
3.3

Request Body Structure

Event payloads must include event_name and event_data at minimum:

Basic Event Structure:

{
  "event_name": "purchase",
  "event_data": {
    "event_id": "purchase-12345",
    "transaction_id": "TXN-ABC123",
    "value": 29.99,
    "currency": "USD"
  },
  "user_data": {
    "email_hash": "hashed_email",
    "phone_hash": "hashed_phone"
  },
  "action_source": "website"
}
Important: PII (email, phone) must be SHA-256 hashed before sending to the API. The API will reject requests containing unhashed PII for security and privacy compliance.

Step 4: Implementation Examples

4.1

cURL Example

Track a purchase event:

curl -X POST https://api.tandembeam.com/api/track \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your_api_token_here" \
  -d '{
    "event_name": "purchase",
    "event_data": {
      "event_id": "purchase-12345",
      "transaction_id": "TXN-ABC123",
      "value": 29.99,
      "currency": "USD",
      "content_ids": ["product-1", "product-2"],
      "content_type": "product"
    },
    "user_data": {
      "email_hash": "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
      "phone_hash": "b3d8c7e5f2a4d9e1c6b8a5f3e2d9c7b4a6e8f1d3c5b7a9e2f4d6c8b1a3e5f7d9"
    },
    "action_source": "website"
  }'
4.2

JavaScript (Node.js) Example

Using fetch API:

const crypto = require('crypto');

// Helper function to hash PII
function hashPII(data) {
  return crypto.createHash('sha256').update(data.toLowerCase().trim()).digest('hex');
}

// Track event
async function trackEvent(eventName, eventData, userData = {}) {
  const response = await fetch('https://api.tandembeam.com/api/track', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer your_api_token_here'
    },
    body: JSON.stringify({
      event_name: eventName,
      event_data: eventData,
      user_data: {
        email_hash: userData.email ? hashPII(userData.email) : undefined,
        phone_hash: userData.phone ? hashPII(userData.phone) : undefined
      },
      action_source: 'website'
    })
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return await response.json();
}

// Example usage
trackEvent('purchase', {
  event_id: 'purchase-12345',
  transaction_id: 'TXN-ABC123',
  value: 29.99,
  currency: 'USD',
  content_ids: ['product-1', 'product-2']
}, {
  email: 'customer@example.com',
  phone: '+15551234567'
})
.then(result => console.log('Event tracked:', result))
.catch(error => console.error('Tracking error:', error));
4.3

PHP Example

Using cURL extension:

<?php

// Helper function to hash PII
function hashPII($data) {
    return hash('sha256', strtolower(trim($data)));
}

// Track event function
function trackEvent($eventName, $eventData, $userData = []) {
    $apiToken = 'your_api_token_here';
    $apiUrl = 'https://api.tandembeam.com/api/track';

    $payload = [
        'event_name' => $eventName,
        'event_data' => $eventData,
        'user_data' => [
            'email_hash' => isset($userData['email']) ? hashPII($userData['email']) : null,
            'phone_hash' => isset($userData['phone']) ? hashPII($userData['phone']) : null,
        ],
        'action_source' => 'website'
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiToken
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception("API error: HTTP $httpCode");
    }

    return json_decode($response, true);
}

// Example usage
try {
    $result = trackEvent('purchase', [
        'event_id' => 'purchase-12345',
        'transaction_id' => 'TXN-ABC123',
        'value' => 29.99,
        'currency' => 'USD',
        'content_ids' => ['product-1', 'product-2']
    ], [
        'email' => 'customer@example.com',
        'phone' => '+15551234567'
    ]);

    echo "Event tracked: " . print_r($result, true);
} catch (Exception $e) {
    echo "Tracking error: " . $e->getMessage();
}
?>
4.4

Python Example

Using requests library:

import requests
import hashlib

def hash_pii(data):
    """Hash PII using SHA-256"""
    return hashlib.sha256(data.lower().strip().encode()).hexdigest()

def track_event(event_name, event_data, user_data=None):
    """Track event via Tandem Beam API"""
    api_token = 'your_api_token_here'
    api_url = 'https://api.tandembeam.com/api/track'

    payload = {
        'event_name': event_name,
        'event_data': event_data,
        'user_data': {
            'email_hash': hash_pii(user_data.get('email')) if user_data and 'email' in user_data else None,
            'phone_hash': hash_pii(user_data.get('phone')) if user_data and 'phone' in user_data else None,
        },
        'action_source': 'website'
    }

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_token}'
    }

    response = requests.post(api_url, json=payload, headers=headers)
    response.raise_for_status()

    return response.json()

# Example usage
try:
    result = track_event('purchase', {
        'event_id': 'purchase-12345',
        'transaction_id': 'TXN-ABC123',
        'value': 29.99,
        'currency': 'USD',
        'content_ids': ['product-1', 'product-2']
    }, {
        'email': 'customer@example.com',
        'phone': '+15551234567'
    })

    print(f"Event tracked: {result}")
except requests.exceptions.RequestException as e:
    print(f"Tracking error: {e}")

Step 5: Response Handling

5.1

Success Response

Successful requests return HTTP 200 with event confirmation:

Success Response (200 OK):

{
  "success": true,
  "event_id": 1234,
  "message": "Event tracked successfully"
}
5.2

Error Responses

Handle common error scenarios with appropriate retry logic:

401 Unauthorized

Invalid or expired API token

{
  "error": "Unauthenticated",
  "message": "Invalid API token"
}

Action: Verify token is active and correctly formatted

400 Bad Request

Invalid request payload or unhashed PII

{
  "error": "Validation Error",
  "message": "PII must be hashed",
  "details": {
    "user_data.em": ["Raw email detected - must be SHA-256 hashed"]
  }
}

Action: Hash PII before sending, verify required fields present

429 Too Many Requests

Rate limit exceeded

{
  "error": "Rate Limit Exceeded",
  "message": "Too many requests - retry after 60 seconds"
}

Action: Implement exponential backoff retry logic

Advanced Configuration

Batch Event Submission

For high-volume scenarios, batch multiple events in a single request:

  • Reduce API call overhead
  • Improved throughput for bulk operations
  • Recommended batch size: 10-50 events

Retry Logic

Implement robust retry strategies for production reliability:

  • Exponential backoff: 1s, 2s, 4s, 8s
  • Max 3-5 retry attempts
  • Queue failed events for later retry

Best Practices

API Usage Guidelines

Always Hash PII: Use SHA-256 for email and phone before API transmission. Normalize (lowercase, trim) before hashing for consistency.
Use Unique Event IDs: Generate unique identifiers to prevent duplicate events across platforms (e.g., order_id or uuid).
Implement Retry Logic: Handle transient failures gracefully with exponential backoff. Queue failed events for later retry.
Monitor API Responses: Log errors and track success rates. Set up alerts for high error rates or API availability issues.
Use Environment Variables: Never hardcode API tokens in source code. Use environment variables or secret management systems.

Troubleshooting

Common API Issues

401 Authentication Errors
Verify API token is active in advertiser dashboard. Check Authorization header format includes "Bearer " prefix. Ensure token hasn't expired or been revoked.
400 Validation Errors for PII
Ensure email and phone are SHA-256 hashed before sending. Verify hash function uses lowercase and trimmed input for consistency. Raw PII will be rejected.
Network Timeout Errors
Increase request timeout to 30+ seconds. Check network connectivity and firewall rules. Verify DNS resolution for api.tandembeam.com. Consider using CNAME if issues persist.
Events Not Appearing in Dashboard
Verify API returns 200 OK response. Check Intelligence Reports time filter includes event timestamp. Confirm advertiser_id matches if using custom header. Review API response for event_id confirmation.

Next Steps

Once your API integration is working, configure Event Settings to forward events to advertising platforms and test your implementation thoroughly.