# WhatsApp order confirmation with Confirm and Cancel buttons

> Send a utility order template with Confirm and Cancel quick replies, match the tap by context.id, update the order once, and handle no reply and free text.

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

Create a custom UTILITY template with two quick-reply buttons, send it when the order is created, and give each button a payload such as `confirm:1042`. The tap arrives as a `messages` webhook with `type: "button"`. Match it to the order by `context.id`, which is the message ID you stored at send time. Then move the order out of `pending_confirmation` with a conditional update, so a second tap changes nothing.

This page is the generic loop for any shop backend. The Shopify version is in [Shopify order webhooks to WhatsApp](/academy/articles/shopify-order-webhook-whatsapp-notifications/), and the WooCommerce version is in [WooCommerce order status on WhatsApp](/academy/articles/woocommerce-order-status-whatsapp-webhooks/). The same button loop also drives [cash-on-delivery verification](/academy/articles/whatsapp-cash-on-delivery-order-verification/), [return and refund updates](/academy/articles/whatsapp-return-refund-status-updates/) and [order notices from a Supabase table](/academy/articles/supabase-database-webhook-whatsapp-notification/).

## Why this template passes as utility

Meta's categorization page says a utility template must be "non-promotional, not containing any promotional or persuasive intent". It must also be "specific to or requested by the user" or "essential or critical to the user", and is "typically triggered by a user action or request" ([template categorization, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)). An order the customer just placed meets all three.

Meta's order management goal reads "Confirm, update, or cancel an order or transaction with a customer". The same page says such a message should not "promote, recommend, upsell, or cross-sell products". It also classes "an order update with a promo" as marketing. Leave discount codes, product suggestions and review requests out of this template. What happens when Meta recategorizes a template is in [template categories explained](/academy/articles/whatsapp-template-categories-marketing-utility-authentication/).

### Why not a Template Library template

The Template Library has an `ORDER_CONFIRMATION` use-case filter, and library templates must be `UTILITY` with "fixed content that cannot be edited" ([Template Library, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library)). The page shows no body for that type. It also doesn't say a library template can carry Confirm and Cancel quick replies. So write a custom UTILITY template, and treat `ORDER_CONFIRMATION` as the matching library type. The library itself is covered in [WhatsApp Template Library](/academy/articles/whatsapp-template-library-prebuilt-templates/).

## Create the template with a TTL

Meta allows up to 10 quick-reply buttons per template, with a 25-character label each ([template components, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/components)). Two are enough here. The body uses named parameters so the order number and total can't swap places.

Set the time-to-live when you create the template. Meta's TTL page puts the utility default at "30 days" and lets you set it from "30 seconds to 12 hours" with `message_send_ttl_seconds` ([time-to-live, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live)). The page describes no per-send override. "The system drops messages that cannot be delivered within the default or customized TTL." Without a TTL, a confirmation request could reach a phone that was off for days, after the package shipped.

The 6-hour value below is our choice for the example. Meta doesn't recommend a value.

```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_confirm_v1",
  "category": "UTILITY",
  "language": "en_US",
  "parameter_format": "NAMED",
  "message_send_ttl_seconds": 21600,
  "components": [
    {
      "type": "BODY",
      "text": "Hi {{customer_name}}, we received order {{order_number}} for {{order_total}}. Please confirm it or cancel it below.",
      "example": {
        "body_text_named_params": [
          { "param_name": "customer_name", "example": "Ana" },
          { "param_name": "order_number", "example": "1042" },
          { "param_name": "order_total", "example": "$84.90" }
        ]
      }
    },
    {
      "type": "BUTTONS",
      "buttons": [
        { "type": "QUICK_REPLY", "text": "Confirm order" },
        { "type": "QUICK_REPLY", "text": "Cancel order" }
      ]
    }
  ]
}'
```

Only send it to customers who opted in. Meta requires the opt-in to state the business's name and that the person is opting in to receive its messages. The opt-in "can be general and not specifically for WhatsApp" ([getting opt-in, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/getting-opt-in)). A checkbox at checkout that says "Send me order updates from SHOP_NAME on WhatsApp" fits. Collection patterns are in [how to collect WhatsApp opt-in](/academy/articles/whatsapp-opt-in-how-to-collect-consent/).

## Send it with a payload per button

At send time, each quick reply takes a `button` component with `sub_type: "quick_reply"`, its `index` and a `payload` parameter. Put the action and the order ID in the payload: `confirm:1042` and `cancel:1042`. Store the `messages[0].id` from the response against the order. That wamid is your join key.

