Skip to content
Kindle AI
Esc
↑↓navigate↵open⌘Jpreview
On this page

Shopify

Install the Kindle AI pixel in theme.liquid, persist the click ID as a cart attribute, and send paid orders from the orders/paid webhook.

Shopify locks down checkout, so the reliable pattern is: cookie, then cart attribute, then order note attribute, then webhook. Shopify carries cart attributes onto the order automatically, so you need no checkout customization.

1. Install the pixel

In Shopify admin, go to Online Store → Themes → ⋯ → Edit code → layout/theme.liquid. Add this before the closing </body> tag:

<script
  src="/media/cdn/pixel/v1/kindle-ai-pixel.js"
  data-key="pk_YOUR_PIXEL_KEY"
></script>

2. Persist the click ID as a cart attribute

Directly below the pixel script, add:

<script>
(function () {
  function getKindle AIClickId() {
    var cookie = document.cookie.split("; ").find(function (entry) {
      return entry.indexOf("kindle-ai_sid=") === 0;
    });
    if (!cookie) return null;
    try {
      var session = JSON.parse(
        decodeURIComponent(cookie.split("=").slice(1).join("="))
      );
      return session.sid || null;
    } catch (e) { return null; }
  }

  var clickId = getKindle AIClickId();
  if (!clickId) return; // no Kindle AI session (pixel blocked or no consent yet)

  fetch("/cart/update.js", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ attributes: { kindle-ai_click_id: clickId } }),
  }).catch(function () {});
})();
</script>

This is idempotent, so it is safe to run on every page view. The attribute lands on the order as note_attributes.kindle-ai_click_id.

3. Send orders from the webhook

Create an orders/paid webhook that points at your backend (Settings → Notifications → Webhooks, or via the Admin API). The URL is public, so anyone can POST to it: check Shopify’s signature before you trust the body. Store the signing secret as SHOPIFY_WEBHOOK_SECRET. For webhooks created in the admin it is the key shown on the Webhooks page. For webhooks your app registers, it is the app’s client secret. Then:

const crypto = require("node:crypto");
const express = require("express");

// Shopify signs the exact bytes it sends, so keep them for the HMAC check.
const shopifyJson = express.json({
  limit: "1mb",
  verify: (req, _res, buf) => {
    req.rawBody = buf;
  },
});

function hasValidShopifyHmac(req) {
  const secret = process.env.SHOPIFY_WEBHOOK_SECRET;
  const header = req.get("X-Shopify-Hmac-Sha256");
  if (!secret || !header || !Buffer.isBuffer(req.rawBody)) return false;
  const expected = crypto.createHmac("sha256", secret).update(req.rawBody).digest();
  const received = Buffer.from(header, "base64");
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

// POST /webhooks/shopify/orders-paid
app.post("/webhooks/shopify/orders-paid", shopifyJson, async (req, res) => {
  if (!hasValidShopifyHmac(req)) return res.sendStatus(401);

  // Read the order from the bytes that were verified.
  const order = JSON.parse(req.rawBody.toString("utf8"));
  res.sendStatus(200); // ack Shopify first, because it retries slow responses

  // Only fully paid, uncancelled orders are revenue. Pending, authorized,
  // partially paid, voided, and refunded orders must never send order_created.
  if (order.financial_status !== "paid" || order.cancelled_at) return;

  const attrs = Object.fromEntries(
    (order.note_attributes || []).map((a) => [a.name, a.value])
  );
  if (!attrs.kindle-ai_click_id) return; // no click ID on this order, so skip

  await fetch("https://api.trykindle.app/api/v1/pixel/server-events", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.KINDLE AI_SERVER_EVENT_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      event_id: `order_created:${order.id}`,
      event_type: "order_created",
      kindle-ai_click_id: attrs.kindle-ai_click_id,
      value: parseFloat(order.total_price),
      currency: order.currency || "USD",
      properties: { order_number: String(order.order_number) },
    }),
  });
});

Tip: Shopify retries webhooks aggressively. Keying event_id to order.id makes every retry deduplicate, so you never double-count.

Warning: Register this route before any app-wide express.json(). A body parser that runs first consumes the request without keeping the raw bytes, so every webhook fails the signature check with 401. Never skip the check: without it, anyone who finds the URL can report fake orders with your Conversion API key.

Warning: do not send order_created from orders/create. Shopify creates the order before money is captured for manual payment methods, manual capture, and offsite payments the shopper abandons, so that webhook arrives with a pending or authorized financial status. Reporting those orders as revenue trains your ads on purchases that were never paid. Use checkout_started for earlier funnel steps.

Shopify-specific notes

  • Republish after editing the theme. Changes to theme.liquid on the live theme go out immediately, but if you edit an unpublished theme, the live one stays unchanged.
  • checkout_started: use the checkouts/create webhook with event_id: "checkout_started:" + checkout.token. The cart attribute is already on the checkout object. Protect that route the same way: parse it with shopifyJson, return 401 unless hasValidShopifyHmac(req) passes, and read the checkout from req.rawBody.
  • Shopify Plus and checkout extensibility: the cart-attribute pattern works unchanged. You do not need checkout.liquid access.
  • Headless Shopify (Hydrogen): treat it as custom code. Set the attribute via the Storefront API cartAttributesUpdate mutation instead of /cart/update.js.
  • No app required: this is intentionally a theme-code integration. There is no Kindle AI Shopify app to install or update.

Full event details: Ecommerce and Shopify events.

Was this page helpful?