How to setup a server to server (S2S) integration
How to setup a S2S pixel integration
This document provides a comprehensive guide to implementing a server-to-server (S2S) data integration for tracking events within Audiohook. Follow the steps below to ensure your integration is set up correctly.
Overview
Server-to-server tracking allows you to send event data directly from your backend to a tracking endpoint. This is useful for tracking user actions that occur outside the browser, such as order confirmations, subscription changes, or other server-side activities.
Steps to Implement S2S Tracking
1. Identify the Endpoint
Send POST requests to the following endpoint, replacing YOUR_AUDIOHOOK_ID
with your unique identifier:
<https://listen.audiohook.com/YOUR_AUDIOHOOK_ID/pixel.png>
The Content-Type
header of the request must be set to application/json
.
2. Event Data Structure
Each event must include the following fields:
Required Fields
- ip_address: The IP address of the user.
- user_agent: The userβs browser or device user agent string.
- event_name: The name of the event (e.g.,
purchase
,subscription_created
,pageview
).
Recommended Fields
- url: The page URL where the event occurred.
- referrer: The URL of the referring page.
- persistent_anonymous_user_id: A unique ID to identify the user anonymously across sessions.
- session_id: A session identifier to group related events.
- event_payload: Additional event-specific data (e.g., product details, order value).
Example Event Payload
{
"event_name": "pageview",
"timestamp": "2024-01-15T10:30:00.000Z",
"visitor_id": "uuid-visitor-id",
"session_id": "uuid-session-id",
"url": "<https://example.com/page>",
"referrer": "<https://previous-page.com>",
"user_agent": "User-Agent-String",
"ip_address": "192.168.1.100"
}
3. Event Examples
Purchase Confirmation Event
{
"event_name": "purchase",
"timestamp": "2024-01-15T10:30:00.000Z",
"visitor_id": "123e4567-e89b-12d3-a456-426614174000",
"session_id": "987fcdeb-51a2-43d1-89ab-123456789012",
"url": "<https://example.com/checkout/success>",
"referrer": "<https://example.com/checkout>",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"ip_address": "203.0.113.195",
"order_id": "ORDER123",
"value": 99.99,
"currency": "USD",
"items": [
{
"product_id": "123",
"product_name": "Example Product",
"price": 29.99,
"quantity": 1
}
]
}
Subscription Event
{
"event_name": "subscription_created",
"timestamp": "2024-01-15T10:30:00.000Z",
"visitor_id": "123e4567-e89b-12d3-a456-426614174000",
"session_id": "987fcdeb-51a2-43d1-89ab-123456789012",
"url": "<https://example.com/subscription/success>",
"referrer": "<https://example.com/pricing>",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
"ip_address": "198.51.100.42",
"subscription_id": "sub_12345",
"plan_name": "Premium Plan",
"value": 29.99,
"currency": "USD",
"billing_cycle": "monthly"
}
4. Implementation Examples
Node.js/Express
const fetch = require('node-fetch');
async function trackServerEvent(audiohookId, eventData) {
const endpoint = `https://listen.audiohook.com/${audiohookId}/pixel.png`;
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(eventData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log('Event tracked successfully');
} catch (error) {
console.error('Failed to track event:', error);
}
}
// Usage
await trackServerEvent('YOUR_AUDIOHOOK_ID', {
event_name: 'purchase',
timestamp: new Date().toISOString(),
visitor_id: 'user-visitor-id',
session_id: 'user-session-id',
url: '<https://example.com/checkout/success>',
referrer: '<https://example.com/checkout>',
user_agent: req.headers['user-agent'],
ip_address: req.ip || req.connection.remoteAddress
});
Python/Django
import requests
import json
from datetime import datetime
def track_server_event(audiohook_id, event_data):
endpoint = f"<https://listen.audiohook.com/{audiohook_id}/pixel.png>"
try:
response = requests.post(
endpoint,
headers={'Content-Type': 'application/json'},
data=json.dumps(event_data)
)
response.raise_for_status()
print("Event tracked successfully")
except requests.exceptions.RequestException as e:
print(f"Failed to track event: {e}")
# Usage
track_server_event('YOUR_AUDIOHOOK_ID', {
'event_name': 'purchase',
'timestamp': datetime.utcnow().isoformat() + 'Z',
'visitor_id': 'user-visitor-id',
'session_id': 'user-session-id',
'url': '<https://example.com/checkout/success>',
'referrer': '<https://example.com/checkout>',
'user_agent': request.META.get('HTTP_USER_AGENT', ''),
'ip_address': request.META.get('REMOTE_ADDR')
})
PHP
function trackServerEvent($audiohookId, $eventData) {
$endpoint = "<https://listen.audiohook.com/{$audiohookId}/pixel.png>";
$options = [
'http' => [
'header' => "Content-Type: application/json\\r\\n",
'method' => 'POST',
'content' => json_encode($eventData)
]
];
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
if ($result === FALSE) {
error_log("Failed to track event");
} else {
error_log("Event tracked successfully");
}
}
// Usage
trackServerEvent('YOUR_AUDIOHOOK_ID', [
'event_name' => 'purchase',
'timestamp' => date('c'),
'visitor_id' => 'user-visitor-id',
'session_id' => 'user-session-id',
'url' => '<https://example.com/checkout/success>',
'referrer' => '<https://example.com/checkout>',
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'ip_address' => $_SERVER['REMOTE_ADDR']
]);
5. Best Practices
- PII Handling: Hash any Personally Identifiable Information (e.g., email, phone number) before sending. Use SHA-256 for hashing.
- Error Handling: Implement retry logic for failed requests to ensure data integrity.
- Timestamps: Use ISO 8601 format (
YYYY-MM-DDTHH:mm:ss.sssZ
) for all timestamps.
6. Security
- All communication must use HTTPS.
- Use first-party cookies and implement the SameSite cookie policy for client-server consistency.
By following this guide, you can successfully set up and implement server-to-server tracking for your integration.