Tracking purchases
Views and clicks tell you whether your recommendations are looked at. Purchases tell you what they bring in, and they are also the strongest signal to train the model. Every site sends the same event, purchase; only where it is sent from changes.
It’s optional. Without purchases, recommendations show up and the model learns from views and clicks. Purchases add the attributed revenue in the console, and the strongest signal for the model.
What makes a purchase count
A purchase counts in the console’s attributed revenue when it carries the recommendation_id of the click it came from, and a numeric properties.price. A purchase without these two fields is still recorded and used for training. Send one event per product of the order.
| Field | Status | Role |
|---|---|---|
item_id | Required | The product id, the same as in your LIKYLY catalog. |
user_id and/or session_id | Required | The signed-in customer, and/or the visitor's anonymous id (the same as for their views and clicks). |
recommendation_id | For attributed revenue | The one of the recommendation where the product was clicked. Without it, the purchase trains the model but is not attributed. |
properties.price | For attributed revenue | The unit price, as a number (49.9), not as text ("€49.90"). A line's revenue = price × quantity. |
quantity | Recommended | The number of units (1 by default). |
event_id | Recommended | A unique key, for example purchase_<order>_<product>: a purchase sent twice only counts once. |
properties.currency, .order_id | Optional | Kept as is with the event, for your own reconciliation. |
Where to send it from, depending on your site
The rule: the purchase is sent from where the order is confirmed. When that place is your code, your code sends it; on Shopify, payment happens on Shopify’s checkout, where the theme’s code doesn’t run: a pixel relays it.
| Site | To do |
|---|---|
| Magento / Adobe Commerce (wizard module) | AutomaticNothing to do: the module sends each purchase from the order confirmation page, with its price and the recommendation it came from. |
| WordPress / WooCommerce (LIKYLY plugin) | AutomaticNothing to do: the plugin keeps the recommendation on the cart line, then sends the purchase when the order moves to “processing” or “completed”. |
| Shopify theme (wizard section) | OptionalViews, impressions and clicks already go out from the theme section. To add add-to-carts and purchases (and revenue), paste the LIKYLY pixel once in the Shopify admin: payment happens on Shopify’s checkout, where theme code doesn’t run, and only a pixel sees these two events there. |
| Laravel (likyly/laravel package) | OptionalThree small steps in your code: keep the recommendation of the click, put it on the cart line, then send the purchase of each line when the order is confirmed. |
| Your code (SDK or REST API) | OptionalThree small steps in your code: keep the recommendation of the click, put it on the cart line, then send the purchase of each line when the order is confirmed. |
Shopify: the pixel
On Shopify, payment happens on Shopify’s checkout, where the theme’s code doesn’t run. The LIKYLY pixel listens there for add-to-carts and orders, finds the recommendation of the click (kept in the browser by the LIKYLY block) and sends one purchase per product, with its price. You paste it once, in the Shopify admin:
- Get the code: in the theme folder,
npx @likyly/wizard pixelshows it with your public key and copies it; or, in the console, Events → Send purchases → Shopify: the code is ready there, with your public key. - Shopify admin → Settings → Customer events → Add custom pixel; name it “LIKYLY”, paste the code, save, then Connect.
- Test from the store’s address, not from
127.0.0.1: the click in the block and the payment must happen on the same domain.
Show the pixel code
// LIKYLY - add to cart and purchases, so LIKYLY can count the revenue its recommendations bring.
// Shopify admin → Settings → Customer events → Add custom pixel → paste this code → Save → Connect.
// Same code as: npx @likyly/wizard pixel
const LIKYLY_KEY = "pk_YOUR_PUBLIC_KEY";
const LIKYLY_API = "https://api.likyly.com";
const numericId = (value) => (String(value ?? "").match(/(\d+)$/) || [])[1] || null;
async function stored(name) {
try {
return await browser.localStorage.getItem(name);
} catch (error) {
return null;
}
}
// The visitor: the same anonymous id as the LIKYLY blocks, and the customer when signed in.
async function who(orderId) {
const out = {};
const session = await stored("likyly_anonymous_id");
if (session) out.session_id = session;
const customer = numericId(init && init.data && init.data.customer && init.data.customer.id);
if (customer) out.user_id = customer;
if (!out.session_id && !out.user_id && orderId) out.session_id = "shopify_order_" + orderId;
return out;
}
// The recommendation this product was clicked in (30 days at most), from the LIKYLY block.
async function attribution(productId) {
try {
const entry = JSON.parse((await stored("likyly_rec")) || "{}")[productId];
if (Array.isArray(entry) && entry[0] && Date.now() - Number(entry[2] || 0) < 30 * 24 * 3600 * 1000) {
return entry[1] ? { recommendation_id: String(entry[0]), placement: String(entry[1]) } : { recommendation_id: String(entry[0]) };
}
} catch (error) {}
return {};
}
function send(events) {
if (!events.length) return;
fetch(LIKYLY_API + "/events/batch", {
method: "POST",
headers: { "Content-Type": "application/json", "X-API-Key": LIKYLY_KEY, "X-Likyly-Client": "likyly-console shopify-custom-pixel" },
body: JSON.stringify({ events: events }),
keepalive: true,
}).catch(() => {});
}
analytics.subscribe("product_added_to_cart", async (event) => {
const line = event.data && event.data.cartLine;
const productId = numericId(line && line.merchandise && line.merchandise.product && line.merchandise.product.id);
if (!productId) return;
const price = Number(line.merchandise.price && line.merchandise.price.amount);
send([Object.assign({
event_type: "add_to_cart",
item_id: productId,
quantity: Math.max(1, Number(line.quantity) || 1),
event_id: "cart_" + event.id,
occurred_at: event.timestamp,
}, await who(), await attribution(productId), Number.isFinite(price) ? { properties: { price: price, currency: line.merchandise.price.currencyCode } } : {})]);
});
// One purchase per product of the order, with its price: what LIKYLY's revenue adds up.
analytics.subscribe("checkout_completed", async (event) => {
const checkout = event.data && event.data.checkout;
if (!checkout) return;
const orderId = numericId(checkout.order && checkout.order.id) || String(checkout.token || event.id);
const byProduct = {};
for (const line of checkout.lineItems || []) {
const productId = numericId(line.variant && line.variant.product && line.variant.product.id);
if (!productId) continue;
const quantity = Math.max(1, Number(line.quantity) || 1);
const total = Number(line.finalLinePrice ? line.finalLinePrice.amount : Number(line.variant.price.amount) * quantity);
const sum = byProduct[productId] || { quantity: 0, revenue: 0 };
sum.quantity += quantity;
sum.revenue += Number.isFinite(total) ? total : 0;
byProduct[productId] = sum;
}
const buyer = await who(orderId);
const events = [];
for (const productId of Object.keys(byProduct)) {
const sum = byProduct[productId];
events.push(Object.assign({
event_type: "purchase",
item_id: productId,
quantity: sum.quantity,
// The same order seen twice (thank-you page reloaded) counts once.
event_id: "purchase_" + orderId + "_" + productId,
occurred_at: event.timestamp,
properties: {
order_id: orderId,
price: Math.round((sum.revenue / sum.quantity) * 100) / 100,
revenue: Math.round(sum.revenue * 100) / 100,
currency: checkout.currencyCode,
},
}, buyer, await attribution(productId)));
}
send(events);
});
Only ever put a public key (pk_…) in a pixel. Changing your public key? Paste the pixel again with the new one.
Your code: SDK or REST API, in three steps
1. On a click on a recommended product: keep its recommendation
Every LIKYLY answer has a recommendation id (
recommendationId). When the visitor clicks a product in a block, keep that id for that product:JavaScript, in your pages// On a click on a recommended product: keep its recommendation, per product. function rememberRecommendation(itemId, recommendationId) { const kept = JSON.parse(localStorage.getItem("likyly_clicks") || "{}"); kept[itemId] = [recommendationId, Date.now()]; localStorage.setItem("likyly_clicks", JSON.stringify(kept)); } // On add to cart: attach it to the line (cart metadata, then order metadata). function recommendationFor(itemId) { const entry = JSON.parse(localStorage.getItem("likyly_clicks") || "{}")[itemId]; return entry && Date.now() - entry[1] < 30 * 24 * 3600 * 1000 ? entry[0] : undefined; }2. On add to cart: put it on the cart line
Save the id with the line, like its quantity or price (
recommendationFor(itemId)above). It follows the line all the way to the order. That is what the WordPress plugin and the Magento module do.3. When the order is confirmed: one purchase per line
An order of 3 products is 3
purchaseevents. Each one carries the recommendation of its line, or nothing if that product was not found through a recommendation: it is then recorded, but not counted in the recommendations’ revenue. Most reliable: from your server, with the secret key, once the payment is confirmed.JavaScript / TypeScriptimport { Likyly } from "@likyly/sdk"; // On your server (secret key), once payment is confirmed. // On the confirmation page, the public key is enough. const likyly = new Likyly({ apiKey: process.env.LIKYLY_SECRET_KEY }); for (const line of order.lines) { await likyly.events.purchase({ itemId: line.productId, // the product's id in your LIKYLY catalog userId: order.customerId, // and/or sessionId for an anonymous visitor recommendationId: line.likylyRecommendationId, // the one from the click, kept with the cart line quantity: line.quantity, eventId: `purchase_${order.id}_${line.productId}`, // if replayed, the purchase counts once properties: { price: line.unitPrice, currency: order.currency, order_id: order.id }, }); }Pythonimport os from likyly import Likyly likyly = Likyly(api_key=os.environ["LIKYLY_SECRET_KEY"]) for line in order.lines: likyly.events.purchase( item_id=line.product_id, user_id=order.customer_id, # and/or session_id recommendation_id=line.likyly_recommendation_id, # the one from the click quantity=line.quantity, event_id=f"purchase_{order.id}_{line.product_id}", properties={"price": float(line.unit_price), "currency": order.currency, "order_id": order.id}, )PHPuse Likyly\LikylyClient; $likyly = new LikylyClient(apiKey: getenv('LIKYLY_SECRET_KEY')); foreach ($order->lines as $line) { $likyly->events()->purchase( itemId: $line->productId, userId: $order->customerId, // and/or sessionId recommendationId: $line->likylyRecommendationId, // the one from the click quantity: $line->quantity, properties: ['price' => (float) $line->unitPrice, 'currency' => $order->currency, 'order_id' => $order->id], eventId: "purchase_{$order->id}_{$line->productId}", ); }REST APIcurl -X POST https://api.likyly.com/events/purchase \ -H "X-API-Key: $LIKYLY_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "item_id": "SKU-42", "user_id": "customer_123", "recommendation_id": "rec_…", "quantity": 1, "event_id": "purchase_1001_SKU-42", "properties": { "price": 49.9, "currency": "EUR", "order_id": "1001" } }'
Payment with Stripe, PayPal…
Nothing to install at Stripe or PayPal. Payment happens on their side, then they notify your server that the payment went through (the “payment succeeded” notification your site already receives to confirm the order). That is when your server sends step 3, rather than from the return page, which the customer may close before it loads.
Checking
- Console → Performance: attributed purchases, revenue, conversion (the breakdown per placement and per product on Pro). A message shows up there if something is missing: clicks with no purchase received, purchases without their recommendation, or a price sent as text.
- Terminal:
npx @likyly/wizard impact, or/likyly-impactin Claude Code.