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']);
$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
$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);
$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]);