AxiTrace Transaction event - parameters, required fields, and integration examples.

Transaction Event

Track completed purchases and orders. This is the most important conversion event for e-commerce analytics, revenue tracking, and marketing attribution. Maps to Facebook Purchase and TikTok CompletePayment standard events.

POST /v1/transaction

When to Use This Event

The transaction event should be triggered when a purchase is successfully completed. This typically occurs when:

  • Payment is confirmed and processed
  • Order is created in your system
  • User reaches the "Thank you" or order confirmation page
  • Subscription payment is successful
E-commerce Funnel Position

Transaction is the final conversion event in the e-commerce funnel:

page.view → product.view → product.addToCart → begin_checkout → transaction.charge

Server-Side Tracking Required

Transaction events MUST be tracked from your server-side code, never from the frontend.

Server-side tracking is critical for transactions because:

  • Accurate data - track only confirmed, successful payments
  • Security - use Secret Keys without exposing them to browsers
  • Fraud prevention - server validates payment before tracking
  • Reliability - not affected by ad blockers or browser issues
  • PCI compliance - sensitive payment data stays server-side

Facebook & TikTok Pixel Mapping

AxiTrace Facebook CAPI TikTok Events API
transaction.charge Purchase CompletePayment

Transaction data is forwarded to Facebook Conversions API and TikTok Events API automatically. To maximize match quality, include email, phone, fbp, fbc, and url in your request.

Request Parameters

Required Fields

Field Type Description
orderId string Unique order identifier from your system
source string Order source: WEB_DESKTOP, WEB_MOBILE, MOBILE_APP, POS, MOBILE, DESKTOP
revenue object Total revenue including tax and shipping (see Money Object below)
value object Order value/subtotal before tax and shipping (see Money Object below)
paymentInfo object Payment method details (see Payment Info below)
products array Array of purchased products. Must contain at least one item (see Products Array below)
client object Customer identification. Must contain at least one identifier (see Client Object below)

Money Object

Used for revenue, value, discountAmount, and product prices:

Field Type Description
amount number Monetary value (e.g., 99.99). Must be >= 0
currency string ISO 4217 currency code (e.g., USD, EUR, GBP)
Currency Consistency

All monetary values in a transaction (revenue, value, discountAmount, and all product finalUnitPrice values) must use the same currency. The server validates this and rejects transactions with mismatched currencies.

Payment Info Object

Field Type Required Description
method string Required Payment method: CASH, CARD, PAYPAL, STRIPE, BANK_TRANSFER, etc.

Client Object

Customer identification - at least one identifier is required:

Field Type Description
customId string Your custom customer identifier. Use the SDK's vt_vid cookie value to link the purchase to browsing history.
id integer Numeric customer ID from your database
uuid string UUID customer identifier
email string Customer email address. Improves Facebook CAPI Event Match Quality by up to 41%. Strongly recommended.
phone string Customer phone number. Improves Facebook CAPI match quality.
Critical: Link Purchase to Browsing Session

To attribute transactions to the user's browsing behavior, pass the SDK cookie values. The JavaScript SDK stores these in cookies:

  • vt_vid - Visitor ID → use as client.customId
  • vt_sid - Session ID → use as sessionId (top-level field)
  • vt_uid - User ID → use as client.uuid (if set via identify())

Without these, the transaction won't be linked to the user's product views, add-to-cart events, and traffic source. The AxiTrace PHP SDK reads these cookies automatically.

Products Array

Each product in the products array:

Field Type Required Description
sku string Required Product SKU or unique identifier
name string Required Product name
finalUnitPrice object Required Final unit price after discounts (Money Object). Currency must match transaction currency.
quantity number Required Quantity purchased (must be > 0)
categories array Optional Array of category strings (e.g., ["Electronics", "Phones"])
image string Optional Product image URL
url string Optional Product page URL
netUnitPrice object Optional Net price before tax (Money Object)
tax number Optional Tax amount per unit
regularPrice object Optional Original price before any discounts (Money Object)
discountPrice object Optional Discount amount per unit (Money Object)
discountPercent number Optional Discount percentage (e.g., 20 for 20%)
externalId string Optional Your product id (for example woocommerce:123). Profit tracking matches it against the external_id of your cost catalog before the SKU.
unitCost object Optional What one unit cost you, without VAT (Money Object, transaction currency, >= 0). Kept only with the Secret Key, removed otherwise. See Profit and POAS.

