A cash-on-delivery verification message is a WhatsApp utility template that asks the buyer to confirm a COD order, the amount due and the address before dispatch. Place a fulfillment hold the moment the order arrives. Send the template with Confirm, Change address and Cancel buttons, and release the hold only on a confirmed answer. Silence sends the order to a call queue, never to an automatic cancel.
The generic Confirm and Cancel loop, with payloads per button and matching on context.id, is in WhatsApp order confirmation with Confirm and Cancel buttons. This page adds what cash on delivery needs on top of it: blocking dispatch in Shopify, changing the address, and a fallback to a person. Shopify’s webhook contract and token are in Shopify order webhooks to WhatsApp.
Why the message passes as utility
Meta’s order management objective reads “Confirm, update, or cancel an order or transaction with a customer, using specific order or transaction details.” Its example reads “Your order {{order_number}} is confirmed. We will let you know once your package is on its way” (template categorization, accessed 2026-11-27).
A COD check fits that objective. The buyer just placed the order, and the message names its number, amount and address. Meta’s page never mentions “cash on delivery”, “COD”, “address” or “verification”, so the fit runs through order management, not a named rule.
Keep the body plain. Meta treats “an order update with a promo” as mixed content, which makes it marketing. No discount for prepaying, no product suggestions and no review request belong in this template.
The Template Library has three matching use cases: ORDER_CONFIRMATION, ORDER_ACTION_NEEDED and ORDER_OR_TRANSACTION_CANCEL. Meta’s page shows no body text for them. You can browse them with GET /message_template_library?topic=ORDER_MANAGEMENT&industry=E_COMMERCE (Template Library, accessed 2026-11-27). This page uses a custom template, because it needs three quick replies.
Detect a COD order in Shopify
Subscribe to orders/create, which “Requires at least one of the following scopes: read_orders, read_marketplace_orders.” Then read paymentGatewayNames from the order. Shopify describes it as “A list of the names of all payment gateways used for the order,” with “Shopify Payments” and “Cash on Delivery (COD)” as its examples (Order object, accessed 2026-11-27).
Shopify’s page doesn’t say whether a merchant can rename that gateway. The service matches on a configurable string, COD_GATEWAY, set by default to Shopify’s example. Place one test COD order and check the value before going live.
If you run WooCommerce, its COD page says “WooCommerce sets the status of orders using COD to Processing until payment is collected” (cash on delivery, accessed 2026-11-27). The page names no gateway ID. cod is the likely value of payment_method, but check it on a test order. Woo signing and write-back are in WooCommerce order status on WhatsApp.
Hold dispatch before you send anything
Hold the order first, or the warehouse can ship while the buyer is still reading. Place a hold on each of the order’s fulfillment orders with fulfillmentOrderHold. It takes the fulfillment order id and a fulfillmentHold input with reason, reasonNotes, notifyMerchant and handle (fulfillmentOrderHold, accessed 2026-11-27). Shopify’s sample response shows "status":"ON_HOLD".
The mutation needs write_merchant_managed_fulfillment_orders or write_third_party_fulfillment_orders. The user behind the token also needs the fulfill and ship orders permission. Passing a handle names your hold, and Shopify rejects a second hold with the same handle on one fulfillment order.
Shopify’s FulfillmentHoldReason enum has no value for a pending customer confirmation (FulfillmentHoldReason, accessed 2026-11-27). Use OTHER with reasonNotes set to “Awaiting WhatsApp COD confirmation”. INCORRECT_ADDRESS exists too, if you want a second hold when the buyer asks to change the address.
Release with fulfillmentOrderReleaseHold(id, holdIds, externalId). Shopify writes: “It is highly recommended that apps supply the ids of the holds that they intend to release” (fulfillmentOrderReleaseHold, accessed 2026-11-27). The service stores each hold ID it creates and releases only those.
The template and its time-to-live
Create a custom UTILITY template with three quick replies. Meta’s TTL page puts the utility range at “30 seconds to 12 hours”, set with message_send_ttl_seconds when you create the template (time-to-live, accessed 2026-11-27). That page shows no per-send override, so pick one TTL that ends before your earliest dispatch cutoff. The code below uses 6 hours.
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": "cod_verify_v1",
"category": "UTILITY",
"language": "en_US",
"parameter_format": "NAMED",
"message_send_ttl_seconds": 21600,
"components": [
{
"type": "BODY",
"text": "Order {{order_number}} is set for cash on delivery. Amount due on delivery: {{amount_due}}. Delivery address: {{delivery_address}}. Please confirm before we dispatch it.",
"example": {
"body_text_named_params": [
{ "param_name": "order_number", "example": "#1042" },
{ "param_name": "amount_due", "example": "84.90 USD" },
{ "param_name": "delivery_address", "example": "12 Market Street, Springfield, 12345" }
]
}
},
{
"type": "BUTTONS",
"buttons": [
{ "type": "QUICK_REPLY", "text": "Confirm order" },
{ "type": "QUICK_REPLY", "text": "Change address" },
{ "type": "QUICK_REPLY", "text": "Cancel order" }
]
}
]
}'
Send it only to buyers who gave a WhatsApp opt-in that names your store. Shopify’s SMS consent doesn’t count. A COD buyer without an opt-in goes straight to the call queue. The service reads that opt-in from an order note attribute named whatsapp_order_updates, which your cart or checkout must set.
The three replies and their write-backs
A tap arrives as a messages webhook with type: "button", button.payload, button.text and a context.id equal to the template’s message ID (button webhook, accessed 2026-11-27). The service sets each payload to cod_confirm:<order_id>, cod_address:<order_id> or cod_cancel:<order_id>, and falls back to the label.
| Tap | Shopify write-back | Hold |
|---|---|---|
| Confirm order | tagsAdd with cod-confirmed |
Released |
| Change address | tagsAdd with cod-address-change-requested, then orderUpdate once a person checks the new address |
Kept until the address is updated |
| Cancel order | After a second confirmation in the window, orderCancel and cod-cancelled |
Irrelevant once cancelled |
| No reply by the deadline | tagsAdd with cod-no-reply, and the order joins the call queue |
Kept |
Change address
The tap opens a customer service window, so you can ask for the new address in plain text. A person reads the reply and submits a structured address. The service then calls orderUpdate(input: {id, shippingAddress}), which needs write_orders (orderUpdate, accessed 2026-11-27). Pass only id and shippingAddress, because tags and note on that input overwrite what’s there.
Shopify’s page doesn’t say whether an address change is limited to unfulfilled orders. The hold keeps the order unfulfilled, but test an address change on an order whose fulfillment orders are on hold.
Meta’s address_message would collect a structured address in the chat. Its page says “This feature is only available for businesses based in India and their India customers” (address messages, accessed 2026-11-27). The reply arrives as interactive.type: "nfm_reply", with response_json as a JSON string. Elsewhere, a Flow with an address form is the structured option, covered in WhatsApp Flows.
Cancel
Don’t cancel on the first tap. Ask once more inside the window with reply buttons, “Yes, cancel” and “Keep my order”. That answer arrives as type: "interactive" with interactive.button_reply.{id, title}. Meta’s sample is {"id":"cancel-button","title":"Cancel"} (interactive webhook, accessed 2026-11-27).
Then call orderCancel(orderId, reason: CUSTOMER, restock: true, notifyCustomer: false, staffNote). It runs as a job, so poll job { id done }. Errors arrive in orderCancelUserErrors, and Shopify warns “This action cannot be reversed” (orderCancel, accessed 2026-11-27). An unpaid COD order has nothing to refund, so the service sends no refundMethod.
The complete service
This Node 18+ file runs with npm install express. It verifies both webhooks, dedupes on X-Shopify-Webhook-Id and Meta’s message IDs, and moves each order through conditional state changes. Two admin routes, protected by ADMIN_KEY, let a person apply a checked address or a phone confirmation. State lives in memory for the example.
// cod-verification.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, ADMIN_KEY,
COD_GATEWAY = "Cash on Delivery (COD)", REPLY_DEADLINE_HOURS = "6",
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 DEADLINE_MS = Number(REPLY_DEADLINE_HOURS) * 60 * 60 * 1000;
const seen = new Set(); // X-Shopify-Webhook-Id and Meta message ids
const orders = new Map(); // order gid -> record
const byWamid = new Map(); // outbound wamid -> order gid
const safeEqual = (a, b) => {
const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? "");
return x.length === y.length && crypto.timingSafeEqual(x, y);
};
const handOff = (gid, reason, detail) => console.log("needs_person", { order: gid, reason, detail });
const findById = (id) => [...orders.values()].find((o) => o.id === String(id));
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 ORDER_INFO = `query info($id: ID!) { order(id: $id) {
paymentGatewayNames
fulfillmentOrders(first: 10) { nodes { id status } } } }`;
const HOLD = `mutation hold($id: ID!, $hold: FulfillmentOrderHoldInput!) {
fulfillmentOrderHold(id: $id, fulfillmentHold: $hold) {
fulfillmentHold { id } fulfillmentOrder { id status } userErrors { field message } } }`;
const RELEASE = `mutation release($id: ID!, $holdIds: [ID!]) {
fulfillmentOrderReleaseHold(id: $id, holdIds: $holdIds) {
fulfillmentOrder { id status } userErrors { field message } } }`;
const ADDRESS = `mutation address($input: OrderInput!) {
orderUpdate(input: $input) { order { id } userErrors { field message } } }`;
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!) { job(id: $id) { id done } }`;
const addTag = (gid, tag) => admin(TAGS_ADD, { id: gid, tags: [tag] })
.then((d) => d.tagsAdd.userErrors.length && handOff(gid, "tag_failed", d.tagsAdd.userErrors))
.catch((err) => handOff(gid, "tag_failed", err.message));
async function releaseHolds(rec) {
for (const h of rec.holds) {
const d = await admin(RELEASE, { id: h.foId, holdIds: [h.holdId] });
if (d.fulfillmentOrderReleaseHold.userErrors.length) {
handOff(rec.gid, "release_failed", d.fulfillmentOrderReleaseHold.userErrors);
return false;
}
}
rec.holds = [];
return true;
}
async function cancelOrder(gid) {
const data = await admin(ORDER_CANCEL, { orderId: gid, staffNote: "Buyer cancelled COD order 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 })).job;
}
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", recipient_type: "individual", ...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 } })
.catch((err) => handOff(null, "text_failed", err.message));
const named = (pairs) => Object.entries(pairs).map(([k, v]) => ({ type: "text", parameter_name: k, text: String(v) }));
const quickReply = (index, payload) => ({ type: "button", sub_type: "quick_reply", index, parameters: [{ type: "payload", payload }] });
function normalizePhone(raw) {
if (!raw || /[a-z]/i.test(raw)) return null;
const digits = String(raw).replace(/\D/g, "");
if (String(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());
}
// Only move forward from an expected state. A second tap or a repeated webhook changes nothing.
function transition(rec, from, to) {
if (!from.includes(rec.state)) return false;
rec.state = to;
return true;
}
async function callQueue(rec, reason, tag = "cod-call-queue") {
rec.state = "call_queue"; // the hold stays in place
console.log("call_queue", { order: rec.gid, name: rec.name, phone: rec.phone, reason });
await addTag(rec.gid, tag);
}
// ---- Order created ----
async function onOrderCreated(order) {
const gid = order.admin_graphql_api_id;
if (orders.has(gid)) return;
const rec = { gid, id: String(order.id), name: order.name, state: "new", holds: [], phone: null };
orders.set(gid, rec);
const info = (await admin(ORDER_INFO, { id: gid })).order;
if (!info.paymentGatewayNames.includes(COD_GATEWAY)) return void (rec.state = "not_cod");
for (const fo of info.fulfillmentOrders.nodes) {
if (["CLOSED", "CANCELLED"].includes(fo.status)) continue;
const r = (await admin(HOLD, {
id: fo.id,
hold: { reason: "OTHER", reasonNotes: "Awaiting WhatsApp COD confirmation", notifyMerchant: false, handle: "whatsapp-cod" },
})).fulfillmentOrderHold;
if (r.userErrors.length) handOff(gid, "hold_failed", r.userErrors);
else rec.holds.push({ foId: fo.id, holdId: r.fulfillmentHold.id });
}
if (!rec.holds.length) handOff(gid, "no_hold_placed", info.fulfillmentOrders.nodes);
rec.phone = normalizePhone(order.phone ?? order.customer?.phone ?? order.shipping_address?.phone ?? order.billing_address?.phone);
if (!whatsappOptIn(order) || !rec.phone) return callQueue(rec, "no_whatsapp_opt_in_or_phone");
const a = order.shipping_address ?? {};
const address = [a.address1, a.address2, a.city, a.zip].filter(Boolean).join(", ") || "the address on your order";
rec.state = "awaiting_reply";
rec.deadline = Date.now() + DEADLINE_MS;
try {
rec.wamid = await waSend({
to: rec.phone, type: "template",
template: {
name: "cod_verify_v1", language: { code: "en_US" },
components: [
{ type: "body", parameters: named({ order_number: order.name, amount_due: `${order.total_price} ${order.currency}`, delivery_address: address }) },
quickReply(0, `cod_confirm:${rec.id}`),
quickReply(1, `cod_address:${rec.id}`),
quickReply(2, `cod_cancel:${rec.id}`),
],
},
});
byWamid.set(rec.wamid, gid);
} catch (err) {
await callQueue(rec, `send_failed: ${err.message}`);
}
}
// ---- Replies ----
const OPEN = ["awaiting_reply", "call_queue"];
const alreadyHandled = (rec) => waText(rec.phone, `Order ${rec.name} was already handled. Reply here if that looks wrong.`);
async function onAction(rec, action) {
if (action === "confirm") {
if (!transition(rec, [...OPEN, "cancel_pending"], "confirmed")) return alreadyHandled(rec);
await addTag(rec.gid, "cod-confirmed");
if (!(await releaseHolds(rec))) return waText(rec.phone, `Thanks. Order ${rec.name} is confirmed. Our team will finish preparing it.`);
return waText(rec.phone, `Thanks. Order ${rec.name} is confirmed and goes to dispatch.`);
}
if (action === "address") {
if (!transition(rec, OPEN, "address_change")) return alreadyHandled(rec);
await addTag(rec.gid, "cod-address-change-requested");
return waText(rec.phone, `Please reply with the full delivery address for order ${rec.name}: street and number, area, city and postal code.`);
}
if (action === "cancel") {
if (!transition(rec, OPEN, "cancel_pending")) return alreadyHandled(rec);
const wamid = await waSend({
to: rec.phone, type: "interactive",
interactive: {
type: "button",
body: { text: `Cancel order ${rec.name}? This can't be undone.` },
action: { buttons: [
{ type: "reply", reply: { id: `cod_cancel_yes:${rec.id}`, title: "Yes, cancel" } },
{ type: "reply", reply: { id: `cod_keep:${rec.id}`, title: "Keep my order" } },
] },
},
});
return void byWamid.set(wamid, rec.gid);
}
handOff(rec.gid, "unreadable_button", null);
}
async function confirmCancel(rec) {
if (!transition(rec, ["cancel_pending"], "cancelling")) return alreadyHandled(rec);
const result = await cancelOrder(rec.gid).catch((err) => ({ ok: false, errors: [err.message] }));
if (!result.ok) {
await callQueue(rec, `order_cancel_failed: ${JSON.stringify(result.errors)}`);
return waText(rec.phone, `We got your request for order ${rec.name}. A person from our team will confirm it here.`);
}
rec.state = "cancelled";
await addTag(rec.gid, "cod-cancelled");
return waText(rec.phone, `Order ${rec.name} is cancelled. Nothing is due.`);
}
async function onMessage(msg) {
if (seen.has(msg.id)) return;
seen.add(msg.id);
let rec = orders.get(byWamid.get(msg.context?.id));
if (msg.type === "button") {
if (!rec) return handOff(null, "unmatched_tap", msg.button);
const verb = String(msg.button?.payload ?? "").split(":")[0];
const label = String(msg.button?.text ?? "").toLowerCase();
const action = verb === "cod_confirm" || label === "confirm order" ? "confirm"
: verb === "cod_address" || label === "change address" ? "address"
: verb === "cod_cancel" || label === "cancel order" ? "cancel" : null;
return onAction(rec, action);
}
if (msg.type === "interactive" && msg.interactive?.type === "button_reply") {
const [verb, id] = String(msg.interactive.button_reply?.id ?? "").split(":");
rec = rec ?? findById(id);
if (!rec) return handOff(null, "unmatched_reply", msg.interactive.button_reply);
if (verb === "cod_cancel_yes") return confirmCancel(rec);
if (verb === "cod_keep") return onAction(rec, "confirm");
}
// Typed text: a new address or a question. A person reads it; nothing is parsed automatically.
rec = rec ?? [...orders.values()].filter((o) => o.phone === msg.from && o.state !== "not_cod").pop();
handOff(rec?.gid ?? null, rec?.state === "address_change" ? "new_address_text" : "free_text", msg.text?.body ?? msg.type);
if (rec?.state === "address_change") {
return waText(rec.phone, `Thanks. A person from our team will check the address for order ${rec.name} and confirm here.`);
}
}
function onStatus(s) {
const rec = orders.get(byWamid.get(s.id));
if (!rec || s.id !== rec.wamid) return;
if (s.status === "delivered") rec.deliveredAt ??= Date.now();
if (s.status === "failed" && rec.state === "awaiting_reply") {
callQueue(rec, `template_failed: ${JSON.stringify(s.errors ?? [])}`);
}
}
// No reply by the deadline: call queue, hold kept. Never an automatic cancel.
setInterval(() => {
for (const rec of orders.values()) {
if (rec.state === "awaiting_reply" && Date.now() > rec.deadline) callQueue(rec, "no_reply", "cod-no-reply");
}
}, 60 * 1000);
// ---- HTTP ----
const app = express();
const requireAdmin = (req, res, next) => (ADMIN_KEY && safeEqual(req.get("x-admin-key"), ADMIN_KEY) ? next() : res.sendStatus(401));
// A person checked the new address. Body: { "shippingAddress": { "address1": "...", "city": "...", "zip": "...", "countryCode": "..." } }
app.post("/admin/orders/:id/address", express.json(), requireAdmin, async (req, res) => {
const rec = findById(req.params.id);
if (!rec) return res.sendStatus(404);
if (!["awaiting_reply", "call_queue", "address_change"].includes(rec.state)) return res.status(409).json({ state: rec.state });
const { shippingAddress } = req.body ?? {};
if (!shippingAddress) return res.status(400).json({ error: "shippingAddress is required" });
try {
const d = await admin(ADDRESS, { input: { id: rec.gid, shippingAddress } });
if (d.orderUpdate.userErrors.length) return res.status(422).json(d.orderUpdate.userErrors);
await addTag(rec.gid, "cod-address-changed");
const released = await releaseHolds(rec);
rec.state = "confirmed";
if (rec.phone) await waText(rec.phone, `Thanks. The delivery address for order ${rec.name} is updated.`);
res.json({ ok: true, released });
} catch (err) {
res.status(502).json({ error: err.message });
}
});
// A person reached the buyer by phone and the buyer confirmed.
app.post("/admin/orders/:id/confirmed-by-call", requireAdmin, async (req, res) => {
const rec = findById(req.params.id);
if (!rec) return res.sendStatus(404);
if (!transition(rec, [...OPEN, "address_change", "cancel_pending"], "confirmed")) return res.status(409).json({ state: rec.state });
try {
await addTag(rec.gid, "cod-confirmed-by-call");
res.json({ ok: true, released: await releaseHolds(rec) });
} catch (err) {
res.status(502).json({ error: err.message });
}
});
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);
res.sendStatus(200);
const deliveryId = req.get("x-shopify-webhook-id");
if (seen.has(deliveryId)) return;
seen.add(deliveryId);
if (req.get("x-shopify-topic") !== "orders/create") return;
const order = JSON.parse(req.body.toString("utf8"));
onOrderCreated(order).catch((err) => handOff(order.admin_graphql_api_id, "order_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 ?? []) {
if (change.field !== "messages") continue;
(change.value?.statuses ?? []).forEach(onStatus);
for (const msg of change.value?.messages ?? []) onMessage(msg).catch((err) => handOff(null, "reply_failed", err.message));
}
}
});
app.listen(Number(PORT), () => console.log(`listening on ${PORT}`));
The buyer’s typed address goes to a person by design. Free-text addresses vary too much to write into an order unread. If you build a Flow for the address instead, its answer replaces the free text and the admin route.
When nobody replies
Never cancel a COD order because the buyer didn’t tap. The phone can be off, the buyer can miss the message, or the template can fail. At the deadline, the service tags the order cod-no-reply, adds it to the call queue and keeps the hold. A failed status on the template does the same at once.
The call queue is yours to run. A person can phone the buyer and then use the confirmed-by-call route, or cancel in the Shopify admin. If you want the call to start from WhatsApp, Meta’s calling option is covered in the WhatsApp Business Calling API.
A late tap still works. An order in call_queue accepts Confirm, Change address and Cancel, so a buyer who answers after the deadline isn’t turned away. The person working the queue should check the order’s tags before calling.
Duplicates, retries and timing
Shopify retries a failed delivery 8 times over 4 hours (HTTPS webhooks, accessed 2026-11-27). The X-Shopify-Webhook-Id check stops repeated deliveries, and orders.has(gid) stops a second delivery of the same order. Meta retries too, so the service dedupes on messages[].id. Every state change is conditional, so a second Confirm gets a short reply instead of a second release.
If the hold fails or no hold is placed, the template still goes out, and a person sees a hold_failed or no_hold_placed log line. The warehouse could ship before the answer arrives, so treat that line as urgent.
The deadline and the TTL work together. With a 6-hour TTL and a 6-hour deadline, an undelivered template expires about when the order reaches the call queue. Meta names no error code for a message the TTL dropped. If your dispatch cutoff is closer than six hours, shorten both.
Check the label lengths of both button types before you translate the template or the cancel prompt. The limits are in interactive buttons and list messages.
Where Z-API Omni fits
Omni documents no Shopify or WooCommerce integration and no scheduler, so the hold, the deadline and the call queue stay in your service. On Meta’s official API, its custom-model page shows a UTILITY template’s quick_reply payload component, and message_send_ttl_seconds accepts 30 to 43200 for utility. Flows (INTERACTIVE_FLOW, Meta only) return a documented FORM_RESPONSE for an address form. The inbound shape of a button tap isn’t documented.
On the QR connection, INTERACTIVE_BUTTON holds up to three buttons, so all three choices fit.
{
"recipient": { "identifier": "5511999999999" },
"content": {
"type": "INTERACTIVE_BUTTON",
"body": { "message": "Order #1042 is set for cash on delivery. Please confirm before we dispatch it." },
"attachments": [
{ "id": "cod_confirm:1042", "title": "Confirm order" },
{ "id": "cod_address:1042", "title": "Change address" },
{ "id": "cod_cancel:1042", "title": "Cancel order" }
]
}
}
A disconnected channel returns 422 with subCode: CHANNEL_DISCONNECTED, and the message isn’t kept to go out later, so queue a call. 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, and Meta’s fees pass through on Meta’s official API.
Z-API Omni team