# Shopify order webhooks to WhatsApp, with replies written back

> Verify Shopify order webhooks, send WhatsApp utility templates only with opt-in, and write Confirm or Cancel taps back to orders with tagsAdd and orderCancel.

Published 2026-11-25. Z-API Omni team.

Subscribe to `orders/create` and `fulfillments/create`, verify `X-Shopify-Hmac-Sha256` over the raw body, and answer 200 inside five seconds. Then send a WhatsApp utility template, but only to customers who gave a WhatsApp opt-in. Shopify's SMS marketing consent is a different thing. When the customer taps a reply, record it with `tagsAdd`. Call `orderCancel` only for an order with nothing fulfilled.

The reply loop itself is in [WhatsApp order confirmation with Confirm and Cancel buttons](/academy/articles/whatsapp-order-confirmation-confirm-cancel-buttons/). That article covers payloads per button, matching on `context.id`, the conditional state change and what to do with silence. The WooCommerce version is in [WooCommerce order status on WhatsApp](/academy/articles/woocommerce-order-status-whatsapp-webhooks/). This page covers what Shopify adds: its webhook contract, the phone and consent fields, the token, and the write-back mutations.

## What Shopify sends and how often

Each delivery carries headers you should use. Shopify notes that HTTP/2 often lowercases them, so read them case-insensitively ([delivery structure, accessed 2026-11-25](https://shopify.dev/docs/apps/build/webhooks/delivery-structure)).

| Header | Use it for |
| --- | --- |
| `X-Shopify-Topic` | Routing, for example `orders/create` |
| `X-Shopify-Hmac-Sha256` | Base64 HMAC signature, HTTPS only |
| `X-Shopify-Shop-Domain` | The `myshopify.com` domain of the store |
| `X-Shopify-API-Version` | The version that serialized the payload |
| `X-Shopify-Webhook-Id` | "A unique composite key per delivery". Dedupe on this |
| `X-Shopify-Event-Id` | Shared by all deliveries from one merchant action |

The signature is an HMAC-SHA256 of the raw body, keyed with your app's client secret and encoded in base64 ([HTTPS webhooks, accessed 2026-11-25](https://shopify.dev/docs/apps/build/webhooks/subscribe/https)). Compute it before any JSON parser touches the body, and compare with a timing-safe function.

Shopify allows a one-second connection timeout and "a five-second timeout for the entire request". Only a 200 counts as success, and a 3XX is an error. After a failure, Shopify "retries 8 times over the next 4 hours". After 8 consecutive failures, a subscription created through the Admin API is deleted automatically, and the app's emergency developer address gets an email. A slow WhatsApp call inside the request can cost you the whole subscription.

Shopify's webhooks overview warns that "Your app might receive the same webhook more than once". It also says "Shopify doesn't guarantee ordering within a topic, or across different topics for the same resource" ([webhooks overview, accessed 2026-11-25](https://shopify.dev/docs/apps/build/webhooks)). Plan for a `fulfillments/create` that arrives before the `orders/create` for the same order. The same page says "Webhook delivery isn't always guaranteed", so run a reconciliation job that lists recent orders.

## The fields you read from the order

Shopify's `orders/create` reference sample shows where things live ([webhook topics, accessed 2026-11-25](https://shopify.dev/docs/api/webhooks/latest?reference=toml#list-topics-orders/create)). These are sample values from Shopify's reference, not a real order:

- `admin_graphql_api_id: "gid://shopify/Order/820982911946154508"` is the ID your mutations need.
- `name: "#9999"` is what the customer sees, and `total_price: "404.95"` with `currency: "USD"` is the total.
- `phone: null` and `customer.phone: null`, while `shipping_address.phone` and `billing_address.phone` read `"555-555-SHIP"`.
- `note_attributes: []`, `tags: "tag1, tag2"` and `fulfillment_status: null`.

The `fulfillments/create` sample has `name: "#9999.1"`, `order_id`, `status: "pending"` and `tracking_company: "UPS"`. Its only phone is `destination.phone`. Keep the number you stored from `orders/create` instead.

### Phone numbers are free text

That `"555-555-SHIP"` value is a reminder that Shopify phone fields accept text. Normalize to digits with a country code before you send, and skip numbers that don't survive normalization. The rules are in [WhatsApp phone number format](/academy/articles/whatsapp-phone-number-format-e164-normalization/).

Protected customer data can also hide the phone. Shopify puts "name, address, phone, or email fields" at level 2, requested one field at a time. Unapproved fields "will be redacted" ([protected customer data, accessed 2026-11-25](https://shopify.dev/docs/apps/launch/protected-customer-data)). For custom apps, levels 1 and 2 are "Always available", and public apps need review. Shopify's page doesn't say how redaction looks inside a webhook payload. Request the phone field and check a test delivery before you build on it.

<!-- TODO:test: whether order webhooks redact phone fields to null when the app lacks level 2 phone access -->

## WhatsApp consent is not Shopify's SMS consent

Shopify's `smsMarketingConsent` is "The record of when a customer consented to receive marketing material by SMS" ([CustomerSmsMarketingConsentState, accessed 2026-11-25](https://shopify.dev/docs/api/admin-graphql/latest/objects/CustomerSmsMarketingConsentState)). It is SMS marketing consent. It doesn't tell you the customer agreed to order updates on WhatsApp, so don't reuse it.

Shopify's checkout settings keep the two apart as well. The SMS marketing checkbox "can't be preselected at checkout", and "This marketing opt-in is a separate setting from order confirmation SMS notifications" ([checkout form options, accessed 2026-11-25](https://help.shopify.com/en/manual/checkout-settings/checkout-form-options)). Shopify's own SMS sends one order confirmation only "when there's no email address" ([SMS notifications, accessed 2026-11-25](https://help.shopify.com/en/manual/fulfillment/setup/notifications/sms-notifications)).

Shopify has no WhatsApp consent field, so add your own. A theme cart attribute such as `name="attributes[whatsapp_order_updates]"` is the simplest ([cart template, accessed 2026-11-25](https://shopify.dev/docs/storefronts/themes/architecture/templates/cart.md)). It should arrive in the order's `note_attributes`, which the code below reads, but that mapping is untested. A checkout UI extension is the other route, and there the Attributes API is deprecated in favor of cart metafields. The label must name the store and say "order updates on WhatsApp", per [WhatsApp opt-in rules](/academy/articles/whatsapp-opt-in-how-to-collect-consent/). If no opt-in is present, send nothing.

<!-- TODO:test: cart attribute whatsapp_order_updates arrives in orders/create note_attributes as {name, value} -->

## Get an Admin API token in 2026

Shopify stopped allowing new admin-created custom apps after 2026-01-01, so build the app in the Dev Dashboard ([changelog, posted 2025-10-30, accessed 2026-11-25](https://shopify.dev/changelog/posts/legacy-custom-apps-can-t-be-created-after-january-1-2026)). When the app and the store sit in the same organization, use the client credentials grant ([client credentials, accessed 2026-11-25](https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/client-credentials-grant)).

The grant is a form-encoded `POST https://{shop}.myshopify.com/admin/oauth/access_token` with `grant_type=client_credentials`, `client_id` and `client_secret`. The response carries `access_token`, `scope` and `expires_in: 86399`. "Tokens expire after 24 hours", so cache the token and refresh it before expiry. From 2026-12-01, new custom apps must use expiring offline tokens, and client-credential tokens already comply ([changelog, accessed 2026-11-25](https://shopify.dev/changelog/posts/expiring-offline-access-tokens-required-for-new-custom-apps-as-of-december-1-2026)).

## Two templates, both utility

Send the `order_confirm_v1` template from the order confirmation article on `orders/create`. Its Template Library match is `ORDER_CONFIRMATION`. On `fulfillments/create`, send a shipped notice whose library match is `SHIPMENT_CONFIRMATION`. Keep both free of discount codes and product suggestions, because Meta treats an order update with a promo as marketing ([template categorization, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)). The same split applies to other store messages: [abandoned checkout recovery](/academy/articles/whatsapp-abandoned-checkout-recovery-marketing-message/) and [back-in-stock alerts](/academy/articles/whatsapp-back-in-stock-alert-customer-asked/) are marketing, while [cash-on-delivery verification](/academy/articles/whatsapp-cash-on-delivery-order-verification/) and [return and refund updates](/academy/articles/whatsapp-return-refund-status-updates/) stay utility.

The tracking link goes in a URL button with a `{{1}}` suffix. Here it points at a tracking page on your own domain, keyed by the order ID. Suffix rules are in [template URL buttons with a dynamic suffix](/academy/articles/whatsapp-template-url-button-dynamic-suffix-utm/).

```bash
curl -X POST "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
  -H "Authorization: Bearer $WA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "name": "order_shipped_v1",
  "category": "UTILITY",
  "language": "en_US",
  "parameter_format": "NAMED",
  "components": [
    {
      "type": "BODY",
      "text": "Order {{order_number}} has shipped with {{carrier}}. Tap below to follow the delivery.",
      "example": {
        "body_text_named_params": [
          { "param_name": "order_number", "example": "#9999" },
          { "param_name": "carrier", "example": "UPS" }
        ]
      }
    },
    {
      "type": "BUTTONS",
      "buttons": [
        { "type": "URL", "text": "Track order", "url": "https://shop.example.com/track/{{1}}", "example": ["820982911946154508"] }
      ]
    }
  ]
}'
```

## Write the reply back to the order

Use `tagsAdd` to record what the customer chose. It "Adds tags to a resource", supports orders, and returns `node { id }` and `userErrors` ([tagsAdd, accessed 2026-11-25](https://shopify.dev/docs/api/admin-graphql/latest/mutations/tagsAdd)). The page doesn't list its scopes. `write_orders` is the likely one, so check it on your app.

Avoid `orderUpdate` for this. Its `OrderInput.note` "Overwrites the existing note", and `tags` "Overwrites the existing tags" ([OrderInput, accessed 2026-11-25](https://shopify.dev/docs/api/admin-graphql/latest/input-objects/OrderInput)). A merchant's packing note would disappear. If you must touch the note, read it first and append.

### Cancel only what Shopify can cancel

`orderCancel` takes `orderId`, `reason` and `restock` as required arguments, plus an optional `notifyCustomer` (default false) and `staffNote` of up to 255 characters ([orderCancel, accessed 2026-11-25](https://shopify.dev/docs/api/admin-graphql/latest/mutations/orderCancel)). Cancellation "can't be reversed". It runs as a job, so poll `job { id done }` until `done` is true.

Shopify refuses the cancel when the order is already cancelled, has pending payment authorizations or active returns, or has outstanding fulfillments that can't be cancelled. A paid order at a deactivated location with restock enabled fails too. The service tags every Cancel tap with `whatsapp-cancel-requested`. It calls `orderCancel(reason: CUSTOMER, restock: true, notifyCustomer: false)` only when nothing was fulfilled. `notifyCustomer: false` is our choice, so the customer doesn't get a Shopify email on top of your WhatsApp reply. The service sends no `refundMethod`. Shopify says "Authorized payments will be voided regardless of this setting", so a person checks any captured payment.

## The complete service

This Node 18+ file runs with `npm install express`. It verifies both webhooks, dedupes on `X-Shopify-Webhook-Id` and on Meta's message ID, and writes back through the Admin GraphQL API, version 2026-10. State lives in memory for the example. Swap the maps for tables.

```js
// shopify-whatsapp.js. Node 18+. npm install express
const crypto = require("crypto");
const express = require("express");

const {
  SHOP, SHOPIFY_CLIENT_ID, SHOPIFY_CLIENT_SECRET,
  WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN,
  DEFAULT_COUNTRY_CODE = "", PORT = "3000",
} = process.env;

const ADMIN_URL = `https://${SHOP}.myshopify.com/admin/api/2026-10/graphql.json`;
const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;

const seenDeliveries = new Set(); // X-Shopify-Webhook-Id
const seenMessages = new Set();   // Meta messages[].id
const orders = new Map();         // order gid -> record
const byWamid = new Map();        // template wamid -> order gid
const fulfilledEarly = new Map(); // order id -> fulfillment that arrived before its order

const safeEqual = (a, b) => {
  const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? "");
  return x.length === y.length && crypto.timingSafeEqual(x, y);
};

// Shopify access token, client credentials grant, cached until shortly before expiry.
let token = { value: null, expiresAt: 0 };
async function shopifyToken() {
  if (token.value && Date.now() < token.expiresAt) return token.value;
  const res = await fetch(`https://${SHOP}.myshopify.com/admin/oauth/access_token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_id: SHOPIFY_CLIENT_ID,
      client_secret: SHOPIFY_CLIENT_SECRET,
    }),
  });
  if (!res.ok) throw new Error(`token ${res.status}`);
  const json = await res.json();
  token = { value: json.access_token, expiresAt: Date.now() + (json.expires_in - 300) * 1000 };
  return token.value;
}

async function admin(query, variables) {
  const res = await fetch(ADMIN_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Shopify-Access-Token": await shopifyToken() },
    body: JSON.stringify({ query, variables }),
  });
  const json = await res.json();
  if (!res.ok || json.errors) throw new Error(`admin ${res.status}: ${JSON.stringify(json.errors)}`);
  return json.data;
}

const TAGS_ADD = `mutation tagsAdd($id: ID!, $tags: [String!]!) {
  tagsAdd(id: $id, tags: $tags) { node { id } userErrors { field message } } }`;
const ORDER_CANCEL = `mutation orderCancel($orderId: ID!, $staffNote: String) {
  orderCancel(orderId: $orderId, reason: CUSTOMER, restock: true, notifyCustomer: false, staffNote: $staffNote) {
    job { id done } orderCancelUserErrors { field message code } } }`;
const JOB = `query job($id: ID!) { node(id: $id) { ... on Job { id done } } }`;

async function addTag(orderGid, tag) {
  const data = await admin(TAGS_ADD, { id: orderGid, tags: [tag] });
  if (data.tagsAdd.userErrors.length) throw new Error(JSON.stringify(data.tagsAdd.userErrors));
}

async function cancelOrder(orderGid) {
  const data = await admin(ORDER_CANCEL, { orderId: orderGid, staffNote: "Customer cancelled on WhatsApp" });
  const errors = data.orderCancel.orderCancelUserErrors;
  if (errors.length) return { ok: false, errors };
  let job = data.orderCancel.job;
  for (let i = 0; i < 10 && !job.done; i++) {
    await new Promise((r) => setTimeout(r, 1000));
    job = (await admin(JOB, { id: job.id })).node;
  }
  return { ok: job.done, errors: [] };
}

async function waSend(body) {
  const res = await fetch(GRAPH_URL, {
    method: "POST",
    headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify({ messaging_product: "whatsapp", ...body }),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`Graph ${res.status}: ${JSON.stringify(json.error ?? json)}`);
  return json.messages[0].id;
}
const waText = (to, text) => waSend({ to, type: "text", text: { body: text } });
const named = (pairs) => Object.entries(pairs).map(([k, v]) => ({ type: "text", parameter_name: k, text: String(v) }));

function normalizePhone(raw) {
  if (!raw || /[a-z]/i.test(raw)) return null;   // "555-555-SHIP" and similar
  const digits = raw.replace(/\D/g, "");
  if (raw.trim().startsWith("+")) return digits.length >= 8 ? digits : null;
  return DEFAULT_COUNTRY_CODE && digits.length >= 6 ? DEFAULT_COUNTRY_CODE + digits.replace(/^0+/, "") : null;
}

function whatsappOptIn(order) {
  const attr = (order.note_attributes ?? []).find((a) => a.name === "whatsapp_order_updates");
  return ["yes", "true", "on", "1"].includes(String(attr?.value ?? "").toLowerCase());
}

const handOff = (gid, reason, detail) => console.log("needs_person", { order: gid, reason, detail });

async function onOrderCreated(order) {
  const gid = order.admin_graphql_api_id;
  if (orders.has(gid)) return;
  const phone = normalizePhone(order.phone ?? order.customer?.phone ?? order.shipping_address?.phone ?? order.billing_address?.phone);
  const record = {
    gid, id: String(order.id), name: order.name, phone,
    status: "pending_confirmation",
    fulfilled: order.fulfillment_status != null || fulfilledEarly.has(String(order.id)),
  };
  orders.set(gid, record);
  if (!whatsappOptIn(order)) return (record.status = "no_opt_in");
  if (!phone) return handOff(gid, "no_usable_phone", null);
  if (record.fulfilled) { // nothing left to confirm: send only the shipped notice, if one is waiting
    const waiting = fulfilledEarly.get(record.id);
    return waiting ? onFulfillmentCreated(waiting) : undefined;
  }

  const quickReply = (index, payload) => ({ type: "button", sub_type: "quick_reply", index, parameters: [{ type: "payload", payload }] });
  const wamid = await waSend({
    to: phone, type: "template",
    template: {
      name: "order_confirm_v1", language: { code: "en_US" },
      components: [
        { type: "body", parameters: named({
          customer_name: order.customer?.first_name ?? "there",
          order_number: order.name,
          order_total: `${order.total_price} ${order.currency}`,
        }) },
        quickReply(0, `confirm:${record.id}`),
        quickReply(1, `cancel:${record.id}`),
      ],
    },
  });
  byWamid.set(wamid, gid);
}

async function onFulfillmentCreated(f) {
  const record = [...orders.values()].find((o) => o.id === String(f.order_id));
  if (!record) return void fulfilledEarly.set(String(f.order_id), f); // arrived before orders/create
  record.fulfilled = true;
  if (record.status === "no_opt_in" || !record.phone || record.shipped) return;
  record.shipped = true;
  await waSend({
    to: record.phone, type: "template",
    template: {
      name: "order_shipped_v1", language: { code: "en_US" },
      components: [
        { type: "body", parameters: named({ order_number: record.name, carrier: f.tracking_company ?? "our carrier" }) },
        { type: "button", sub_type: "url", index: 0, parameters: [{ type: "text", text: record.id }] },
      ],
    },
  });
}

async function onWhatsAppMessage(msg) {
  if (seenMessages.has(msg.id)) return;
  seenMessages.add(msg.id);
  const gid = byWamid.get(msg.context?.id);
  const record = gid && orders.get(gid);
  if (!record) return handOff(null, "unmatched_message", { id: msg.id, type: msg.type });
  if (msg.type !== "button") return handOff(gid, "free_text", msg.text?.body ?? msg.type);

  const [verb] = String(msg.button?.payload ?? "").split(":");
  const label = String(msg.button?.text ?? "").toLowerCase();
  const action = verb === "confirm" || label === "confirm order" ? "confirm"
    : verb === "cancel" || label === "cancel order" ? "cancel" : null;
  if (!action) return handOff(gid, "unreadable_button", msg.button);
  if (record.status !== "pending_confirmation") {
    return waText(record.phone, `Order ${record.name} was already handled. Reply here if that looks wrong.`);
  }

  if (action === "confirm") {
    record.status = "confirmed";
    await addTag(gid, "whatsapp-confirmed").catch((err) => handOff(gid, "tag_failed", err.message));
    return waText(record.phone, `Thanks. Order ${record.name} is confirmed.`);
  }

  record.status = "cancel_requested";
  await addTag(gid, "whatsapp-cancel-requested").catch((err) => handOff(gid, "tag_failed", err.message));
  if (record.fulfilled) {
    handOff(gid, "cancel_after_fulfillment", null);
    return waText(record.phone, `Order ${record.name} is already being fulfilled. A person from our team will reply here.`);
  }
  const result = await cancelOrder(gid).catch((err) => ({ ok: false, errors: [err.message] }));
  if (!result.ok) {
    handOff(gid, "order_cancel_failed", result.errors);
    return waText(record.phone, `We got your request for order ${record.name}. A person from our team will confirm it here.`);
  }
  record.status = "cancelled";
  handOff(gid, "check_refund", null); // no refundMethod sent; a person checks captured payments
  return waText(record.phone, `Order ${record.name} is cancelled. Reply here if you have a question about it.`);
}

const app = express();

app.post("/shopify/webhooks", express.raw({ type: "*/*" }), (req, res) => {
  const digest = crypto.createHmac("sha256", SHOPIFY_CLIENT_SECRET).update(req.body).digest("base64");
  if (!safeEqual(digest, req.get("x-shopify-hmac-sha256"))) return res.sendStatus(401);
  const deliveryId = req.get("x-shopify-webhook-id");
  res.sendStatus(200); // inside Shopify's five seconds; the work runs after
  if (seenDeliveries.has(deliveryId)) return;
  seenDeliveries.add(deliveryId);

  const topic = req.get("x-shopify-topic");
  const payload = JSON.parse(req.body.toString("utf8"));
  const job = topic === "orders/create" ? onOrderCreated(payload)
    : topic === "fulfillments/create" ? onFulfillmentCreated(payload) : Promise.resolve();
  job.catch((err) => handOff(payload.admin_graphql_api_id, `${topic}_failed`, err.message));
});

app.get("/whatsapp/webhook", (req, res) => {
  const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
  return ok ? res.send(req.query["hub.challenge"]) : res.sendStatus(403);
});

app.post("/whatsapp/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  if (!safeEqual(expected, req.get("x-hub-signature-256"))) return res.sendStatus(401);
  res.sendStatus(200);
  const body = JSON.parse(req.body.toString("utf8"));
  for (const entry of body.entry ?? []) {
    for (const change of entry.changes ?? []) {
      for (const msg of change.value?.messages ?? []) {
        onWhatsAppMessage(msg).catch((err) => handOff(null, "reply_failed", err.message));
      }
    }
  }
});

app.listen(Number(PORT), () => console.log(`listening on ${PORT}`));
```

The `X-Shopify-Webhook-Id` check stops repeated deliveries. The `orders.has(gid)` check also stops a second delivery of the same order with a different delivery ID. The Meta side follows [X-Hub-Signature-256 verification](/academy/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/). Port the status handler, the no-reply sweep and the TTL handling from the order confirmation article. They are left out here.

## When something fails

If the WhatsApp send throws, the error goes to a person. The Shopify delivery already got its 200, so Shopify won't retry. That is deliberate, because a retry would resend the template. If your endpoint goes down instead, Shopify retries for four hours, and the dedupe absorbs the repeats.

If `orderCancel` returns `orderCancelUserErrors`, the order stays open with the `whatsapp-cancel-requested` tag, and a person picks it up. A tap that arrives after the order was confirmed gets a short reply and no write-back.

The Admin GraphQL API bills by query cost. Shopify's sample shows a 1,000-point bucket that restores at 50 points per second ([Admin GraphQL, accessed 2026-11-25](https://shopify.dev/docs/api/admin-graphql)). The job polling above stops after ten queries per cancel and hands the order to a person if the job is still running.

## Where Z-API Omni fits

Omni has no documented Shopify integration, so a service like the one above stays the bridge. You send the same template through `POST https://api.omni.z-api.io/v1/channels/{channelId}/messages` with a `Bearer` Secret Key. Its docs show the quick-reply payload component, but not yet the inbound shape of a tap. Its webhooks expect a 2xx within five seconds, retry six times over about 23 hours, and carry `x-webhook-delivery-id` for dedupe. One subscription covers WhatsApp, Messenger, Instagram and Telegram, at US$29 per number per month for 1 to 10 numbers, down to US$20 above 100. The QR connection has no per-message cost. On Meta's official API, Meta's fees pass through.

[View documentation](https://developer.omni.z-api.io/en)

*Z-API Omni team*