Optional Fields

Field Type Description
sessionId string Session ID for cross-SDK profile matching. Use the vt_sid cookie value to link this transaction to the browsing session. The PHP SDK sets this automatically.
fbp string Facebook pixel browser ID (from _fbp cookie). Improves Facebook CAPI match quality by ~36%. The PHP SDK reads this automatically when autoReadCookies is enabled.
fbc string Facebook click ID (from _fbc cookie). Contains click attribution data from Facebook ads. The PHP SDK reads this automatically.
url string Page URL for event_source_url in Facebook CAPI. Should match a verified domain in your Facebook pixel settings. Helps with domain matching when fbp/fbc are not available.
discountAmount object Total discount applied to order (Money Object). Amount must be > 0. Currency must match transaction currency.
metadata object Additional custom data (coupon codes, shipping method, notes, etc.)
recordedAt string ISO 8601 timestamp when the transaction occurred. If not provided or in the future, server time is used. Set it whenever the order is sent later than it was placed (a queue, a cron job that re-sends failed deliveries, a backfill), or the order is dated at the moment it arrives. The PHP SDK (1.8.0 or later) takes it as recorded_at in transaction() params or through TransactionEvent::setRecordedAt().
eventSalt string Custom event ID for deduplication. Use your order ID to prevent duplicate tracking on retries. Defaults to auto-generated UUID.
tax number Total tax of the order, in the transaction currency, >= 0. Used by profit tracking instead of the workspace's default VAT rate.
shipping number Shipping the buyer paid, tax included, >= 0. This is revenue, not your shipping cost.
taxesIncluded boolean Whether revenue and the product prices include tax. Absent means true.
costs object Your costs for this order: shipping (what you pay the carrier), paymentFee and handling, each a Money Object in the transaction currency, >= 0. Kept only with the Secret Key, removed from a Public Key request, never forwarded to ad platforms. See Profit and POAS.

Server-Enriched Fields

The following fields are automatically added by the server:

Field Description
ip Client IP address (extracted from X-Forwarded-For, CF-Connecting-IP, X-Client-IP, etc.)
userAgent Browser User-Agent string (from User-Agent header or X-Client-User-Agent)
timestamp Server timestamp (ISO 8601 format)

Examples

Server-Side (PHP SDK - Recommended)

<?php
use AxiTrace\AxiTrace;

$axitrace = AxiTrace::init('sk_live_YOUR_SECRET_KEY');

// Read SDK cookies - CRITICAL for linking purchase to browsing session
$visitorId = $_COOKIE['vt_vid'] ?? null;
$sessionId = $_COOKIE['vt_sid'] ?? null;

if ($visitorId) {
    $axitrace->setClientId($visitorId);
}
if ($sessionId) {
    $axitrace->setSessionId($sessionId);
}

// Forward client context for Facebook CAPI matching
$axitrace->setClientIp($_SERVER['REMOTE_ADDR']);
$axitrace->setClientUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '');
$axitrace->setPageUrl('https://yoursite.com/order-confirmation');

// Build products array
$products = [];
foreach ($order->getItems() as $item) {
    $products[] = [
        'sku' => $item->getSku(),
        'name' => $item->getName(),
        'finalUnitPrice' => [
            'amount' => $item->getFinalPrice(),
            'currency' => $order->getCurrency(),
        ],
        'quantity' => $item->getQuantity(),
    ];
}

// Track the transaction
// The PHP SDK automatically reads _fbp and _fbc cookies for Facebook CAPI matching
$response = $axitrace->transaction(
    $order->getId(),              // orderId
    $order->getTotal(),           // revenue (total with tax/shipping)
    $order->getSubtotal(),        // value (subtotal)
    $order->getCurrency(),        // currency
    strtoupper($paymentMethod),   // paymentMethod (CARD, STRIPE, PAYPAL, etc.)
    $products,                    // products array
    [                             // optional params
        'email' => $customer->getEmail(),  // Improves FB match quality by 41%
    ]
);

