orders/create اور fulfillments/create پر subscribe کریں، raw body پر X-Shopify-Hmac-Sha256 verify کریں، اور پانچ سیکنڈ کے اندر 200 جواب دیں۔ پھر WhatsApp utility ٹیمپلیٹ بھیجیں، لیکن صرف ان کسٹمرز کو جنہوں نے WhatsApp opt-in دیا ہو۔ Shopify کی SMS marketing consent ایک الگ چیز ہے۔ جب کسٹمر کسی جواب پر ٹیپ کرے تو اسے tagsAdd سے ریکارڈ کریں۔ orderCancel صرف اس آرڈر کے لیے کال کریں جس کا کچھ بھی fulfill نہ ہوا ہو۔
جواب کا چکر خود Confirm اور Cancel بٹنوں کے ساتھ WhatsApp پر آرڈر کی تصدیق میں ہے۔ وہ مضمون ہر بٹن کے payloads، context.id پر matching، شرطیہ حالت کی تبدیلی اور خاموشی کی صورت میں کیا کریں، کا احاطہ کرتا ہے۔ WooCommerce والا ورژن WooCommerce آرڈر status، WhatsApp پر میں ہے۔ یہ صفحہ وہ بتاتا ہے جو Shopify اضافہ کرتا ہے: اس کا webhook معاہدہ، فون اور consent کے fields، token، اور write-back mutations۔
Shopify کیا بھیجتا ہے اور کتنی بار
ہر delivery میں کچھ headers ہوتے ہیں جو آپ کو استعمال کرنے چاہئیں۔ Shopify نوٹ کرتا ہے کہ HTTP/2 اکثر انہیں چھوٹے حروف میں کر دیتا ہے، اس لیے انہیں case-insensitive طریقے سے پڑھیں (delivery structure، رسائی 2026-11-25)۔
| Header | کس کام کے لیے |
|---|---|
X-Shopify-Topic |
routing، مثلاً orders/create |
X-Shopify-Hmac-Sha256 |
Base64 HMAC signature، صرف HTTPS |
X-Shopify-Shop-Domain |
store کا myshopify.com domain |
X-Shopify-API-Version |
وہ version جس نے payload بنایا |
X-Shopify-Webhook-Id |
«ہر delivery کی ایک منفرد composite key»۔ اسی پر dedupe کریں |
X-Shopify-Event-Id |
merchant کے ایک عمل سے ہونے والی تمام deliveries میں مشترک |
signature، raw body کا HMAC-SHA256 ہے، جس کی key آپ کی app کا client secret ہے اور جو base64 میں encode ہوتا ہے (HTTPS webhooks، رسائی 2026-11-25)۔ کسی JSON parser کے body کو چھونے سے پہلے اسے compute کریں، اور timing-safe function سے موازنہ کریں۔
Shopify ایک سیکنڈ کا connection timeout دیتا ہے اور «پوری request کے لیے پانچ سیکنڈ کا timeout»۔ صرف 200 کامیابی شمار ہوتا ہے، اور 3XX ایک error ہے۔ ناکامی کے بعد Shopify «اگلے 4 گھنٹوں میں 8 بار retry کرتا ہے»۔ مسلسل 8 ناکامیوں کے بعد Admin API سے بنائی گئی subscription خود بخود delete ہو جاتی ہے، اور app کے emergency developer address پر email جاتی ہے۔ request کے اندر WhatsApp کی سست call آپ کی پوری subscription ختم کروا سکتی ہے۔
Shopify کا webhooks overview خبردار کرتا ہے: «آپ کی app کو ایک ہی webhook ایک سے زیادہ بار مل سکتا ہے»۔ یہ یہ بھی کہتا ہے: «Shopify کسی topic کے اندر، یا ایک ہی resource کے مختلف topics کے درمیان، ترتیب کی ضمانت نہیں دیتا» (webhooks overview، رسائی 2026-11-25)۔ ایسی صورت کے لیے تیار رہیں جب کسی آرڈر کا fulfillments/create، اسی آرڈر کے orders/create سے پہلے آ جائے۔ اسی صفحے کے مطابق «webhook delivery کی ہمیشہ ضمانت نہیں»، اس لیے ایک reconciliation job چلائیں جو حالیہ آرڈرز کی فہرست لے۔
آرڈر سے پڑھے جانے والے fields
Shopify کے orders/create reference کا نمونہ دکھاتا ہے کہ چیزیں کہاں ہیں (webhook topics، رسائی 2026-11-25)۔ یہ Shopify کے reference کی نمونہ values ہیں، کوئی اصل آرڈر نہیں:
admin_graphql_api_id: "gid://shopify/Order/820982911946154508"وہ ID ہے جو آپ کی mutations کو چاہیے۔name: "#9999"وہ ہے جو کسٹمر دیکھتا ہے، اورtotal_price: "404.95"کے ساتھcurrency: "USD"کل رقم ہے۔phone: nullاورcustomer.phone: null، جبکہshipping_address.phoneاورbilling_address.phoneمیں"555-555-SHIP"ہے۔note_attributes: []،tags: "tag1, tag2"اورfulfillment_status: null۔
fulfillments/create کے نمونے میں name: "#9999.1"، order_id، status: "pending" اور tracking_company: "UPS" ہیں۔ اس میں واحد فون destination.phone ہے۔ اس کی بجائے وہ نمبر رکھیں جو آپ نے orders/create سے محفوظ کیا تھا۔
فون نمبر آزاد text ہیں
وہ "555-555-SHIP" value یاد دلاتی ہے کہ Shopify کے فون fields میں text بھی آ سکتا ہے۔ بھیجنے سے پہلے country code کے ساتھ ہندسوں میں normalize کریں، اور جو نمبر normalization میں نہ بچیں انہیں چھوڑ دیں۔ قواعد WhatsApp فون نمبر format میں ہیں۔
protected customer data بھی فون کو چھپا سکتا ہے۔ Shopify «name، address، phone یا email fields» کو level 2 پر رکھتا ہے، جنہیں ایک ایک field کر کے مانگا جاتا ہے۔ غیر منظور شدہ fields «redact کر دیے جائیں گے» (protected customer data، رسائی 2026-11-25)۔ custom apps کے لیے levels 1 اور 2 «ہمیشہ دستیاب» ہیں، اور public apps کو review درکار ہے۔ Shopify کا صفحہ یہ نہیں بتاتا کہ webhook payload کے اندر redaction کیسی دکھتی ہے۔ فون field مانگیں اور اس پر کچھ بنانے سے پہلے ایک test delivery چیک کریں۔
WhatsApp consent، Shopify کی SMS consent نہیں
Shopify کا smsMarketingConsent «اس بات کا ریکارڈ ہے کہ کسٹمر نے کب SMS کے ذریعے marketing مواد وصول کرنے کی رضامندی دی» (CustomerSmsMarketingConsentState، رسائی 2026-11-25)۔ یہ SMS marketing کی رضامندی ہے۔ اس سے یہ پتہ نہیں چلتا کہ کسٹمر WhatsApp پر آرڈر اپ ڈیٹس کے لیے راضی ہے، اس لیے اسے دوبارہ استعمال نہ کریں۔
Shopify کی checkout settings بھی دونوں کو الگ رکھتی ہیں۔ SMS marketing checkbox «checkout پر پہلے سے منتخب نہیں ہو سکتا»، اور «یہ marketing opt-in، آرڈر کی تصدیق والی SMS notifications سے الگ سیٹنگ ہے» (checkout form options، رسائی 2026-11-25)۔ Shopify کا اپنا SMS آرڈر کی ایک تصدیق صرف تب بھیجتا ہے «جب کوئی email address نہ ہو» (SMS notifications، رسائی 2026-11-25)۔
Shopify میں WhatsApp consent کا کوئی field نہیں، اس لیے اپنا بنائیں۔ theme کا cart attribute، جیسے name="attributes[whatsapp_order_updates]"، سب سے آسان ہے (cart template، رسائی 2026-11-25)۔ اسے آرڈر کے note_attributes میں آنا چاہیے، جسے نیچے والا code پڑھتا ہے، لیکن یہ mapping test نہیں ہوئی۔ دوسرا راستہ checkout UI extension ہے، اور وہاں Attributes API کو cart metafields کے حق میں deprecate کر دیا گیا ہے۔ WhatsApp opt-in کے قواعد کے مطابق label میں store کا نام ہو اور «WhatsApp پر آرڈر اپ ڈیٹس» لکھا ہو۔ اگر opt-in موجود نہ ہو تو کچھ نہ بھیجیں۔
2026 میں Admin API token حاصل کریں
Shopify نے 2026-01-01 کے بعد admin میں بنائی جانے والی نئی custom apps کی اجازت بند کر دی، اس لیے app کو Dev Dashboard میں بنائیں (changelog، شائع 2025-10-30، رسائی 2026-11-25)۔ جب app اور store ایک ہی organization میں ہوں تو client credentials grant استعمال کریں (client credentials، رسائی 2026-11-25)۔
یہ grant ایک form-encoded POST https://{shop}.myshopify.com/admin/oauth/access_token ہے، grant_type=client_credentials، client_id اور client_secret کے ساتھ۔ response میں access_token، scope اور expires_in: 86399 ہوتے ہیں۔ «Tokens، 24 گھنٹے بعد expire ہو جاتے ہیں»، اس لیے token کو cache کریں اور expiry سے پہلے refresh کریں۔ 2026-12-01 سے نئی custom apps کو expire ہونے والے offline tokens استعمال کرنے ہوں گے، اور client credentials والے tokens پہلے ہی اس پر پورا اترتے ہیں (changelog، رسائی 2026-11-25)۔
دو ٹیمپلیٹس، دونوں utility
orders/create پر آرڈر کی تصدیق والے مضمون کا order_confirm_v1 ٹیمپلیٹ بھیجیں۔ Template Library میں اس کا مماثل ORDER_CONFIRMATION ہے۔ fulfillments/create پر روانگی کی اطلاع بھیجیں، جس کا library مماثل SHIPMENT_CONFIRMATION ہے۔ دونوں کو discount codes اور مصنوعات کی تجاویز سے پاک رکھیں، کیونکہ Meta، promo والی آرڈر اپ ڈیٹ کو مارکیٹنگ مانتا ہے (template categorization، رسائی 2026-11-25)۔ یہی تقسیم دکان کے دوسرے پیغامات پر بھی لاگو ہوتی ہے: abandoned checkout کی بحالی اور back-in-stock alerts مارکیٹنگ ہیں، جبکہ cash-on-delivery کی تصدیق اور return اور refund اپ ڈیٹس utility رہتی ہیں۔
tracking لنک، {{1}} suffix والے URL بٹن میں جاتا ہے۔ یہاں یہ آپ کے اپنے domain پر ایک tracking صفحے کی طرف جاتا ہے، جس کی key آرڈر ID ہے۔ suffix کے قواعد dynamic suffix والے ٹیمپلیٹ URL بٹن میں ہیں۔
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"] }
]
}
]
}'
جواب کو آرڈر پر واپس لکھیں
کسٹمر نے کیا چنا، یہ ریکارڈ کرنے کے لیے tagsAdd استعمال کریں۔ یہ «کسی resource میں tags شامل کرتا ہے»، آرڈرز کو سپورٹ کرتا ہے، اور node { id } اور userErrors واپس کرتا ہے (tagsAdd، رسائی 2026-11-25)۔ صفحہ اس کے scopes درج نہیں کرتا۔ غالباً write_orders ہے، اس لیے اپنی app پر چیک کر لیں۔
اس کام کے لیے orderUpdate سے بچیں۔ اس کا OrderInput.note «موجودہ note کو overwrite کر دیتا ہے»، اور tags «موجودہ tags کو overwrite کر دیتا ہے» (OrderInput، رسائی 2026-11-25)۔ merchant کا packing note غائب ہو جائے گا۔ اگر note کو چھونا ہی ہو تو پہلے اسے پڑھیں اور آخر میں اضافہ کریں۔
صرف وہی منسوخ کریں جو Shopify منسوخ کر سکتا ہے
orderCancel لازمی arguments کے طور پر orderId، reason اور restock لیتا ہے، ساتھ optional notifyCustomer (default false) اور زیادہ سے زیادہ 255 حروف کا staffNote (orderCancel، رسائی 2026-11-25)۔ منسوخی «واپس نہیں ہو سکتی»۔ یہ ایک job کے طور پر چلتی ہے، اس لیے job { id done } کو تب تک poll کریں جب تک done، true نہ ہو۔
Shopify منسوخی سے انکار کرتا ہے جب آرڈر پہلے سے منسوخ ہو، اس پر pending payment authorizations یا active returns ہوں، یا ایسی باقی fulfillments ہوں جو منسوخ نہیں ہو سکتیں۔ غیر فعال location پر restock آن کے ساتھ ادا شدہ آرڈر بھی ناکام ہوتا ہے۔ سروس ہر Cancel ٹیپ پر whatsapp-cancel-requested tag لگاتی ہے۔ یہ orderCancel(reason: CUSTOMER, restock: true, notifyCustomer: false) صرف تب کال کرتی ہے جب کچھ بھی fulfill نہ ہوا ہو۔ notifyCustomer: false ہمارا انتخاب ہے، تاکہ کسٹمر کو آپ کے WhatsApp جواب کے اوپر Shopify کی email نہ ملے۔ سروس کوئی refundMethod نہیں بھیجتی۔ Shopify کہتا ہے: «Authorized payments اس سیٹنگ سے قطع نظر void ہو جائیں گی»، اس لیے کوئی بھی captured payment ایک شخص چیک کرتا ہے۔
مکمل سروس
یہ Node 18+ فائل npm install express کے بعد چلتی ہے۔ یہ دونوں webhooks verify کرتی ہے، X-Shopify-Webhook-Id اور Meta کی message ID پر dedupe کرتی ہے، اور Admin GraphQL API، version 2026-10، کے ذریعے واپس لکھتی ہے۔ مثال کے لیے state، memory میں ہے۔ maps کی جگہ tables لگائیں۔
// 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}`));
X-Shopify-Webhook-Id کا چیک دہرائی گئی deliveries روکتا ہے۔ orders.has(gid) کا چیک اسی آرڈر کی ایسی دوسری delivery بھی روکتا ہے جس کی delivery ID مختلف ہو۔ Meta والا حصہ X-Hub-Signature-256 verification کے مطابق ہے۔ status handler، جواب نہ آنے کا sweep اور TTL کی handling آرڈر کی تصدیق والے مضمون سے لیں۔ یہاں انہیں شامل نہیں کیا گیا۔
جب کچھ ناکام ہو
اگر WhatsApp send کوئی error دے تو وہ کسی شخص کے پاس جاتی ہے۔ Shopify delivery کو پہلے ہی 200 مل چکا ہے، اس لیے Shopify دوبارہ retry نہیں کرے گا۔ یہ جان بوجھ کر ہے، کیونکہ retry ٹیمپلیٹ دوبارہ بھیج دے گا۔ اگر آپ کا endpoint ہی بند ہو جائے تو Shopify چار گھنٹے تک retry کرتا ہے، اور dedupe دہرائی گئی deliveries کو سنبھال لیتا ہے۔
اگر orderCancel، orderCancelUserErrors واپس کرے تو آرڈر whatsapp-cancel-requested tag کے ساتھ کھلا رہتا ہے، اور کوئی شخص اسے سنبھالتا ہے۔ آرڈر کی تصدیق کے بعد آنے والے ٹیپ کو ایک مختصر جواب ملتا ہے اور کوئی write-back نہیں ہوتا۔
Admin GraphQL API، query cost کے حساب سے حساب لگاتی ہے۔ Shopify کا نمونہ 1,000 points کی ایک bucket دکھاتا ہے جو 50 points فی سیکنڈ کی رفتار سے بحال ہوتی ہے (Admin GraphQL، رسائی 2026-11-25)۔ اوپر والی job polling ہر منسوخی پر دس queries کے بعد رک جاتی ہے، اور اگر job ابھی چل رہی ہو تو آرڈر کسی شخص کے حوالے کر دیتی ہے۔
Z-API Omni کہاں کام آتا ہے
Omni کی کوئی دستاویزی Shopify integration نہیں، اس لیے اوپر جیسی سروس ہی bridge رہتی ہے۔ آپ یہی ٹیمپلیٹ POST https://api.omni.z-api.io/v1/channels/{channelId}/messages سے، Bearer Secret Key کے ساتھ بھیجتے ہیں۔ اس کے docs، quick reply کا payload component دکھاتے ہیں، لیکن ابھی ٹیپ کی inbound شکل نہیں۔ اس کے webhooks پانچ سیکنڈ کے اندر 2xx کی توقع کرتے ہیں، تقریباً 23 گھنٹوں میں چھ بار retry کرتے ہیں، اور dedupe کے لیے x-webhook-delivery-id ساتھ لاتے ہیں۔ ایک subscription میں WhatsApp، Messenger، Instagram اور Telegram شامل ہیں، 1 سے 10 نمبروں کے لیے US$29 فی نمبر ماہانہ، جو 100 سے زیادہ پر US$20 تک آ جاتی ہے۔ QR connection پر فی پیغام کوئی لاگت نہیں۔ Meta کی آفیشل API پر Meta کی فیس آگے منتقل ہوتی ہے۔
Z-API Omni ٹیم