Meta's current components page doesn't document the send-time `payload` parameter. The syntax appears on Meta's older On-Premises interactive templates page, which is flagged as being sunset ([interactive message templates, accessed 2026-11-25](https://developers.facebook.com/docs/whatsapp/api/messages/message-templates/interactive-message-templates)). That page says the callback echoes your payload, and it warns that users may type instead of tapping. The service below therefore never depends on the payload alone.

## The reply webhook and how to match it

A tap arrives in `entry[].changes[].value.messages[]` with this shape, per Meta's button reference ([button webhook, accessed 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button)):

```json
{
  "context": {
    "from": "<BUSINESS_DISPLAY_PHONE_NUMBER>",
    "id": "<CONTEXTUAL_WHATSAPP_MESSAGE_ID>"
  },
  "from": "<WHATSAPP_USER_PHONE_NUMBER>",
  "from_user_id": "<BSUID>",
  "id": "<WHATSAPP_MESSAGE_ID>",
  "timestamp": "<WEBHOOK_TRIGGER_TIMESTAMP>",
  "type": "button",
  "button": {
    "payload": "<BUTTON_LABEL_TEXT>",
    "text": "<BUTTON_LABEL_TEXT>"
  }
}
```

Meta defines `context.id` as the "WhatsApp message ID of the message containing the button the WhatsApp user tapped". Match on it first. The `from` field is conditional: Meta omits it when the user has a username and no available phone number. A lookup by phone fails for that customer, while `context.id` still finds the order.

Then read `button.payload`. The reference labels it as the button label, and its example has payload and text both set to "Unsubscribe". If the payload doesn't parse as `confirm:<id>` or `cancel:<id>`, fall back to `button.text`. Reply to the phone number stored on the order, never to a number taken from the webhook.

The tap opens a 24-hour customer service window, so the "your order is cancelled" reply can be free-form text. Meta's billing for messages inside that window changed on 2026-10-01, as [service message charges from October 2026](/academy/articles/meta-whatsapp-service-message-charges-october-2026/) explains.

## The order states

Each order moves through these states:

| State | Entered when | Write-back to the shop |
| --- | --- | --- |
| `pending_confirmation` | The template is sent | None |
| `confirmed` | Confirm tapped while pending | PATCH status `confirmed` |
| `cancelled` | Cancel tapped while pending and unfulfilled | PATCH status `cancelled`; your backend releases stock |
| `expired_no_reply` | No delivery before the TTL, or no reply by your deadline | None. A person decides |

Make the handler idempotent in two places. First, dedupe inbound messages on `messages[].id`, because Meta retries failed deliveries and the same tap can arrive twice ([what happens when your webhook endpoint is down](/academy/articles/whatsapp-webhook-retries-endpoint-down/)). Second, make the transition conditional: `UPDATE orders SET status = 'confirmed' WHERE id = $1 AND status = 'pending_confirmation'`. If zero rows change, the order already left that state. A Confirm after a Cancel becomes a polite reply instead of a reversal.

## The complete service

This Node 18+ file runs with `npm install express`. It takes order events from your backend, sends the template, verifies Meta's `X-Hub-Signature-256`, matches taps and writes back. It assumes your backend accepts `PATCH SHOP_API_URL/orders/<id>` with a JSON `status`. Swap the in-memory maps for tables, and keep the conditional update.