if ($response->isSuccess()) {
    // Transaction tracked: $response->getEventId()
}

PHP SDK 1.9.0 and later also send your product costs, tax and shipping for profit tracking (setTax(), setShipping(), setTaxesIncluded(), setCosts(), and unitCost / externalId per product). See Profit and POAS.

Basic Transaction (cURL)

curl -X POST https://stat.axitrace.com/v1/transaction \
  -u "sk_live_YOUR_SECRET_KEY:" \
  -H "Content-Type: application/json" \
  -d '{
    "orderId": "ORD-2024-001234",
    "source": "WEB_DESKTOP",
    "client": {
        "customId": "value-from-vt_vid-cookie",
        "email": "customer@example.com"
    },
    "sessionId": "value-from-vt_sid-cookie",
    "revenue": {
        "amount": 129.99,
        "currency": "USD"
    },
    "value": {
        "amount": 119.99,
        "currency": "USD"
    },
    "paymentInfo": {
        "method": "CARD"
    },
    "products": [
        {
            "sku": "WIDGET-001",
            "name": "Premium Widget",
            "finalUnitPrice": {
                "amount": 59.99,
                "currency": "USD"
            },
            "quantity": 2,
            "categories": ["Electronics", "Widgets"]
        }
    ]
  }'

Full Transaction with Facebook CAPI Data (cURL)

# Full transaction with all Facebook CAPI matching fields
curl -X POST https://stat.axitrace.com/v1/transaction \
  -u "sk_live_YOUR_SECRET_KEY:" \
  -H "Content-Type: application/json" \
  -H "X-Client-IP: 203.0.113.42" \
  -H "X-Client-User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)..." \
  -d '{
    "orderId": "ORD-2024-001234",
    "source": "WEB_MOBILE",
    "client": {
        "customId": "value-from-vt_vid-cookie",
        "email": "john@example.com",
        "phone": "+1234567890"
    },
    "sessionId": "value-from-vt_sid-cookie",
    "fbp": "fb.1.1558571054389.1098115397",
    "fbc": "fb.1.1554763741205.AbCdEfGhIjKlMnOpQr",
    "url": "https://yoursite.com/order-confirmation",
    "revenue": {
        "amount": 159.98,
        "currency": "USD"
    },
    "value": {
        "amount": 199.98,
        "currency": "USD"
    },
    "discountAmount": {
        "amount": 40.00,
        "currency": "USD"
    },
    "paymentInfo": {
        "method": "PAYPAL"
    },
    "metadata": {
        "coupon": "SUMMER20",
        "shippingMethod": "express"
    },
    "eventSalt": "ORD-2024-001234",
    "products": [
        {
            "sku": "WIDGET-001",
            "name": "Premium Widget",
            "finalUnitPrice": {
                "amount": 79.99,
                "currency": "USD"
            },
            "quantity": 2,
            "categories": ["Electronics", "Widgets"],
            "image": "https://example.com/images/widget.jpg",
            "url": "https://example.com/products/widget-001",
            "regularPrice": {
                "amount": 99.99,
                "currency": "USD"
            },
            "discountPercent": 20
        }
    ]
  }'

Server-Side (PHP - Raw HTTP)

<?php
$secretKey = getenv('AXITRACE_SECRET_KEY');

// Read AxiTrace SDK cookies - CRITICAL for linking purchase to browsing session
$visitorId = $_COOKIE['vt_vid'] ?? null;
$sessionId = $_COOKIE['vt_sid'] ?? null;

// Read Facebook cookies for CAPI matching (improves match quality)
$fbp = $_COOKIE['_fbp'] ?? null;
$fbc = $_COOKIE['_fbc'] ?? null;

// Get order data from your application
$order = getOrder($orderId);
$customer = $order->getCustomer();

