PHP code example of onetracepro / onetrace-php

1. Go to this page and download the library: Download onetracepro/onetrace-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

onetracepro / onetrace-php example snippets


use OneTrace\Client;

$onetrace = new Client('https://cdp.onetrace.pro', [
    'write_key' => getenv('ONETRACE_WRITE_KEY'),       // cdp_wk_…: recommendations, widgets, search
    'secret_key' => getenv('ONETRACE_SECRET_KEY'),     // cdp_sk_…: events and everything else, server only
    'identity_key' => getenv('ONETRACE_IDENTITY_KEY'), // cdp_ik_…: signs user ids for the tracker, server only
]);

$onetrace->events()->track([
    'userId' => (string) $user->id,
    'event' => 'order_completed',
    'messageId' => 'order-' . $order->number, // a repeat within 24 hours is ignored
    'properties' => [
        'order_id' => $order->number,
        'amount' => $order->total,
        'products' => [['product_id' => 'SKU-1', 'quantity' => 2, 'price' => 4990]],
    ],
]);

$events = $onetrace->events();

// A visitor became a known customer: link the browser's anonymous id to the user.
$events->identify([
    'userId' => (string) $user->id,
    'anonymousId' => $_COOKIE['cdp_aid'] ?? null, // set by the website tracker
    'traits' => ['email' => $user->email, 'phone' => '+4915112345678', 'first_name' => 'Anna'],
]);

$events->track(['userId' => '42', 'event' => 'subscription_renewed', 'properties' => ['plan' => 'pro']]);
$events->page(['anonymousId' => $anonymousId, 'name' => 'Checkout', 'properties' => ['url' => $url]]);
$events->alias(['previousId' => $oldUserId, 'userId' => '42']);

$onetrace->events()->batch([
    ['type' => 'identify', 'userId' => '42', 'traits' => ['plan' => 'pro']],
    ['type' => 'track', 'userId' => '42', 'event' => 'plan_changed'],
]);

$buffer = $onetrace->events()->buffer(100); // sends every 100 events

foreach ($orders as $order) {
    $buffer->track(['userId' => $order->userId, 'event' => 'order_shipped', 'properties' => ['order_id' => $order->number]]);
}

$buffer->flush(); // the rest; also sent automatically when the buffer is destroyed

$hash = $onetrace->userHash($user->id); // HMAC-SHA256 of the id with the identity key, hex; null without identity_key

use OneTrace\Identity;

$profile = $onetrace->profiles()->get('email', '[email protected]');   // traits, identities, first/last seen
$onetrace->profiles()->updateConsent('user_id', '42', 'email', 'unsubscribed', 'news');

foreach ($onetrace->profiles()->iterateEvents('user_id', '42', ['name' => 'order_completed']) as $event) {
    // newest first, all pages
}

$link = $onetrace->profiles()->telegramLink(Identity::userId(42)); // ['url' => 'https://t.me/…', …]
$onetrace->profiles()->delete('user_id', '42'); // GDPR erasure

$preferences = $onetrace->profiles()->preferences('user_id', '42', 'en');
// channels: [['key' => 'email', 'blocked' => false]], topics: [['key' => 'news', 'name' => 'News', 'channels' => ['email' => true]]],
// frequency: null|weekly|monthly, paused_until, preferences_url

$onetrace->profiles()->updatePreferences('user_id', '42', [
    'topics' => ['news' => ['email' => false]],   // only the given topics and channels change
    'frequency' => 'weekly',                       // at most one marketing message a week across channels
    'paused_until' => new DateTimeImmutable('+30 days'),
]);
$onetrace->profiles()->updatePreferences('user_id', '42', ['unsubscribe_all' => true]);

$topics = $onetrace->profiles()->subscriptionTopics(); // names and descriptions in the project languages

$onetrace->products()->upsert(
    [['id' => 'SKU-1', 'name' => 'Sneakers', 'price' => 4990, 'currency' => 'EUR', 'url' => 'https://shop.example/sku-1',
      'image' => 'https://shop.example/sku-1.jpg', 'category_ids' => ['shoes'], 'available' => true]],
    [['id' => 'shoes', 'name' => 'Shoes']]
);
$onetrace->products()->delete(['SKU-2']);

$recommendations = $onetrace->recommendations()->get('viewed_with', ['item' => 'SKU-1', 'limit' => 4]);
// personal, popular, trending, viewed_with, bought_with, similar, recently_viewed

use OneTrace\Commerce\CatalogItem;

$item = CatalogItem::make('SKU-1', 'Кроссовки', 'https://shop.example/sku-1', null, 4990, 'EUR', true, ['shoes'], null, null, [], 12, '<p>Лёгкие беговые кроссовки</p>'); // 12 in stock
$item = CatalogItem::translate($item, 'en', 'Sneakers', 'https://shop.example/en/sku-1', [], '<p>Light running sneakers</p>');
$category = CatalogItem::translateCategory(CatalogItem::category('shoes', 'Обувь'), 'en', 'Shoes');
$onetrace->products()->upsert([$item], [$category]);

