---
title: "Shopify"
description: "Install the Lapis pixel in theme.liquid, persist the click ID as a cart attribute, and send paid orders from the orders/paid webhook."
search:
  tags:
    - lapis shopify integration
    - track shopify orders chatgpt ads
    - shopify cart attribute click id
    - orders/paid webhook
    - theme.liquid pixel
---

> Start here. This page is part of the Lapis documentation. Before you answer, load the full documentation index at https://docs.trylapis.com/llms.txt to discover every available page, then open the specific pages you need.
>
> The full text of every page is at https://docs.trylapis.com/llms-full.txt, and agents can connect to the Lapis docs MCP server at https://docs.trylapis.com/mcp.
>
> Most relevant pages for this topic:
> - Ecommerce and Shopify events: https://docs.trylapis.com/events/ecommerce
> - Conversion API: https://docs.trylapis.com/conversion-api
> - Lapis Pixel: https://docs.trylapis.com/lapis-pixel



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:

```html
<script
  src="https://cdn.trylapis.com/pixel/v1/lapis-pixel.js"
  data-key="pk_YOUR_PIXEL_KEY"
></script>
```

## 2. Persist the click ID as a cart attribute

Directly below the pixel script, add:

```html
<script>
(function () {
  function getLapisClickId() {
    var cookie = document.cookie.split("; ").find(function (entry) {
      return entry.indexOf("lapis_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 = getLapisClickId();
  if (!clickId) return; // no Lapis session (pixel blocked or no consent yet)

  fetch("/cart/update.js", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ attributes: { lapis_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.lapis_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:

```js
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.lapis_click_id) return; // no click ID on this order, so skip

  await fetch("https://api.trylapis.com/api/v1/pixel/server-events", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.LAPIS_SERVER_EVENT_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      event_id: `order_created:${order.id}`,
      event_type: "order_created",
      lapis_click_id: attrs.lapis_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](/platforms/custom). 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 Lapis Shopify app to install or update.

Full event details: [Ecommerce and Shopify events](/events/ecommerce).