// Build products array
$products = [];
foreach ($order->getItems() as $item) {
    $product = [
        'sku' => $item->getSku(),
        'name' => $item->getName(),
        'finalUnitPrice' => [
            'amount' => $item->getFinalPrice(),
            'currency' => $order->getCurrency(),
        ],
        'quantity' => $item->getQuantity(),
        'categories' => $item->getCategories(),
    ];

    if ($item->getImage()) {
        $product['image'] = $item->getImage();
    }
    if ($item->getRegularPrice() > $item->getFinalPrice()) {
        $product['regularPrice'] = [
            'amount' => $item->getRegularPrice(),
            'currency' => $order->getCurrency(),
        ];
    }

    $products[] = $product;
}

$data = [
    'orderId' => $order->getId(),
    'source' => $order->getSource(), // WEB_DESKTOP, WEB_MOBILE, etc.
    'client' => array_filter([
        'customId' => $visitorId,
        'id' => $customer->getId(),
        'email' => $customer->getEmail(),
        'phone' => $customer->getPhone(),
    ], fn($v) => $v !== null && $v !== ''),
    'sessionId' => $sessionId,
    'fbp' => $fbp,
    'fbc' => $fbc,
    'url' => 'https://yoursite.com/order-confirmation',
    'revenue' => [
        'amount' => $order->getTotal(),
        'currency' => $order->getCurrency(),
    ],
    'value' => [
        'amount' => $order->getSubtotal(),
        'currency' => $order->getCurrency(),
    ],
    'paymentInfo' => [
        'method' => strtoupper($order->getPaymentMethod()),
    ],
    'products' => $products,
    'eventSalt' => (string)$order->getId(), // Use order ID for idempotency
];

// Add discount if applied
if ($order->getDiscount() > 0) {
    $data['discountAmount'] = [
        'amount' => $order->getDiscount(),
        'currency' => $order->getCurrency(),
    ];
    $data['metadata'] = [
        'coupon' => $order->getCouponCode(),
    ];
}

// Remove null values from top level
$data = array_filter($data, fn($v) => $v !== null);

$ch = curl_init('https://stat.axitrace.com/v1/transaction');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_USERPWD => $secretKey . ':',
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'User-Agent: MyApp/1.0',
        // Forward real client IP and user agent for Facebook CAPI
        'X-Client-IP: ' . ($_SERVER['REMOTE_ADDR'] ?? ''),
        'X-Client-User-Agent: ' . ($_SERVER['HTTP_USER_AGENT'] ?? ''),
    ],
    CURLOPT_POSTFIELDS => json_encode($data)
]);

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

if ($httpCode === 200) {
    $result = json_decode($response, true);
    // Transaction tracked: $result['transactionId']
}

Server-Side (Python)

import os
import requests
from flask import request  # Example using Flask

secret_key = os.environ.get('AXITRACE_SECRET_KEY')

# Read AxiTrace SDK cookies - CRITICAL for linking purchase to browsing session
visitor_id = request.cookies.get('vt_vid')
session_id = request.cookies.get('vt_sid')

# Read Facebook cookies for CAPI matching
fbp = request.cookies.get('_fbp')
fbc = request.cookies.get('_fbc')

# Get order data from your application
order = get_order(order_id)
customer = order.customer

# Build products array
products = [{
    'sku': item.sku,
    'name': item.name,
    'finalUnitPrice': {
        'amount': float(item.final_price),
        'currency': order.currency,
    },
    'quantity': item.quantity,
    'categories': item.categories,
} for item in order.items]

# Build transaction data
data = {
    'orderId': str(order.id),
    'source': 'WEB_DESKTOP',
    'client': {
        'customId': visitor_id,
        'id': customer.id,
        'email': customer.email,
    },
    'sessionId': session_id,
    'fbp': fbp,
    'fbc': fbc,
    'url': f'https://yoursite.com/order/{order.id}/confirmation',
    'revenue': {
        'amount': float(order.total),
        'currency': order.currency,
    },
    'value': {
        'amount': float(order.subtotal),
        'currency': order.currency,
    },
    'paymentInfo': {
        'method': order.payment_method.upper(),
    },
    'products': products,
    'eventSalt': str(order.id),  # Use order ID for idempotency
}

# Add discount if applied
if order.discount > 0:
    data['discountAmount'] = {
        'amount': float(order.discount),
        'currency': order.currency,
    }
    data['metadata'] = {
        'coupon': order.coupon_code,
    }