$onetrace->recommendations()->get('popular', ['language' => 'en']);

$result = $onetrace->search()->products('linen dress', [
    'per_page' => 24, 'sort' => 'relevance', 'brand' => ['Contoso'], 'anonymousId' => $visitorId,
]);
// $result['items'], $result['total'], $result['facets'] (categories, brands, price, attributes), $result['relaxed'], $result['personalized']
// $result['corrected'] — results for the corrected query, $result['suggestion'] — "did you mean"
// $result['filters'] — price, brand and characteristics recognized in the text and applied ("red dress under 50")
// $result['learned'], $result['semantic'] — order learned from clicks and purchases, products found by meaning

$onetrace->search()->products('red dress under 50', ['correct' => false, 'ignore' => ['price'], 'attr' => ['season' => 'winter']]);

// AI search: the query in plain words → catalog filters; waits up to 2.5 s for the parse, ai: null — use products()
$ai = $onetrace->search()->ai('warm coat for winter under 150, not black', ['anonymousId' => $visitorId, 'per_page' => 24]);
$result = $ai['ai'] !== null ? $ai : $onetrace->search()->products('warm coat for winter under 150, not black', ['anonymousId' => $visitorId]);

$hints = $onetrace->search()->suggest('lin'); // products, categories, popular queries
$widget = $onetrace->search()->widget('de'); // search widget settings of Site → Search: enabled, cart_url, texts

$segment = $onetrace->segments()->create(['name' => 'VIP', 'type' => 'static']);
$onetrace->segments()->addMembers($segment['id'], [Identity::email('[email protected]'), Identity::userId(42)]);
$onetrace->segments()->membership($segment['id'], 'user_id', '42'); // ['member' => true, …]

// Start a journey with the "API" trigger for one customer; the key enrolls only once.
$onetrace->journeys()->enroll(7, Identity::userId(42), ['order_id' => 'A-1001'], 'order-A-1001');
$onetrace->journeys()->pause(7);

$campaign = $onetrace->campaigns()->get(3);
$onetrace->campaigns()->schedule(3);
$report = $onetrace->campaigns()->report(3);

$funnel = $onetrace->analytics()->funnel([
    'steps' => [['event' => 'product_viewed'], ['event' => 'add_to_cart'], ['event' => 'order_completed']],
    'window' => ['amount' => 7, 'unit' => 'day'],
    'period' => ['last' => 30],
]);
$funnel['steps'][2]['from_start']; // conversion from the first step

$revenue = $onetrace->analytics()->revenue(['interval' => 'week', 'period' => ['last' => 90]]);
$sources = $onetrace->analytics()->traffic(['dimension' => 'source_medium']);
$credit = $onetrace->analytics()->attribution(['window_days' => 7, 'model' => 'linear']);

// Saved reports and dashboards
$report = $onetrace->analytics()->createSavedReport(['name' => 'Purchase funnel', 'type' => 'funnel', 'definition' => $funnel['definition']]);
$lastWeek = $onetrace->analytics()->runSavedReport($report['id'], ['last' => 7]);
$onetrace->analytics()->createDashboard(['name' => 'Weekly', 'layout' => [['report_id' => $report['id'], 'size' => 'full']]]);

$customer = Identity::email('[email protected]');

// Checkout: how many points the cart can take, then hold them for 30 minutes
$offer = $onetrace->loyalty()->calculate($customer, 1500.0);   // balance, max_points, max_discount, earn_points
$hold = $onetrace->loyalty()->hold($customer, $offer['max_points'], 'cart-17', 1500.0);
// … apply $hold['discount'] to the order, then
$onetrace->loyalty()->confirm($hold['id'], 'A-1001');          // or cancel($hold['id']) if the customer leaves

$account = $onetrace->loyalty()->account('email', '[email protected]'); // balance, pending, tier, expiring
$onetrace->loyalty()->adjust($customer, 500, 'Compensation for a late delivery');

$onetrace->loyalty()->refer(Identity::userId('42'), $_COOKIE['cdp_ref']); // friend reward at once; 422 for own code or an existing customer

// A store plugin: create coupons for new and changed codes of a pool, keep the cursor
$codes = $onetrace->promo()->iterateCodes('welcome', $savedCursor);
foreach ($codes as $code) {
    // create or update the coupon $code['code'] (status, expires_at)
}
$savedCursor = $codes->getReturn();

