Cash-on-delivery تصدیقی پیغام ایک WhatsApp utility ٹیمپلیٹ ہے جو خریدار سے dispatch سے پہلے COD آرڈر، واجب الادا رقم اور پتے کی تصدیق مانگتا ہے۔ آرڈر آتے ہی fulfillment hold لگائیں۔ Confirm، Change address اور Cancel بٹنوں والا ٹیمپلیٹ بھیجیں، اور hold صرف تصدیق شدہ جواب پر ہٹائیں۔ جواب نہ آئے تو آرڈر call queue میں جاتا ہے، کبھی خودکار منسوخی میں نہیں۔
عام Confirm اور Cancel چکر، ہر بٹن کے payloads اور context.id پر matching کے ساتھ، Confirm اور Cancel بٹنوں کے ساتھ WhatsApp پر آرڈر کی تصدیق میں ہے۔ یہ صفحہ اس کے اوپر وہ شامل کرتا ہے جو cash on delivery کو چاہیے: Shopify میں dispatch روکنا، پتہ بدلنا، اور کسی شخص تک واپسی کا راستہ۔ Shopify کا webhook معاہدہ اور token Shopify order webhooks سے WhatsApp میں ہیں۔
پیغام utility کیوں شمار ہوتا ہے
Meta کا order management objective کہتا ہے: «مخصوص آرڈر یا transaction کی تفصیلات استعمال کرتے ہوئے کسٹمر کے ساتھ کسی آرڈر یا transaction کی تصدیق، اپ ڈیٹ یا منسوخی»۔ اس کی مثال ہے “Your order {{order_number}} is confirmed. We will let you know once your package is on its way” (template categorization، رسائی 2026-11-27)۔
COD چیک اس objective میں آتا ہے۔ خریدار نے ابھی آرڈر دیا ہے، اور پیغام اس کا نمبر، رقم اور پتہ بتاتا ہے۔ Meta کا صفحہ کہیں “cash on delivery”، “COD”، “address” یا “verification” کا ذکر نہیں کرتا، اس لیے یہ مطابقت order management کے ذریعے ہے، کسی نامزد قاعدے کے ذریعے نہیں۔
Body سادہ رکھیں۔ Meta «promo کے ساتھ آرڈر اپ ڈیٹ» کو mixed content سمجھتی ہے، جو اسے مارکیٹنگ بنا دیتا ہے۔ پیشگی ادائیگی پر رعایت، پروڈکٹ کی تجاویز اور review کی درخواست، ان میں سے کچھ بھی اس ٹیمپلیٹ میں نہیں ہونا چاہیے۔
Template Library میں تین ملتے جلتے use cases ہیں: ORDER_CONFIRMATION، ORDER_ACTION_NEEDED اور ORDER_OR_TRANSACTION_CANCEL۔ Meta کا صفحہ ان کا body text نہیں دکھاتا۔ آپ انہیں GET /message_template_library?topic=ORDER_MANAGEMENT&industry=E_COMMERCE سے دیکھ سکتے ہیں (Template Library، رسائی 2026-11-27)۔ یہ صفحہ custom ٹیمپلیٹ استعمال کرتا ہے، کیونکہ اسے تین quick replies چاہییں۔
Shopify میں COD آرڈر پہچانیں
orders/create پر subscribe کریں، جسے «ان میں سے کم از کم ایک scope درکار ہے: read_orders، read_marketplace_orders»۔ پھر آرڈر سے paymentGatewayNames پڑھیں۔ Shopify اسے «آرڈر میں استعمال ہونے والے تمام payment gateways کے ناموں کی فہرست» بتاتا ہے، اور اس کی مثالیں “Shopify Payments” اور “Cash on Delivery (COD)” ہیں (Order object، رسائی 2026-11-27)۔
Shopify کا صفحہ یہ نہیں بتاتا کہ merchant اس gateway کا نام بدل سکتا ہے یا نہیں۔ سروس ایک قابلِ ترتیب string، COD_GATEWAY، پر match کرتی ہے، جس کا default، Shopify کی مثال ہے۔ Live ہونے سے پہلے ایک test COD آرڈر دیں اور value چیک کریں۔
اگر آپ WooCommerce چلاتے ہیں تو اس کا COD صفحہ کہتا ہے: «WooCommerce، COD استعمال کرنے والے آرڈرز کا status ادائیگی وصول ہونے تک Processing رکھتا ہے» (cash on delivery، رسائی 2026-11-27)۔ صفحہ کوئی gateway ID نہیں بتاتا۔ payment_method کی ممکنہ value cod ہے، لیکن اسے test آرڈر پر چیک کریں۔ Woo کی signing اور write-back WooCommerce آرڈر status، WhatsApp پر میں ہیں۔
کچھ بھی بھیجنے سے پہلے dispatch روکیں
پہلے آرڈر روکیں، ورنہ خریدار ابھی پڑھ رہا ہو گا اور warehouse مال بھیج دے گا۔ آرڈر کے ہر fulfillment order پر fulfillmentOrderHold سے hold لگائیں۔ یہ fulfillment order کی id اور ایک fulfillmentHold input لیتا ہے، جس میں reason، reasonNotes، notifyMerchant اور handle ہیں (fulfillmentOrderHold، رسائی 2026-11-27)۔ Shopify کے نمونہ response میں "status":"ON_HOLD" ہے۔
اس mutation کو write_merchant_managed_fulfillment_orders یا write_third_party_fulfillment_orders درکار ہے۔ Token کے پیچھے والے user کے پاس fulfill اور ship orders کی permission بھی ہونی چاہیے۔ handle دینے سے آپ کے hold کا نام بنتا ہے، اور Shopify ایک fulfillment order پر اسی handle والا دوسرا hold رد کر دیتا ہے۔
Shopify کے FulfillmentHoldReason enum میں کسٹمر کی زیرِ التوا تصدیق کے لیے کوئی value نہیں (FulfillmentHoldReason، رسائی 2026-11-27)۔ OTHER استعمال کریں، اور reasonNotes کو “Awaiting WhatsApp COD confirmation” پر سیٹ کریں۔ INCORRECT_ADDRESS بھی موجود ہے، اگر آپ خریدار کے پتہ بدلنے کی درخواست پر دوسرا hold چاہیں۔
fulfillmentOrderReleaseHold(id, holdIds, externalId) سے hold ہٹائیں۔ Shopify لکھتا ہے: «سختی سے تجویز کیا جاتا ہے کہ apps ان holds کی ids دیں جنہیں وہ ہٹانا چاہتی ہیں» (fulfillmentOrderReleaseHold، رسائی 2026-11-27)۔ سروس اپنے بنائے ہوئے ہر hold کی ID محفوظ کرتی ہے اور صرف وہی ہٹاتی ہے۔
ٹیمپلیٹ اور اس کا time-to-live
تین quick replies والا ایک custom UTILITY ٹیمپلیٹ بنائیں۔ Meta کا TTL صفحہ utility کی حد «30 سیکنڈ سے 12 گھنٹے» بتاتا ہے، جو ٹیمپلیٹ بناتے وقت message_send_ttl_seconds سے سیٹ ہوتی ہے (time-to-live، رسائی 2026-11-27)۔ وہ صفحہ ہر send پر الگ TTL کا کوئی طریقہ نہیں دکھاتا، اس لیے ایک ایسا TTL چنیں جو آپ کے سب سے پہلے dispatch cutoff سے پہلے ختم ہو۔ نیچے والا code 6 گھنٹے استعمال کرتا ہے۔
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" }
]
}
]
}'
اسے صرف ان خریداروں کو بھیجیں جنہوں نے ایسا WhatsApp opt-in دیا ہو جس میں آپ کے store کا نام ہو۔ Shopify کی SMS consent شمار نہیں ہوتی۔ Opt-in کے بغیر COD خریدار سیدھا call queue میں جاتا ہے۔ سروس یہ opt-in whatsapp_order_updates نامی order note attribute سے پڑھتی ہے، جسے آپ کے cart یا checkout کو سیٹ کرنا ہو گا۔
تین جوابات اور ان کے write-backs
ٹیپ، type: "button"، button.payload، button.text اور ٹیمپلیٹ کی message ID کے برابر context.id کے ساتھ messages webhook کے طور پر آتا ہے (button webhook، رسائی 2026-11-27)۔ سروس ہر payload کو cod_confirm:<order_id>، cod_address:<order_id> یا cod_cancel:<order_id> پر سیٹ کرتی ہے، اور label پر واپس جاتی ہے۔
| ٹیپ | Shopify write-back | Hold |
|---|---|---|
| Confirm order (آرڈر کی تصدیق) | cod-confirmed کے ساتھ tagsAdd |
ہٹا دیا جاتا ہے |
| Change address (پتہ بدلیں) | cod-address-change-requested کے ساتھ tagsAdd، پھر کسی شخص کے نیا پتہ چیک کرنے پر orderUpdate |
پتہ اپ ڈیٹ ہونے تک برقرار |
| Cancel order (آرڈر منسوخ کریں) | ونڈو میں دوسری تصدیق کے بعد orderCancel اور cod-cancelled |
منسوخی کے بعد غیر متعلق |
| Deadline تک کوئی جواب نہیں | cod-no-reply کے ساتھ tagsAdd، اور آرڈر call queue میں |
برقرار |
پتہ بدلنا
ٹیپ ایک کسٹمر سروس ونڈو کھول دیتا ہے، اس لیے آپ سادہ text میں نیا پتہ مانگ سکتے ہیں۔ کوئی شخص جواب پڑھتا ہے اور structured پتہ درج کرتا ہے۔ پھر سروس orderUpdate(input: {id, shippingAddress}) کال کرتی ہے، جسے write_orders درکار ہے (orderUpdate، رسائی 2026-11-27)۔ صرف id اور shippingAddress بھیجیں، کیونکہ اس input پر tags اور note موجودہ value کو overwrite کر دیتے ہیں۔
Shopify کا صفحہ یہ نہیں بتاتا کہ پتے کی تبدیلی صرف unfulfilled آرڈرز تک محدود ہے یا نہیں۔ Hold آرڈر کو unfulfilled رکھتا ہے، لیکن ایسے آرڈر پر پتے کی تبدیلی test کریں جس کے fulfillment orders، hold پر ہوں۔
Meta کا address_message چیٹ میں structured پتہ جمع کر سکتا ہے۔ اس کا صفحہ کہتا ہے: «یہ feature صرف بھارت میں قائم بزنسز اور ان کے بھارتی کسٹمرز کے لیے دستیاب ہے» (address messages، رسائی 2026-11-27)۔ جواب interactive.type: "nfm_reply" کے طور پر آتا ہے، جس میں response_json ایک JSON string ہے۔ دوسری جگہوں پر پتے کے فارم والا Flow، structured آپشن ہے، جس کی تفصیل WhatsApp Flows میں ہے۔
منسوخی
پہلے ٹیپ پر منسوخ نہ کریں۔ ونڈو کے اندر reply buttons کے ساتھ ایک بار اور پوچھیں: “Yes, cancel” (ہاں، منسوخ کریں) اور “Keep my order” (میرا آرڈر رہنے دیں)۔ یہ جواب interactive.button_reply.{id, title} کے ساتھ type: "interactive" کے طور پر آتا ہے۔ Meta کا نمونہ {"id":"cancel-button","title":"Cancel"} ہے (interactive webhook، رسائی 2026-11-27)۔
پھر orderCancel(orderId, reason: CUSTOMER, restock: true, notifyCustomer: false, staffNote) کال کریں۔ یہ ایک job کے طور پر چلتا ہے، اس لیے job { id done } کو poll کریں۔ Errors، orderCancelUserErrors میں آتی ہیں، اور Shopify خبردار کرتا ہے: «یہ عمل واپس نہیں ہو سکتا» (orderCancel، رسائی 2026-11-27)۔ غیر ادا شدہ COD آرڈر میں refund کرنے کو کچھ نہیں، اس لیے سروس کوئی refundMethod نہیں بھیجتی۔
مکمل سروس
یہ Node 18+ فائل npm install express کے ساتھ چلتی ہے۔ یہ دونوں webhooks verify کرتی ہے، X-Shopify-Webhook-Id اور Meta کی message IDs پر dedupe کرتی ہے، اور ہر آرڈر کو شرطیہ حالت کی تبدیلیوں سے آگے بڑھاتی ہے۔ ADMIN_KEY سے محفوظ دو admin routes کسی شخص کو چیک شدہ پتہ یا فون پر ملی تصدیق درج کرنے دیتے ہیں۔ مثال کے لیے state، memory میں ہے۔
// 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}`));
خریدار کا ٹائپ کیا ہوا پتہ جان بوجھ کر کسی شخص کے پاس جاتا ہے۔ آزاد text والے پتے اتنے مختلف ہوتے ہیں کہ انہیں بغیر پڑھے آرڈر میں نہیں لکھا جا سکتا۔ اگر آپ پتے کے لیے Flow بنائیں تو اس کا جواب آزاد text اور admin route دونوں کی جگہ لے لیتا ہے۔
جب کوئی جواب نہ دے
COD آرڈر کو اس لیے کبھی منسوخ نہ کریں کہ خریدار نے ٹیپ نہیں کیا۔ فون بند ہو سکتا ہے، خریدار پیغام نہیں دیکھ پاتا، یا ٹیمپلیٹ ناکام ہو سکتا ہے۔ Deadline پر سروس آرڈر پر cod-no-reply tag لگاتی ہے، اسے call queue میں ڈالتی ہے اور hold برقرار رکھتی ہے۔ ٹیمپلیٹ پر failed status فوراً یہی کرتا ہے۔
Call queue چلانا آپ کا کام ہے۔ کوئی شخص خریدار کو فون کر کے confirmed-by-call route استعمال کر سکتا ہے، یا Shopify admin میں منسوخ کر سکتا ہے۔ اگر آپ چاہتے ہیں کہ کال WhatsApp سے شروع ہو تو Meta کے calling آپشن کی تفصیل WhatsApp Business Calling API میں ہے۔
دیر سے آنے والا ٹیپ بھی کام کرتا ہے۔ call_queue میں موجود آرڈر، Confirm، Change address اور Cancel قبول کرتا ہے، اس لیے deadline کے بعد جواب دینے والا خریدار واپس نہیں لوٹایا جاتا۔ Queue پر کام کرنے والا شخص کال سے پہلے آرڈر کے tags چیک کرے۔
Duplicates، retries اور وقت
Shopify ناکام delivery کو 4 گھنٹوں میں 8 بار retry کرتا ہے (HTTPS webhooks، رسائی 2026-11-27)۔ X-Shopify-Webhook-Id کا چیک دہرائی گئی deliveries روکتا ہے، اور orders.has(gid) اسی آرڈر کی دوسری delivery روکتا ہے۔ Meta بھی retry کرتی ہے، اس لیے سروس messages[].id پر dedupe کرتی ہے۔ ہر حالت کی تبدیلی شرطیہ ہے، اس لیے دوسرے Confirm کو دوسری release کی بجائے ایک مختصر جواب ملتا ہے۔
اگر hold ناکام ہو یا کوئی hold نہ لگے تو ٹیمپلیٹ پھر بھی جاتا ہے، اور کسی شخص کو hold_failed یا no_hold_placed والی log line نظر آتی ہے۔ Warehouse جواب آنے سے پہلے مال بھیج سکتا ہے، اس لیے اس line کو فوری سمجھیں۔
Deadline اور TTL مل کر کام کرتے ہیں۔ 6 گھنٹے کے TTL اور 6 گھنٹے کی deadline کے ساتھ، ڈیلیور نہ ہونے والا ٹیمپلیٹ تقریباً اسی وقت ختم ہوتا ہے جب آرڈر call queue میں پہنچتا ہے۔ TTL کی وجہ سے drop ہونے والے پیغام کے لیے Meta کوئی error code نہیں بتاتی۔ اگر آپ کا dispatch cutoff چھ گھنٹے سے کم دور ہے تو دونوں کم کریں۔
ٹیمپلیٹ یا منسوخی کا سوال ترجمہ کرنے سے پہلے دونوں قسم کے بٹنوں کے labels کی لمبائی چیک کریں۔ حدیں interactive buttons اور list messages میں ہیں۔
Z-API Omni کہاں کام آتا ہے
Omni کی کوئی دستاویزی Shopify یا WooCommerce integration یا scheduler نہیں، اس لیے hold، deadline اور call queue آپ کی سروس میں رہتے ہیں۔ Meta کی آفیشل API پر اس کا custom-model صفحہ UTILITY ٹیمپلیٹ کا quick_reply payload component دکھاتا ہے، اور message_send_ttl_seconds utility کے لیے 30 سے 43200 قبول کرتا ہے۔ Flows (INTERACTIVE_FLOW، صرف Meta) پتے کے فارم کے لیے ایک دستاویزی FORM_RESPONSE واپس کرتے ہیں۔ بٹن ٹیپ کی inbound شکل دستاویزی نہیں۔
QR connection پر INTERACTIVE_BUTTON میں تین تک بٹن آتے ہیں، اس لیے تینوں انتخاب پورے آ جاتے ہیں۔
{
"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" }
]
}
}
منقطع channel، subCode: CHANNEL_DISCONNECTED کے ساتھ 422 واپس کرتا ہے، اور پیغام بعد میں بھیجنے کے لیے رکھا نہیں جاتا، اس لیے کال queue کریں۔ ایک subscription میں WhatsApp، Messenger، Instagram اور Telegram شامل ہیں، 1 سے 10 نمبروں کے لیے US$29 فی نمبر ماہانہ، جو 100 سے زیادہ پر US$20 تک آ جاتی ہے۔ QR connection پر فی پیغام کوئی لاگت نہیں، اور Meta کی آفیشل API پر Meta کی فیس آگے منتقل ہوتی ہے۔
Z-API Omni ٹیم