# Remove None values
data = {k: v for k, v in data.items() if v is not None}

response = requests.post(
    'https://stat.axitrace.com/v1/transaction',
    auth=(secret_key, ''),
    headers={
        'Content-Type': 'application/json',
        'User-Agent': 'MyApp/1.0',
        'X-Client-IP': request.remote_addr,
        'X-Client-User-Agent': request.user_agent.string,
    },
    json=data
)

if response.status_code == 200:
    result = response.json()
    print(f"Transaction tracked: {result['transactionId']}")

Response

Success Response (200 OK)

{
    "success": true,
    "transactionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "orderId": "ORD-2024-001234",
    "productsCount": 2
}

Error Responses

Status Error Description
400 client must have at least one identifier (customId, id, uuid, or email) No customer identifier provided in the client object
400 orderId is required Missing order ID
400 paymentInfo.method is required Missing payment method
400 products array must contain at least one item Empty products array
400 invalid source: {value} Source must be WEB_DESKTOP, WEB_MOBILE, MOBILE_APP, POS, MOBILE, or DESKTOP
400 all monetary values must use the same currency Revenue and value currencies don't match
400 revenue.amount must be >= 0 Revenue is negative
400 value.amount must be >= 0 Value is negative
400 discountAmount.amount must be > 0 Discount amount is zero or negative (omit discountAmount if no discount)
400 discountAmount must use same currency as revenue Discount currency doesn't match transaction currency
400 product[N]: sku is required Product at index N is missing SKU
400 product[N]: name is required Product at index N is missing name
400 product[N]: finalUnitPrice.amount must be >= 0 Product price is negative
400 product[N]: currency must match transaction currency Product currency doesn't match transaction currency
400 product[N]: quantity must be > 0 Product quantity must be positive
400 costs.shipping.amount must be >= 0 A cost (tax, shipping, costs.*, products[N].unitCost) is negative
400 products[N].unitCost.currency: expected "EUR" (must match revenue.currency) A cost uses another currency than the transaction
401 unauthorized Invalid or missing Secret Key

E-commerce Integration Examples

WooCommerce (WordPress)

<?php
// Hook into WooCommerce order completion
add_action('woocommerce_payment_complete', function($order_id) {
    $order = wc_get_order($order_id);
    if (!$order) return;

    $secret_key = get_option('axitrace_secret_key');
    $visitor_id = $_COOKIE['vt_vid'] ?? null;
    $session_id = $_COOKIE['vt_sid'] ?? null;
    $fbp = $_COOKIE['_fbp'] ?? null;
    $fbc = $_COOKIE['_fbc'] ?? null;

    // Determine source based on user agent
    $source = wp_is_mobile() ? 'WEB_MOBILE' : 'WEB_DESKTOP';

    // Build products array
    $products = [];
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $products[] = [
            'sku' => $product->get_sku() ?: (string)$product->get_id(),
            'name' => $item->get_name(),
            'finalUnitPrice' => [
                'amount' => (float)$order->get_item_total($item, false),
                'currency' => $order->get_currency(),
            ],
            'quantity' => $item->get_quantity(),
            'categories' => wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']),
            'image' => wp_get_attachment_url($product->get_image_id()),
            'url' => get_permalink($product->get_id()),
        ];
    }

    $data = [
        'orderId' => (string)$order->get_id(),
        'source' => $source,
        'client' => array_filter([
            'customId' => $visitor_id,
            'id' => $order->get_customer_id(),
            'email' => $order->get_billing_email(),
            'phone' => $order->get_billing_phone(),
        ], fn($v) => !empty($v)),
        'sessionId' => $session_id,
        'fbp' => $fbp,
        'fbc' => $fbc,
        'url' => $order->get_checkout_order_received_url(),
        'revenue' => [
            'amount' => (float)$order->get_total(),
            'currency' => $order->get_currency(),
        ],
        'value' => [
            'amount' => (float)$order->get_subtotal(),
            'currency' => $order->get_currency(),
        ],
        'paymentInfo' => [
            'method' => strtoupper($order->get_payment_method()),
        ],
        'products' => $products,
        'eventSalt' => 'woo-' . $order->get_id(), // Idempotency
    ];

    // Add discount if applied
    if ($order->get_discount_total() > 0) {
        $data['discountAmount'] = [
            'amount' => (float)$order->get_discount_total(),
            'currency' => $order->get_currency(),
        ];
        $coupons = $order->get_coupon_codes();
        if (!empty($coupons)) {
            $data['metadata'] = ['coupon' => implode(',', $coupons)];
        }
    }

    // Remove null values
    $data = array_filter($data, fn($v) => $v !== null);

    wp_remote_post('https://stat.axitrace.com/v1/transaction', [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode($secret_key . ':'),
            'Content-Type' => 'application/json',
            'X-Client-IP' => $_SERVER['REMOTE_ADDR'] ?? '',
            'X-Client-User-Agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        ],
        'body' => json_encode($data),
        'timeout' => 10,
    ]);
});

