Return status اپ ڈیٹ ایک utility ٹیمپلیٹ ہے جو کسٹمر کو بتاتا ہے کہ اس کا return کس مرحلے پر ہے: requested، approved، declined یا refunded۔ Shopify میں returns/request، returns/approve، returns/decline، returns/close اور refunds/create پر subscribe کریں۔ ان payloads میں صرف ids ہوتی ہیں، اس لیے فون حاصل کرنے کے لیے GraphQL سے Return اور اس کا آرڈر query کریں۔ Approval پر دو quick replies والا custom UTILITY ٹیمپلیٹ بھیجیں: “Refund to card” (card پر refund) اور “Store credit” (store credit)۔ ٹیپ کو اپنی returns table میں محفوظ کریں، tagsAdd سے آرڈر پر tag لگائیں، اور returnProcess کال کرتے وقت یہ انتخاب لاگو کریں۔
Webhook کا معاہدہ، HMAC چیک اور access token وہی ہیں جو Shopify order webhooks سے WhatsApp میں ہیں، اس لیے یہ صفحہ انہیں دہرانے کی بجائے link دیتا ہے۔ ٹیپ ملانے کی منطق Confirm اور Cancel بٹنوں کے ساتھ آرڈر کی تصدیق سے آتی ہے۔
Return کے لیے Shopify کون سے events بھیجتا ہے
Shopify یہ return topics درج کرتا ہے: returns/request، returns/approve، returns/decline، returns/process، returns/close، returns/cancel، returns/update، returns/reopen، اور ساتھ refunds/create اور دو reverse-logistics topics (Apps in returns، رسائی 2026-11-27)۔ «Return webhooks صرف GraphQL Admin API میں دستیاب ہیں»، version 2023-01 سے۔ اسی صفحے کے مطابق «آپ صرف وہی items واپس کر سکتے ہیں جو fulfill ہو چکے ہوں»، اس لیے return ہمیشہ fulfillment کے بعد آتا ہے۔
چکر ان topics پر چلتا ہے:
| Topic | Payload میں status | آپ کیا بھیجتے ہیں |
|---|---|---|
returns/request |
requested |
return_requested_v1، بغیر بٹنوں کے |
returns/approve |
open |
return_approved_v1، دونوں quick replies کے ساتھ |
returns/decline |
declined |
return_declined_v1، بغیر بٹنوں کے |
returns/close |
closed |
کچھ نہیں۔ اپنا record بند کریں |
refunds/create |
کوئی نہیں | return_refunded_v1، اگر آپ کی اپنی سروس پہلے ہی نہ بھیج چکی ہو |
Shopify کے webhook reference (رسائی 2026-11-27) میں returns/request کا نمونہ یوں دکھتا ہے۔ یہ Shopify کی نمونہ values ہیں:
{
"id": 123134564567890,
"admin_graphql_api_id": "gid://shopify/Return/123134564567890",
"status": "requested",
"order": { "id": 4783296544821, "admin_graphql_api_id": "gid://shopify/Order/4783296544821" },
"total_return_line_items": 2,
"name": null,
"return_line_items": [],
"return_shipping_fees": [],
"exchange_line_items": [],
"total_exchange_line_items": 0,
"requested_at": "2026-01-15T07:00:00-05:00"
}
returns/decline میں decline: { reason, note } شامل ہوتا ہے، اور Shopify کے نمونے کا note ہے: “As discussed on the phone, the 30-day return window has ended.” یہ آزاد text والا note کسی ٹیمپلیٹ variable میں نہ ڈالیں۔ ٹیمپلیٹ کے الفاظ مقرر رکھیں، اور اگر کسٹمر جواب دے تو کوئی شخص چیٹ میں انکار کی وجہ سمجھائے۔
returns/close چھوٹا ہے اور اس کی شکل مختلف ہے: { id, admin_graphql_api_id, order_id, status: "closed" }۔ اس میں order_id ہے، order object نہیں، اس لیے payload.order.id پڑھنے والا code اس پر ٹوٹ جاتا ہے۔ refunds/create کے نمونے میں refund کی id، اس کا order_id، ایک note، refund_line_items اور transactions ہیں۔ returns/process کا کوئی نمونہ دستیاب نہیں تھا۔
Payloads میں ids ہیں، فون نہیں
ان میں سے کسی payload میں فون، کسٹمر یا line items کی تفصیل نہیں۔ انہیں Return object پر ایک GraphQL query سے حاصل کریں، جسے «read_returns access scope یا read_marketplace_returns درکار ہے» (Return، رسائی 2026-11-27)۔ order { phone customer { defaultPhoneNumber { phoneNumber } } shippingAddress { phone } } پڑھیں اور پہلی قابلِ استعمال value کو normalize کریں، جیسا کہ فون نمبر format میں ہے۔ یہی query آپ کو returnLineItems بھی دیتی ہے، جو بعد میں returnProcess کو چاہییں۔
Shopify کے ReturnStatus enum میں پانچ values ہیں: REQUESTED، OPEN، DECLINED، CLOSED («return مکمل ہو چکا ہے») اور CANCELED (ReturnStatus، رسائی 2026-11-27)۔ returnApproveRequest کسی return کو OPEN پر لے جاتا ہے۔ returnProcess اسے بند کرتا ہے «جب تمام items process ہو جائیں اور restock کا فیصلہ ہو چکا ہو»۔
پیغامات: چار utility ٹیمپلیٹس
Return اپ ڈیٹس، Meta کا utility ٹیسٹ پاس کرتی ہیں۔ Meta ایسا مواد مانگتی ہے جو «غیر تشہیری» ہو، «صارف سے مخصوص یا اس کا مانگا ہوا» ہو اور «صارف کے لیے ضروری یا اہم» ہو (template categorization، رسائی 2026-11-27)۔ اس صفحے کی Order Management row میں refund کی ایک مثال بھی ہے: “We have received your item from order {{order_number}}. Your refund for ${{amount}} has been processed. Thank you for your business.”
یہی صفحہ «promo کے ساتھ آرڈر اپ ڈیٹ» کو مارکیٹنگ قرار دیتا ہے۔ اس لیے ان میں سے کسی ٹیمپلیٹ میں کبھی “دوبارہ خریداری کریں” والا coupon یا پروڈکٹ کی تجویز نہ ڈالیں۔ قواعد اور دوبارہ categorization کی قیمت ٹیمپلیٹ categories میں ہیں۔
Template Library میں ایک RETURN_CONFIRMATION use case ہے، اور library ٹیمپلیٹس کا UTILITY ہونا اور «مقررہ مواد جسے edit نہیں کیا جا سکتا» رکھنا لازمی ہے (Template Library، رسائی 2026-11-27)۔ Meta کا صفحہ اس type کی کوئی body نہیں دکھاتا۔ اسے ملتی جلتی library type سمجھیں اور custom ٹیمپلیٹس لکھیں، جیسا کہ WhatsApp Template Library میں بیان ہے۔
Approval والے پیغام کو مختصر TTL دیں۔ Utility ٹیمپلیٹس کا default 30 دن ہے، اور message_send_ttl_seconds 30 سے 43,200 سیکنڈ قبول کرتا ہے (time-to-live، رسائی 2026-11-27)۔ نیچے والے 12 گھنٹے ہمارا انتخاب ہیں؛ Meta کوئی value تجویز نہیں کرتی۔ “Refund کا طریقہ چنیں” والا سوال اگر کئی دن بعد پہنچے، جب staff return کو process کر چکا ہو، تو وہ کسٹمر کو صرف الجھاتا ہے۔
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": "return_approved_v1",
"category": "UTILITY",
"language": "en_US",
"parameter_format": "NAMED",
"message_send_ttl_seconds": 43200,
"components": [
{
"type": "BODY",
"text": "Hi {{customer_name}}, your return for order {{order_number}} is approved. How would you like your refund?",
"example": {
"body_text_named_params": [
{ "param_name": "customer_name", "example": "Ana" },
{ "param_name": "order_number", "example": "#1042" }
]
}
},
{
"type": "BUTTONS",
"buttons": [
{ "type": "QUICK_REPLY", "text": "Refund to card" },
{ "type": "QUICK_REPLY", "text": "Store credit" }
]
}
]
}'
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": "return_refunded_v1",
"category": "UTILITY",
"language": "en_US",
"parameter_format": "NAMED",
"components": [
{
"type": "BODY",
"text": "We have received your item from order {{order_number}}. Your refund of {{amount}} has been processed. Thank you for your business.",
"example": {
"body_text_named_params": [
{ "param_name": "order_number", "example": "#1042" },
{ "param_name": "amount", "example": "25.99 USD" }
]
}
}
]
}'
بغیر بٹنوں والے دونوں ٹیمپلیٹس بھی اسی طرح بنائیں۔ return_requested_v1 کا متن ہے “We got your return request for order {{order_number}}. We will message you here once it is reviewed.” return_declined_v1 کا متن ہے “Your return request for order {{order_number}} was not approved. Reply here and our team will explain the next step.” ان میں سے کوئی بھی صرف ان کسٹمرز کو بھیجیں جن کا WhatsApp opt-in ہو۔ Shopify کی SMS consent ایک الگ record ہے، جیسا کہ Shopify والا مضمون بتاتا ہے، اور opt-in کے قواعد WhatsApp opt-in کیسے جمع کریں میں ہیں۔
جواب: refund کے طریقے پر ٹیپ
بھیجتے وقت ہر quick reply کو ایک payload ملتا ہے، جیسے refund:card:123134564567890 یا refund:credit:123134564567890۔ ٹیپ، type: "button"، button.payload، button.text اور context.id کے ساتھ messages webhook کے طور پر آتا ہے، جہاں context.id ٹیمپلیٹ کا wamid ہے۔ context.id پر match کریں، کیونکہ جب صارف کا username ہو اور فون نمبر دستیاب نہ ہو تو Meta، from نہیں بھیجتی۔ پوری شکل آرڈر کی تصدیق والے مضمون میں ہے۔
ٹیپ 24 گھنٹے کی ونڈو کھول دیتا ہے، اس لیے “نوٹ کر لیا، store credit ہی ہو گا” والا جواب free-form text ہو سکتا ہے۔ جو کسٹمر اس کی بجائے کوئی سوال ٹائپ کرے وہ کسی شخص کے پاس جاتا ہے۔ جو کسٹمر ارادہ بدلے وہ دوبارہ ٹیپ کرتا ہے، اور return کے process ہونے تک آپ کی table میں آخری ٹیپ ہی مانا جاتا ہے۔
Write-back: آپ کی table، ایک tag، پھر returnProcess
Shopify میں refund کے پسندیدہ طریقے کا کوئی field نہیں۔ انتخاب اپنی returns table میں محفوظ کریں، جو وہ record ہے جسے آپ کا code بعد میں پڑھتا ہے۔ پھر tagsAdd سے آرڈر پر ایک tag لگائیں، مثلاً refund-pref:store-credit، تاکہ staff کو admin میں انتخاب نظر آئے۔ tagsAdd، orderUpdate کے برعکس، overwrite کیے بغیر شامل کرتا ہے، جیسا کہ Shopify والا مضمون دکھاتا ہے۔
Return process ہوتے وقت انتخاب لاگو کریں۔ returnProcess کو «write_returns access scope یا write_marketplace_returns درکار ہے» (returnProcess، رسائی 2026-11-27)۔ Shopify کی مثالی input، financialTransfer.issueRefund.orderTransactions کے ذریعے refund کرتی ہے، ہر ایک میں transactionAmount اور اصل OrderTransaction کی parentId کے ساتھ۔ Response میں returnProcess.return.id اور userErrors آتے ہیں۔
Store credit، refundMethods کے ذریعے جاتا ہے۔ ReturnProcessRefundInput میں orderTransactions (لازمی)، refundMethods اور allowOverRefunding ہیں (ReturnProcessRefundInput، رسائی 2026-11-27)۔ RefundMethodInput.storeCreditRefund ایک amount اور optional expiresAt لیتا ہے۔ Shopify نوٹ کرتا ہے کہ «store credit کے طور پر دیے گئے refunds ادا شدہ رقم سے زیادہ نہیں ہو سکتے»۔ Shopify store credit کی کوئی مکمل مثال نہیں دکھاتا، اس لیے سروس میں store credit والی body test نہیں ہوئی۔ خاص طور پر یہ test نہیں ہوا کہ Shopify خالی orderTransactions فہرست قبول کرتا ہے یا نہیں۔
notifyCustomer: false سیٹ کریں۔ true کے ساتھ Shopify کسٹمر کو email بھیجتا ہے، اور آپ کا WhatsApp پیغام انہیں دوسری بار بتائے گا۔
رقم staff کا فیصلہ رہتی ہے۔ معائنہ، restocking fees اور shipping سب اسے بدلتے ہیں، اس لیے سروس ایک internal endpoint دیتی ہے جسے آپ کا back office، return id اور رقم کے ساتھ کال کرتا ہے۔ کسٹمر کا ٹیپ طریقہ طے کرتا ہے، اور کوئی شخص رقم طے کرتا ہے۔ اگر کسٹمر نے کبھی ٹیپ نہیں کیا تو سروس اصل payment method پر refund کرتی ہے۔ یہ default ہمارا انتخاب ہے۔
مکمل سروس
یہ Node 18+ فائل npm install express کے ساتھ چلتی ہے۔ یہ دونوں webhook signatures verify کرتی ہے، deliveries، return events اور Meta پیغامات پر dedupe کرتی ہے، اور Admin GraphQL API، version 2026-10، کے ذریعے واپس لکھتی ہے۔ مثال کے لیے state، memory میں ہے؛ production میں unique keys والی tables استعمال کریں۔
// return-updates.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,
INTERNAL_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 seenEvents = new Set(); // `${returnGid}:${status}` and `refund:${id}`
const seenMessages = new Set(); // Meta messages[].id
const optIns = new Set(); // order gids with a WhatsApp opt-in, fed by your order pipeline
const optOuts = new Set(); // phones and BSUIDs that sent STOP
const returns = new Map(); // return gid -> record (your returns table)
const byWamid = new Map(); // template wamid -> return 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 = (ref, reason, detail) => console.log("needs_person", { ref, reason, detail });
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 RETURN_QUERY = `query ret($id: ID!) {
return(id: $id) {
id name status
order { id name phone customer { firstName defaultPhoneNumber { phoneNumber } } shippingAddress { phone } }
returnLineItems(first: 50) { nodes { id quantity: processableQuantity } }
} }`;
// Fields checked against OrderTransaction, 2026-10.
const TX_QUERY = `query tx($id: ID!) {
order(id: $id) { transactions(first: 20) { id kind status amountSet { shopMoney { amount currencyCode } } } } }`;
const TAGS_ADD = `mutation tagsAdd($id: ID!, $tags: [String!]!) {
tagsAdd(id: $id, tags: $tags) { node { id } userErrors { field message } } }`;
const RETURN_PROCESS = `mutation returnProcess($input: ReturnProcessInput!) {
returnProcess(input: $input) { return { id status } userErrors { field message } } }`;
function normalizePhone(raw) {
if (!raw || /[a-z]/i.test(raw)) return null;
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;
}
async function loadReturn(gid) {
const r = (await admin(RETURN_QUERY, { id: gid })).return;
if (!r) throw new Error(`return ${gid} not found`);
const o = r.order;
const rec = returns.get(gid) ?? { gid, preference: null, processing: false, refundedNotified: false, userId: null };
Object.assign(rec, {
status: r.status, orderGid: o.id, orderName: o.name,
firstName: o.customer?.firstName ?? "there",
phone: normalizePhone(o.phone ?? o.customer?.defaultPhoneNumber?.phoneNumber ?? o.shippingAddress?.phone),
lineItems: r.returnLineItems.nodes.map((n) => ({ id: n.id, quantity: n.quantity })),
});
returns.set(gid, rec);
return rec;
}
const canMessage = (rec) => optIns.has(rec.orderGid) && rec.phone
&& !optOuts.has(rec.phone) && !(rec.userId && optOuts.has(rec.userId));
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 } });
async function sendTemplate(rec, name, params, payloads = []) {
const components = [{
type: "body",
parameters: Object.entries(params).map(([k, v]) => ({ type: "text", parameter_name: k, text: String(v) })),
}];
payloads.forEach((payload, index) => components.push({
type: "button", sub_type: "quick_reply", index, parameters: [{ type: "payload", payload }],
}));
const wamid = await waSend({ to: rec.phone, type: "template", template: { name, language: { code: "en_US" }, components } });
byWamid.set(wamid, rec.gid);
return wamid;
}
const STATUS_BY_TOPIC = {
"returns/request": "REQUESTED", "returns/approve": "OPEN",
"returns/decline": "DECLINED", "returns/close": "CLOSED",
};
async function onReturnEvent(topic, payload) {
const gid = payload.admin_graphql_api_id;
const status = STATUS_BY_TOPIC[topic];
const key = `${gid}:${status}`; // one message per return and status, even if a topic arrives again
if (seenEvents.has(key)) return;
seenEvents.add(key);
try {
const rec = await loadReturn(gid);
if (status === "CLOSED") return void (rec.status = "CLOSED");
if (!canMessage(rec)) return;
const id = gid.split("/").pop();
if (status === "REQUESTED") await sendTemplate(rec, "return_requested_v1", { order_number: rec.orderName });
if (status === "DECLINED") await sendTemplate(rec, "return_declined_v1", { order_number: rec.orderName });
if (status === "OPEN") {
await sendTemplate(rec, "return_approved_v1",
{ customer_name: rec.firstName, order_number: rec.orderName },
[`refund:card:${id}`, `refund:credit:${id}`]);
}
} catch (err) {
seenEvents.delete(key);
handOff(gid, `${topic}_failed`, err.message);
}
}
async function onRefundCreated(refund) {
const key = `refund:${refund.id}`;
if (seenEvents.has(key)) return;
seenEvents.add(key);
const orderGid = `gid://shopify/Order/${refund.order_id}`;
const rec = [...returns.values()].find((r) => r.orderGid === orderGid);
if (!rec || rec.processing || rec.refundedNotified) return; // untracked, or our endpoint sends it
// Field names checked against Shopify's refunds/create sample; its transaction currency can be null.
const tx = (refund.transactions ?? []).filter((t) => t.kind === "refund" && t.status === "success");
const currency = tx[0]?.currency ?? refund.refund_line_items?.[0]?.subtotal_set?.shop_money?.currency_code;
if (!tx.length || !currency) return handOff(orderGid, "refund_amount_unknown", refund.id);
const total = tx.reduce((sum, t) => sum + Number(t.amount), 0).toFixed(2);
rec.refundedNotified = true;
if (canMessage(rec)) {
await sendTemplate(rec, "return_refunded_v1", { order_number: rec.orderName, amount: `${total} ${currency}` });
}
}
async function onWhatsAppMessage(msg) {
if (seenMessages.has(msg.id)) return;
seenMessages.add(msg.id);
if (msg.type === "text" && /^\s*stop\s*$/i.test(msg.text?.body ?? "")) {
[msg.from, msg.from_user_id].filter(Boolean).forEach((v) => optOuts.add(v));
if (msg.from) await waText(msg.from, "Done. You will not get more return updates here.");
return;
}
const gid = byWamid.get(msg.context?.id);
const rec = gid && returns.get(gid);
if (!rec) return handOff(null, "unmatched_message", { id: msg.id, type: msg.type });
if (msg.from_user_id) rec.userId = msg.from_user_id;
if (msg.type !== "button") return handOff(gid, "free_text", msg.text?.body ?? msg.type);
const [, method] = String(msg.button?.payload ?? "").split(":");
const label = String(msg.button?.text ?? "").trim().toLowerCase();
const choice = method === "card" || label === "refund to card" ? "card"
: method === "credit" || label === "store credit" ? "credit" : null;
if (!choice) return handOff(gid, "unreadable_button", msg.button);
if (rec.processing || rec.refundedNotified || rec.status === "CLOSED") {
return waText(rec.phone, `The refund for order ${rec.orderName} is already processed. Reply here if you have a question.`);
}
rec.preference = choice; // your returns table is the source of truth
const data = await admin(TAGS_ADD, { id: rec.orderGid, tags: [choice === "credit" ? "refund-pref:store-credit" : "refund-pref:card"] })
.catch((err) => ({ tagsAdd: { userErrors: [err.message] } }));
if (data.tagsAdd.userErrors.length) handOff(gid, "tag_failed", data.tagsAdd.userErrors);
return waText(rec.phone, choice === "credit"
? `Noted. The refund for order ${rec.orderName} will go to store credit.`
: `Noted. The refund for order ${rec.orderName} will go back to your original payment method.`);
}
async function processReturn(rec, amount, currencyCode) {
const money = { amount: String(amount), currencyCode };
let issueRefund;
if (rec.preference === "credit") {
// TODO:test: store credit only, with an empty orderTransactions list.
issueRefund = { orderTransactions: [], refundMethods: [{ storeCreditRefund: { amount: money } }] };
} else {
const txs = (await admin(TX_QUERY, { id: rec.orderGid })).order.transactions;
const parent = txs.find((t) => ["SALE", "CAPTURE"].includes(t.kind) && t.status === "SUCCESS");
if (!parent) throw new Error("no captured transaction to refund");
issueRefund = { orderTransactions: [{ transactionAmount: money, parentId: parent.id }] };
}
const data = await admin(RETURN_PROCESS, { input: {
returnId: rec.gid, returnLineItems: rec.lineItems, financialTransfer: { issueRefund }, notifyCustomer: false,
} });
return data.returnProcess;
}
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);
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 = STATUS_BY_TOPIC[topic] ? onReturnEvent(topic, payload)
: topic === "refunds/create" ? onRefundCreated(payload) : Promise.resolve();
job.catch((err) => handOff(payload.admin_graphql_api_id ?? payload.id, `${topic}_failed`, err.message));
});
const internal = (req, res, next) =>
safeEqual(req.get("authorization"), `Bearer ${INTERNAL_TOKEN}`) ? next() : res.sendStatus(401);
// Your order pipeline records the WhatsApp opt-in captured at checkout.
app.post("/internal/opt-in", express.json(), internal, (req, res) => {
if (!req.body?.orderGid) return res.sendStatus(400);
optIns.add(req.body.orderGid);
res.sendStatus(204);
});
// Your back office calls this after inspection, with the amount a person approved.
app.post("/internal/returns/process", express.json(), internal, async (req, res) => {
const { returnId, amount, currencyCode } = req.body ?? {};
if (!returnId || !(Number(amount) > 0) || !currencyCode) return res.sendStatus(400);
try {
const rec = returns.get(returnId) ?? await loadReturn(returnId);
if (rec.processing || rec.refundedNotified) return res.status(409).json({ error: "already processed" });
rec.processing = true;
const result = await processReturn(rec, amount, currencyCode).catch((err) => ({ userErrors: [{ message: err.message }] }));
if (result.userErrors.length) {
rec.processing = false;
return res.status(422).json({ userErrors: result.userErrors });
}
rec.refundedNotified = true;
if (canMessage(rec)) {
await sendTemplate(rec, "return_refunded_v1", { order_number: rec.orderName, amount: `${amount} ${currencyCode}` })
.catch((err) => handOff(rec.gid, "refunded_message_failed", err.message));
}
res.json({ return: result.return, method: rec.preference ?? "card" });
} catch (err) {
res.status(502).json({ error: 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}`));
Refunded والا پیغام ہر return کے لیے ایک ہی جگہ سے جاتا ہے۔ جب آپ کی سروس نے return کو process کیا ہو تو internal endpoint اسے بھیجتا ہے۔ جب staff نے اس کی بجائے Shopify admin سے refund کیا ہو تو refunds/create اسے بھیجتا ہے، اور اگر payload کے transaction fields پڑھے نہ جا سکیں تو کسی شخص کے حوالے کر دیتا ہے۔ اس آرڈر پر ایسا refund بھی اسے trigger کرتا ہے جو return کا حصہ نہ ہو۔ اگر staff ایسے refunds دیتا ہے تو refunded والا پیغام صرف internal endpoint سے بھیجیں۔
جب کچھ ناکام ہو
اگر کسٹمر کبھی ٹیپ نہ کرے تو کچھ بھی اس کے انتظار میں نہیں رکتا۔ Staff معمول کے مطابق return کو process کرتا ہے، اور سروس اصل payment method پر refund کرتی ہے۔ 12 گھنٹے کا TTL اس approval پیغام کو drop کر دیتا ہے جو وقت پر ڈیلیور نہ ہو سکا، اور Meta اس drop کے لیے کوئی error code نہیں بتاتی۔
Shopify ایک ہی webhook ایک سے زیادہ بار بھیج سکتا ہے، اس لیے سروس دہرائے گئے X-Shopify-Webhook-Id کو چھوڑ دیتی ہے۔ سروس ہر پیغام کو return id اور status کی key پر بھی رکھتی ہے، اس لیے دہرایا گیا status کبھی دوسرا پیغام نہیں بھیجتا۔ Meta کوئی ٹیپ دوبارہ بھیج سکتی ہے، اس لیے سروس دہرائی گئی messages[].id کو چھوڑ دیتی ہے۔ ناکام send، event key ہٹا دیتا ہے اور کسی شخص کے پاس جاتا ہے، کیونکہ Shopify کو اپنا 200 پہلے ہی مل چکا ہے اور وہ retry نہیں کرے گا۔
STOP والا جواب فون اور from_user_id دونوں کو ایک opt-out فہرست میں ڈال دیتا ہے جسے ہر send چیک کرتا ہے۔ اسے اپنی consent table میں بھی ریکارڈ کریں، تاکہ اگلا آرڈر اسے دوبارہ فعال نہ کر دے۔
اگر returnProcess، userErrors واپس کرے تو endpoint، 422 جواب دیتا ہے اور return کھلا چھوڑ دیتا ہے، جبکہ tag اب بھی کسٹمر کا انتخاب دکھاتا ہے۔ پھر کوئی شخص اسے admin میں process کرتا ہے۔ Shopify کا صفحہ یہ نہیں بتاتا کہ جب staff، returnCreate سے پہلے سے کھلا return بنائے تو کون سا webhook چلتا ہے، اس لیے returns/approve پر انحصار سے پہلے یہ راستہ test کریں۔
Z-API Omni کہاں کام آتا ہے
Omni کی کوئی دستاویزی Shopify integration نہیں، اس لیے اوپر والی سروس ہی bridge رہتی ہے۔ Meta کی آفیشل API پر ٹیمپلیٹس POST https://api.omni.z-api.io/v1/channels/{channelId}/messages سے، Bearer Secret Key کے ساتھ جاتے ہیں، اور ٹیمپلیٹ بناتے وقت message_send_ttl_seconds قبول ہوتا ہے۔ منقطع channel، subCode: CHANNEL_DISCONNECTED کے ساتھ 422 واپس کرتا ہے، اور پیغام نہیں بھیجا جاتا۔ آزاد text والے جوابات MESSAGE_RECEIVED کے طور پر آتے ہیں، لیکن docs ابھی quick reply ٹیپ کی inbound شکل نہیں دکھاتے۔
ایک subscription میں WhatsApp، Messenger، Instagram اور Telegram شامل ہیں، 1 سے 10 نمبروں کے لیے US$29 فی نمبر ماہانہ سے لے کر 100 سے زیادہ پر US$20 تک۔ Webhooks بغیر حد کے شامل ہیں۔ آفیشل connection پر Meta کی فیس آگے منتقل ہوتی ہے۔
curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
-H "Authorization: Bearer $OMNI_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"recipient":{"identifier":"5511999999999"},"content":{"type":"TEMPLATE","attachments":[{"template":{"name":"return_refunded_v1","language":{"policy":"deterministic","code":"en_US"},"components":[{"type":"body","parameters":[{"type":"text","text":"#1042"},{"type":"text","text":"25.99 USD"}]}]}}]}}'
Z-API Omni ٹیم