$code = $onetrace->promo()->issue('welcome', Identity::email('[email protected]')); // the same code until it is used
$onetrace->promo()->check('WEL7KQ2XM');                                            // pool, status, active, uses
$onetrace->promo()->generate('welcome', 5000);                                     // or import('welcome', ['SHOP-1', …])

$message = $onetrace->messages()->send(Identity::email('[email protected]'), 12, [
    'traits' => ['first_name' => 'Anna'],    // written to the profile, {{ traits.first_name }}
    'data' => ['order_id' => 'A-1001'],      // only for this message, {{ context.data.order_id }}
], 'order-A-1001');                          // the same key returns the same message
$onetrace->messages()->get($message['id']); // status: queued, sent, delivered, failed, skipped …

// A cascade (plans with cascades): WhatsApp, and email if it is not delivered in 2 minutes
$cascade = $onetrace->messages()->sendCascade(Identity::phone('+4915112345678'), [
    ['integration_id' => 3, 'template_id' => 21, 'wait_for' => 'delivered', 'timeout' => ['amount' => 2, 'unit' => 'minute']],
    ['integration_id' => 4, 'template_id' => 22],
], ['data' => ['code' => '482913']]);
$onetrace->messages()->cascade($cascade['id']); // running, reached (reached_channel) or failed

use OneTrace\Resource\Emails;

$settings = $onetrace->emails()->settings(); // cache it for a few minutes

try {
    switch (Emails::route($settings, 'order_shipped')) {
        case Emails::TEMPLATE: // OneTrace builds the email in the customer's language
            $onetrace->emails()->send([
                'to' => '[email protected]',
                'kind' => 'order_shipped',
                'language' => 'de',
                'order' => $order->emailData(['number' => '1001', 'url' => $orderUrl, 'carrier' => 'DHL', 'tracking_number' => 'JD0001', 'tracking_url' => $trackingUrl]),
            ], 'order-1001-shipped');
            break;
        case Emails::RELAY: // the shop's own email as is
            $onetrace->emails()->send([
                'to' => '[email protected]',
                'kind' => 'order_shipped',
                'subject' => $subject,
                'html' => $html,
                'attachments' => [Emails::attachment('invoice-1001.pdf', 'application/pdf', $pdf)],
            ], 'order-1001-shipped');
            break;
        default:
            $mailer->send($nativeEmail);
    }
} catch (\OneTrace\Exception\OneTraceException $e) {
    $mailer->send($nativeEmail); // not accepted or unavailable: the shop sends it itself
}

// Conversations waiting for an answer; a customer's conversations — 'profile' => Identity::email(…)
foreach ($onetrace->chats()->iterateConversations(['status' => 'open', 'channel' => 'web']) as $conversation) {
    $full = $onetrace->chats()->conversation($conversation['id']); // with the latest messages, oldest first
    $last = end($full['messages']);                                  // author: visitor, operator, system

    $onetrace->chats()->reply($conversation['id'], 'Your order ships today.', 'answer-' . $last['id']);
}

$onetrace->chats()->close($conversation['id']); // the website visitor is asked to rate the conversation

use OneTrace\StoreMcp\{Context, CustomerTokens, Server, ToolError, Verification};

$tokens = new CustomerTokens(getenv('ONETRACE_CUSTOMER_TOKEN_SECRET'));   // 32+ random characters, only the store knows it
$verification = new Verification(
    $codeStore,                                                         // OneTrace\StoreMcp\CodeStore: your cache
    fn (string $contact, ?string $order): ?string => findCustomerId($contact, $order),
    fn (string $customerId, string $contact, string $code, string $channel) => sendCode($contact, $code, $channel),
);

$server = new Server(getenv('ONETRACE_STORE_MCP_KEY'), $tokens, [
    'store_get_customer' => fn (array $args, Context $ctx): array => customerInfo($ctx->customerId),
    'store_get_order' => function (array $args, Context $ctx): array {
        $order = findOrder($args['order'], $ctx->customerId);

        if ($order === null) {
            throw new ToolError(ToolError::NOT_FOUND, 'No such order.');
        }

        return ['order' => $order->number, 'status' => $order->status, 'status_label' => $order->label($ctx->language)];
    },
    'store_cancel_order' => fn (array $args, Context $ctx): array => cancelOrder($args['order'], $ctx->customerId, $ctx->idempotencyKey),
], ['name' => 'my-shop', 'enabled' => $toolsAllowedByTheOwner, 'verification' => $verification]);

$server->serve();                                         // plain PHP; in a framework — $server->handle($method, $headers, $body)
$onetrace->chats()->connectStoreMcp('https://shop.example.com/onetrace/mcp', getenv('ONETRACE_STORE_MCP_KEY')); // chats.manage

use OneTrace\StoreMcp\{Context, Server, ToolError};