Stripe Webhook Handler

<?php
// Stripe webhook handler for checkout.session.completed
$payload = @file_get_contents('php://input');
$event = \Stripe\Event::constructFrom(json_decode($payload, true));

if ($event->type === 'checkout.session.completed') {
    $session = $event->data->object;

    // Get line items from Stripe
    $lineItems = \Stripe\Checkout\Session::allLineItems($session->id);

    $products = [];
    foreach ($lineItems->data as $item) {
        $products[] = [
            'sku' => $item->price->product,
            'name' => $item->description,
            'finalUnitPrice' => [
                'amount' => $item->amount_total / 100 / $item->quantity,
                'currency' => strtoupper($session->currency),
            ],
            'quantity' => $item->quantity,
        ];
    }

    $data = [
        'orderId' => $session->id,
        'source' => 'WEB_DESKTOP',
        'client' => [
            // Pass vt_vid as client_reference_id when creating Stripe session
            'customId' => $session->client_reference_id,
            'email' => $session->customer_details->email,
        ],
        'revenue' => [
            'amount' => $session->amount_total / 100,
            'currency' => strtoupper($session->currency),
        ],
        'value' => [
            'amount' => $session->amount_subtotal / 100,
            'currency' => strtoupper($session->currency),
        ],
        'paymentInfo' => [
            'method' => 'STRIPE',
        ],
        'products' => $products,
        'eventSalt' => $session->id, // Idempotent on retry
    ];

    // Track to AxiTrace (same curl code pattern as above)
}
Stripe Tip: Pass vt_vid Cookie

When creating a Stripe Checkout session, pass the user's vt_vid cookie as client_reference_id. This lets your webhook handler link the purchase back to the user's browsing session, even though cookies aren't available in webhook requests.

$session = \Stripe\Checkout\Session::create([
    // ...
    'client_reference_id' => $_COOKIE['vt_vid'] ?? null,
]);

Best Practices

  • Always include email - This is the single most impactful field for Facebook CAPI match quality (up to +41%). At checkout, you always have the customer's email.
  • Include sessionId - Use the vt_sid cookie to link the transaction to the browsing session. The PHP SDK does this automatically.
  • Include fbp/fbc cookies - Read _fbp and _fbc cookies and pass them for Facebook CAPI matching. The PHP SDK reads these automatically.
  • Use eventSalt with order ID - Set eventSalt to your order ID for idempotency. If your webhook fires twice, AxiTrace will deduplicate.
  • Track at order creation - For best attribution, track when the order is created in your system (while cookies are still available), not from an async webhook where cookies may not be accessible.
  • Use consistent SKUs - Match sku with product identifiers used in product.view and product.addToCart for full funnel analysis.
  • Set correct source - Use WEB_MOBILE vs WEB_DESKTOP based on the user agent to segment mobile vs desktop conversions.
  • Forward client IP and User-Agent - Send the real client's IP and User-Agent via X-Client-IP and X-Client-User-Agent headers. This improves Facebook CAPI matching.
Revenue Attribution

Transaction events are used for marketing attribution analysis. AxiTrace links purchases back to:

  • Original traffic source (UTM parameters, ad campaigns)
  • User's browsing journey (products viewed, added to cart)
  • Time from first visit to purchase
  • Conversion rates by source, campaign, and product