```js
// order-confirm-service.js. Node 18+. npm install express
const crypto = require("crypto");
const express = require("express");

const {
  WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN,
  SHOP_API_URL, SHOP_API_TOKEN, EVENT_TOKEN, PORT = "3000",
} = process.env;

const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const TTL_MS = 21600 * 1000;           // same value as message_send_ttl_seconds
const REPLY_DEADLINE_MS = 24 * 3600 * 1000; // your choice

const orders = new Map();   // orderId -> order
const byWamid = new Map();  // wamid of the template -> orderId
const seen = new Set();     // inbound message ids already handled

function transition(order, from, to) {
  if (order.status !== from) return false; // UPDATE ... WHERE status = from
  order.status = to;
  order.updatedAt = Date.now();
  return true;
}

async function graphSend(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;
}

const sendText = (to, text) => graphSend({ to, type: "text", text: { body: text } });

async function sendConfirmation(order) {
  const quickReply = (index, payload) => ({
    type: "button", sub_type: "quick_reply", index,
    parameters: [{ type: "payload", payload }],
  });
  const json = await graphSend({
    to: order.phone,
    type: "template",
    template: {
      name: "order_confirm_v1",
      language: { code: "en_US" },
      components: [
        {
          type: "body",
          parameters: [
            { type: "text", parameter_name: "customer_name", text: order.customerName },
            { type: "text", parameter_name: "order_number", text: order.number },
            { type: "text", parameter_name: "order_total", text: order.total },
          ],
        },
        quickReply(0, `confirm:${order.id}`),
        quickReply(1, `cancel:${order.id}`),
      ],
    },
  });
  return json.messages[0].id;
}

async function patchOrder(orderId, status) {
  const res = await fetch(`${SHOP_API_URL}/orders/${encodeURIComponent(orderId)}`, {
    method: "PATCH",
    headers: { Authorization: `Bearer ${SHOP_API_TOKEN}`, "Content-Type": "application/json" },
    body: JSON.stringify({ status }),
  });
  if (!res.ok) throw new Error(`shop PATCH ${res.status}`);
}

function handOff(order, reason, detail) {
  // Replace with a ticket, a Slack message or an inbox assignment.
  console.log("needs_person", { orderId: order?.id ?? null, reason, detail });
}

function readAction(msg) {
  const [verb, id] = String(msg.button?.payload ?? "").split(":");
  if ((verb === "confirm" || verb === "cancel") && id) return { verb, id };
  const label = String(msg.button?.text ?? "").trim().toLowerCase();
  if (label === "confirm order") return { verb: "confirm" };
  if (label === "cancel order") return { verb: "cancel" };
  return null;
}

function findPendingByPhone(phone) {
  if (!phone) return null;
  for (const o of orders.values()) {
    if (o.phone === phone && o.status === "pending_confirmation") return o;
  }
  return null;
}

async function handleMessage(msg) {
  if (seen.has(msg.id)) return;
  seen.add(msg.id);

  const linkedId = byWamid.get(msg.context?.id);
  const order = linkedId ? orders.get(linkedId) : findPendingByPhone(msg.from);
  if (!order) return handOff(null, "unmatched_message", { id: msg.id, type: msg.type });
  if (msg.type !== "button") return handOff(order, "free_text", msg.text?.body ?? msg.type);

  const action = readAction(msg);
  if (!action || (action.id && action.id !== order.id)) {
    return handOff(order, "unreadable_button", msg.button);
  }
  if (order.status === "expired_no_reply") {
    handOff(order, "late_reply", action.verb);
    return sendText(order.phone, `Thanks. A person from our team will follow up on order ${order.number} here.`);
  }

  if (action.verb === "confirm") {
    if (!transition(order, "pending_confirmation", "confirmed")) {
      return sendText(order.phone, `Order ${order.number} is already ${order.status.replace(/_/g, " ")}. Reply here if that looks wrong.`);
    }
    try {
      await patchOrder(order.id, "confirmed");
    } catch (err) {
      order.status = "pending_confirmation";
      handOff(order, "write_back_failed", err.message);
      return sendText(order.phone, `We got your reply for order ${order.number}. A person from our team will confirm it here.`);
    }
    return sendText(order.phone, `Thanks. Order ${order.number} is confirmed.`);
  }

  if (order.fulfilled) {
    handOff(order, "cancel_after_fulfillment", null);
    return sendText(order.phone, `Order ${order.number} is already being fulfilled. A person from our team will reply here.`);
  }
  if (!transition(order, "pending_confirmation", "cancelled")) {
    return sendText(order.phone, `Order ${order.number} is already ${order.status.replace(/_/g, " ")}. Reply here if that looks wrong.`);
  }
  try {
    await patchOrder(order.id, "cancelled");
  } catch (err) {
    order.status = "pending_confirmation";
    return handOff(order, "write_back_failed", err.message);
  }
  return sendText(order.phone, `Order ${order.number} is cancelled. Reply here if you have a question about it.`);
}

function handleStatus(status) {
  const order = orders.get(byWamid.get(status.id));
  if (!order) return;
  if (status.status === "delivered") {
    order.deliveredAt = Date.now();
    if (order.status === "expired_no_reply") console.log("late_delivery", { orderId: order.id });
  }
  if (status.status === "failed") {
    transition(order, "pending_confirmation", "expired_no_reply");
    handOff(order, "template_failed", status.errors);
  }
}

const app = express();

// Your shop backend posts { type: "order.created" | "order.fulfilled", order }.
app.post("/events", express.json(), async (req, res) => {
  if (req.get("authorization") !== `Bearer ${EVENT_TOKEN}`) return res.sendStatus(401);
  const { type, order } = req.body ?? {};
  if (type === "order.fulfilled" && orders.has(String(order?.id))) {
    orders.get(String(order.id)).fulfilled = true;
    return res.sendStatus(200);
  }
  if (type !== "order.created" || !order?.id) return res.sendStatus(400);
  const id = String(order.id);
  if (orders.has(id)) return res.sendStatus(200); // repeated event
  if (!order.whatsappOptIn) return res.sendStatus(202); // no opt-in, no message

  const record = {
    id, number: String(order.number), total: String(order.total),
    customerName: order.customerName, phone: order.phone, // digits with country code
    status: "pending_confirmation", fulfilled: false, sentAt: Date.now(), deliveredAt: null,
  };
  orders.set(id, record);
  try {
    const wamid = await sendConfirmation(record);
    byWamid.set(wamid, id);
    record.wamid = wamid;
    res.sendStatus(200);
  } catch (err) {
    record.status = "expired_no_reply";
    handOff(record, "send_failed", err.message);
    res.sendStatus(502);
  }
});

app.get("/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("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  const given = Buffer.from(req.get("x-hub-signature-256") ?? "");
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, Buffer.from(expected))) {
    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 ?? []) {
      if (change.field !== "messages") continue;
      for (const s of change.value?.statuses ?? []) handleStatus(s);
      for (const m of change.value?.messages ?? []) {
        handleMessage(m).catch((err) => handOff(null, "handler_error", err.message));
      }
    }
  }
});

// No silent cancels: expired orders go to a person and stay open in the shop.
setInterval(() => {
  const now = Date.now();
  for (const o of orders.values()) {
    if (o.status !== "pending_confirmation") continue;
    if (!o.deliveredAt && now - o.sentAt > TTL_MS) {
      transition(o, "pending_confirmation", "expired_no_reply");
      handOff(o, "not_delivered_within_ttl", null);
    } else if (o.deliveredAt && now - o.deliveredAt > REPLY_DEADLINE_MS) {
      transition(o, "pending_confirmation", "expired_no_reply");
      handOff(o, "no_reply", null);
    }
  }
}, 60 * 1000);

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

The phone on the order must be digits with the country code, the same form Meta puts in `from`. The fallback lookup by phone only runs when a message's `context.id` doesn't match a stored template, which is the usual case for typed text.

## When nobody replies

Never cancel an order silently because the customer didn't tap. For a prepaid order, the sensible default is to keep it and ship. For cash on delivery, a person can call or send one follow-up inside the rules, then decide.

Meta names no error code for a message the TTL dropped. The service treats "no `delivered` status before the TTL ran out" as a drop. A `delivered` status can still arrive late, so log it even after the order expired. A `failed` status goes straight to a person.

## Typed replies and late cancels

Customers type "no", "wrong address" or a question instead of tapping. Route any non-button message to a person. Don't treat "no" as a cancel unless you send a confirm step first, such as a reply-button message asking "Cancel order 1042?". That in-window message type is covered in [interactive reply buttons](/academy/articles/whatsapp-interactive-buttons-list-messages-limits/).

Accept Cancel only while the order is unfulfilled. After that, answer with your support or returns route. The shop's own rules still apply. Shopify's `orderCancel` refuses orders with outstanding fulfillments it can't cancel, while WooCommerce enforces no window, so your code has to.

Webhooks can also arrive [out of order](/academy/articles/whatsapp-webhooks-out-of-order-message-sequencing/). A Cancel tap can land before the `delivered` status for the same template. The service doesn't care, because the state change depends on the order status, not on event order.

## Where Z-API Omni fits

Omni sends the same template through `POST https://api.omni.z-api.io/v1/channels/{channelId}/messages` with `Authorization: Bearer <Secret Key>`. Its custom-model page documents the quick-reply payload component. A disconnected channel returns `422` with `subCode: CHANNEL_DISCONNECTED`, and the message is not sent. Template creation accepts `message_send_ttl_seconds`. The docs don't yet show the inbound shape of a button tap.

<!-- TODO:test Omni snippet: send with quick-reply payloads; whether body params need parameter_name on a NAMED template; inbound JSON of the tap (where payload and text land, and whether message_id_reply links it to the template's messageId) -->
```json
{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "TEMPLATE",
    "attachments": [{
      "template": {
        "name": "order_confirm_v1",
        "language": { "policy": "deterministic", "code": "en_US" },
        "components": [
          { "type": "body", "parameters": [
            { "type": "text", "text": "Ana" },
            { "type": "text", "text": "1042" },
            { "type": "text", "text": "$84.90" }
          ] },
          { "type": "button", "sub_type": "quick_reply", "index": 0, "parameters": [{ "type": "payload", "payload": "confirm:1042" }] },
          { "type": "button", "sub_type": "quick_reply", "index": 1, "parameters": [{ "type": "payload", "payload": "cancel:1042" }] }
        ]
      }
    }]
  }
}
```

One subscription covers WhatsApp, Messenger, Instagram and Telegram, at US$29 per number per month for 1 to 10 numbers, with webhooks included without limit. The QR connection has no templates and no per-message cost; there, an `INTERACTIVE_BUTTON` message carries up to three buttons. Meta's fees pass through on Meta's official API.

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

*Z-API Omni team*