$server = new Server(getenv('ONETRACE_STORE_MCP_KEY'), $tokens, [
    // ... the v1 tools ...
    'store_quote_order' => function (array $args, Context $ctx): array {
        // $args['items']: [['product_id' => 'sku-1', 'quantity' => 2], ...] — checked: 1–20 lines, 1–99 each
        // $args['shipping']: ['country' => 'DE', 'city' => 'Berlin', 'postcode' => '10115'] or [] — given fields only
        $cart = priceCart($args['items'], $args['shipping'], $args['shipping_method']);

        return [
            'items' => $cart->lines(),                // [{ product_id, name, quantity, price, total }]
            'unavailable' => $cart->unavailableIds(), // product ids that cannot be ordered
            'subtotal' => ['amount' => $cart->subtotal, 'currency' => 'EUR'],
            'discount' => ['amount' => $cart->discount, 'currency' => 'EUR'],
            'shipping_methods' => $cart->shippingMethods(), // [{ id, name, price, min_days, max_days }]
            'shipping_method' => $cart->shippingMethod,
            'shipping_price' => ['amount' => $cart->shippingPrice, 'currency' => 'EUR'],
            'total' => ['amount' => $cart->total, 'currency' => 'EUR'],
            'payment_methods' => [['id' => 'card', 'name' => 'Card on the website']],
        ];
    },
    'store_create_order' => function (array $args, Context $ctx): array {
        // A customer ($ctx->customerId) or a guest ($ctx->guestEmail() / $ctx->guestPhone()); prices are checked again
        $order = placeOrder($ctx->customerId, $ctx->guestContact, $args['items'], $args['shipping'], $args['shipping_method'], $args['payment_method'], $args['comment'], [
            'source' => $ctx->source,       // "assistant"
            'assistant' => $ctx->assistant, // chatgpt, claude, perplexity, gemini, copilot or other
        ]);

        if ($order->priceChanged) {
            throw new ToolError(ToolError::INVALID_INPUT, 'The price of a product has changed: quote the order again.');
        }

        return ['order' => $order->number, 'status' => 'pending', 'total' => $order->total(), 'payment_status' => 'pending', 'payment_url' => $order->paymentUrl()];
    },
], ['name' => 'my-shop', 'enabled' => $toolsAllowedByTheOwner, 'verification' => $verification, 'idempotency' => $codeStore]);

$template = $onetrace->templates()->create([
    'name' => 'Welcome',
    'channel_key' => 'email',
    'language' => 'en',
    'content' => ['subject' => 'Hello {{ traits.first_name }}', 'html' => '<p>Welcome!</p>'],
    'translations' => ['de' => ['subject' => 'Hallo {{ traits.first_name }}', 'html' => '<p>Willkommen!</p>']],
]);
$onetrace->templates()->update($template['id'], ['name' => 'Welcome email']); // versions are kept

use OneTrace\Commerce\{CatalogItem, Customer, LineItem, Messages, Order, Retry};

$messages = new Messages('myshop', 'https://shop.example.com');
$customer = (new Customer((string) $user->id, $_COOKIE['cdp_aid'] ?? null))
    ->email($user->email)->phone($user->phone)->name($user->first_name, $user->last_name)->country('DE')->language('de');
$order = (new Order('A-1001', 109.90, 'EUR', $placedAt, $customer, [new LineItem('SKU-1', 'Sneakers', 49.95, 2)]))
    ->with(['shipping' => 10, 'coupon' => 'AUTUMN']);

$onetrace->events()->batch(array_filter([
    $messages->identify($customer, [Messages::subscribed('email')]), // consents need the secret key
    $messages->orderCompleted($order),                               // the same order gives the same messageId
]));

$onetrace->products()->upsert([CatalogItem::make('SKU-1', 'Sneakers', $url, $image, 49.95, 'EUR', true, ['shoes'])]);

$page = $onetrace->segments()->list(['limit' => 50]);
$next = $onetrace->segments()->list(['cursor' => $page->getNextCursor()]);

foreach ($onetrace->segments()->iterateMembers(12, ['limit' => 200]) as $member) {
    // …
}

try {
    $onetrace->segments()->create(['name' => '']);
} catch (OneTrace\Exception\ValidationException $e) {
    $e->getErrors(); // ['name' => ['The name field is 

$onetrace->segments()->create(['name' => 'VIP', 'type' => 'static'], 'segment-vip');

$factory = new Nyholm\Psr7\Factory\Psr17Factory();

$onetrace = new OneTrace\Client('https://cdp.onetrace.pro', [
    'secret_key' => getenv('ONETRACE_SECRET_KEY'),
    'http_client' => new GuzzleHttp\Client(['timeout' => 10]),
    'request_factory' => $factory,
    'stream_factory' => $factory,
]);
bash
composer 
html
<script>cdp.identify(<?= json_encode((string) $user->id)