WhatsApp· 8 منٹ کا مطالعہ

WooCommerce آرڈر status، webhooks سے WhatsApp پر، بغیر plugin


order.updated topic والا ایک WooCommerce webhook اپنی سروس کی طرف موڑیں اور X-WC-Webhook-Signature verify کریں۔ پھر WhatsApp utility ٹیمپلیٹ صرف تب بھیجیں جب آرڈر کا status اس سے مختلف ہو جس پر آپ نے آخری پیغام بھیجا تھا۔ WooCommerce پچھلا status نہیں بھیجتا، اور docs کسی retry کا ذکر نہیں کرتے۔ ہر delivery کو فوری 2xx سے جواب دیں اور آخری status خود محفوظ کریں۔ کسٹمر کے جوابات REST API کے ذریعے private order notes کے طور پر واپس جاتے ہیں۔

جواب کا چکر (quick reply payloads، context.id پر matching، شرطیہ updates، خاموشی) Confirm اور Cancel بٹنوں کے ساتھ WhatsApp پر آرڈر کی تصدیق میں ہے۔ Shopify والا ورژن Shopify order webhooks سے WhatsApp ہے۔ یہ صفحہ وہ بتاتا ہے جو WooCommerce مختلف طریقے سے کرتا ہے، اس کے docs اور class-wc-webhook.php میں core source کی بنیاد پر (trunk، پڑھا گیا 2026-11-25)۔

Webhook بنائیں

WooCommerce > Settings > Advanced > Webhooks استعمال کریں، یا REST API۔ آرڈر کے topics یہ ہیں: «order.created، order.updated اور order.deleted» (REST API webhooks، رسائی 2026-11-25)، اور source میں order.restored بھی ہے۔

curl -X POST "$WC_URL/wp-json/wc/v3/webhooks" \
  -u "$WC_KEY:$WC_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
  "name": "Order updated to WhatsApp",
  "topic": "order.updated",
  "delivery_url": "https://hooks.example.com/woo/webhook",
  "secret": "'"$WC_WEBHOOK_SECRET"'"
}'

ایسا secret چنیں جس میں &، <، > یا quotes نہ ہوں۔ source، محفوظ secret پر wp_specialchars_decode() لگا کر sign کرتا ہے، اس لیے اس میں HTML entities ہوں تو key بدل جائے گی۔

order.created نہیں، order.updated کیوں

block checkout پہلے آرڈر کو checkout-draft کے طور پر بناتا ہے، اور webhook code drafts (DRAFT، AUTO_DRAFT، CHECKOUT_DRAFT، NEW) کو چھوڑ دیتا ہے۔ source سے ہم یہ سمجھتے ہیں کہ اسی وجہ سے اصل آرڈر کی پہلی delivery، order.updated کے طور پر آ سکتی ہے۔ ہم نے کسی live store پر اس کی تصدیق نہیں کی۔ order.updated پر subscribe کرنا اور status سے فیصلہ کرنا دونوں صورتوں میں کام کرتا ہے۔

Delivery کیسی دکھتی ہے

ہر delivery ایک POST ہے، جس کے headers X-WC-Webhook-Source، -Topic، -Resource، -Event، -Signature، -ID اور -Delivery-ID ہیں۔ body، trim( wp_json_encode( $payload ) ) ہے۔ signature اسی body پر base64_encode( hash_hmac( 'sha256', $payload, wp_specialchars_decode( $secret, ENT_QUOTES ), true ) ) ہے۔ SHA-256 default ہے، اور ایک filter اسے بدل سکتا ہے۔

raw bytes پر verify کریں۔ signature میں کوئی timestamp شامل نہیں، اور delivery ID، webhook ID اور موجودہ سیکنڈ کا hash ہے۔ dedupe میں ان دونوں سے مدد نہیں ملتی، اس لیے اپنی key آرڈر ID، status اور date_modified_gmt سے بنائیں۔

Activation ping میں signature نہیں ہوتا

جب webhook کو active کے طور پر save کیا جائے تو WooCommerce ایک ping بھیجتا ہے، جس کی form-encoded body webhook_id=<ID> ہوتی ہے اور کوئی signature header نہیں ہوتا۔ 2xx کے علاوہ کوئی response، “Error: Delivery URL returned response code” پیدا کرتا ہے۔ ping کو 200 سے جواب دیں اور کچھ اور نہ کریں۔ signature نہ ہونے پر اسے رد کرنے سے activation رک جاتی ہے۔

Payload، delivery کے وقت بنتا ہے

Deliveries بطور default، Action Scheduler کے ذریعے asynchronously چلتی ہیں۔ جب job چلتی ہے تو deliver()، build_payload() کو کال کرتا ہے، جو اسی لمحے /wc/v3/orders/<id> سے آرڈر پڑھتا ہے۔ body آرڈر کو ویسا دکھاتی ہے جیسا وہ delivery کے وقت ہے، event کے وقت نہیں۔ source میں ایک code comment یہ بھی کہتا ہے: “Make webhooks unique - only schedule one webhook every 10 minutes”۔

اس لیے status کی دو تیز تبدیلیاں ایک delivery کے طور پر آ سکتی ہیں، یا دو کے طور پر جن دونوں میں تازہ ترین status ہو۔ payload میں پچھلے status کا کوئی field نہیں۔ ہر آرڈر کا وہ status محفوظ کریں جس پر آپ نے آخری پیغام بھیجا، اور صرف تب عمل کریں جب نیا مختلف ہو۔ یہی قاعدہ آپ کی اپنی writes کو بھی سنبھالتا ہے: cancelled پر PUT سے woocommerce_update_order چلتا ہے، اور آپ کی سروس کو وہ تبدیلی webhook کے طور پر ملتی ہے۔ ترتیب کا عمومی مسئلہ بے ترتیب webhooks میں ہے۔

کوئی retry نہیں، اور پانچ ناکامیاں اسے بند کر دیتی ہیں

core code میں کوئی retry نظر نہیں آتا۔ ناکام deliveries صرف ایک حد کی طرف گنی جاتی ہیں: if ( $failures > apply_filters( 'woocommerce_max_webhook_delivery_failures', 5 ) )، اور webhook کا status، disabled ہو جاتا ہے۔ docs بھی یہی کہتے ہیں: «مسلسل 5 ناکام deliveries کے بعد (جن کی تعریف HTTP 2xx کے علاوہ response code ہے)»، جس کے بعد آپ اسے REST سے دوبارہ فعال کرتے ہیں۔

کسی بھی WhatsApp call سے پہلے 2xx واپس کریں، اور کام queue میں ڈالیں۔ ایک cron job چلائیں جو webhook کا status پڑھے اور disabled ہونے پر alert دے۔ نہ docs اور نہ core code دوبارہ بھیجنے کا ذکر کرتے ہیں، اس لیے حال ہی میں بدلے ہوئے آرڈرز پر reconciliation کا ایک چکر یہ خلا پورا کرتا ہے۔ idempotency کا pattern duplicate webhooks اور idempotency میں ہے۔

ہر status کو ایک utility پیغام سے جوڑیں

نیچے ہر پیغام کسٹمر کے اپنے آرڈر کے بارے میں ہے اور اس میں کوئی offer نہیں، جو اسے Meta کی utility تعریف کے اندر رکھتا ہے۔ Meta، «promo والی آرڈر اپ ڈیٹ» کو مارکیٹنگ مانتا ہے (template categorization، رسائی 2026-11-25)۔ status کی values، REST API سے ہیں (orders، رسائی 2026-11-25)۔

Status ٹیمپلیٹ Template Library مماثل مواد
processing order_confirm_v1 ORDER_CONFIRMATION نمبر، کل رقم، Confirm اور Cancel quick replies
on-hold order_on_hold_v1 کوئی نام نہیں دیا گیا «آرڈر {{order_number}} ادائیگی ملنے تک روکا گیا ہے۔»
completed order_shipped_v1 SHIPMENT_CONFIRMATION carrier اور tracking URL بٹن
cancelled order_cancelled_v1 ORDER_OR_TRANSACTION_CANCEL «آرڈر {{order_number}} منسوخ کر دیا گیا ہے۔»

order_confirm_v1 آرڈر کی تصدیق والے مضمون میں بنتا ہے، اور order_shipped_v1 Shopify والے میں۔ باقی دو بھی اسی طرح بنائیں، UTILITY کے طور پر، ایک named parameter کے ساتھ۔ on-hold کا text حقائق تک رکھیں۔ دباؤ والے الفاظ کے ساتھ ادائیگی کی یاد دہانی ایک الگ پیغام ہے، جس کے قواعد بھی الگ ہیں۔ اس table سے باہر دکان کے دو پیغامات کے اپنے صفحات ہیں: back-in-stock alerts، جو مارکیٹنگ ہیں، اور return اور refund اپ ڈیٹس، جو utility رہتی ہیں۔

WooCommerce میں WhatsApp consent کا کوئی field نہیں۔ block checkout پر woocommerce_init میں woocommerce_register_additional_checkout_field سے ایک field رجسٹر کریں (additional checkout fields، رسائی 2026-11-25)۔ WhatsApp opt-in کے قواعد کے مطابق label میں store کا نام ہو اور یہ بتایا جائے کہ کسٹمر کو کیا ملے گا۔ یہ آپ کی theme کی functions.php یا آپ کے اپنے چھوٹے site plugin میں جاتا ہے۔

<?php
add_action( 'woocommerce_init', function () {
    if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
        return;
    }
    woocommerce_register_additional_checkout_field( array(
        'id'       => 'yourstore/whatsapp-updates',
        'label'    => 'Send me order updates from YOUR_STORE_NAME on WhatsApp',
        'location' => 'contact',
        'type'     => 'checkbox',
    ) );
} );

value، order meta _wc_other/yourstore/whatsapp-updates کے طور پر محفوظ ہوتی ہے، checkbox کی values "1"، "0" یا "" کے ساتھ۔ WooCommerce کے docs یہ نہیں بتاتے کہ یہ key، REST کے اس meta_data میں آتی ہے یا نہیں جو webhook payload لاتا ہے۔ نیچے والی سروس اسے meta_data سے پڑھتی ہے اور نہ ملنے پر کچھ نہیں بھیجتی، جو محفوظ طریقے سے ناکام ہوتا ہے۔ classic shortcode checkout کو اس کی بجائے checkout hooks چاہئیں۔

فون آزاد text ہے

billing.phone ایک سادہ string ہے، اور v3 order table میں کوئی shipping.phone درج نہیں۔ بھیجنے سے پہلے اسے billing.country کے ساتھ normalize کریں، جیسا کہ WhatsApp فون نمبر format میں بیان ہے۔

جواب کو private note کے طور پر لکھیں

POST /wp-json/wc/v3/orders/<id>/notes اور {"note": "..."} body سے note شامل کریں (order notes، رسائی 2026-11-25)۔ customer_note کو false رکھیں۔ true کے ساتھ «note کسٹمرز کو دکھایا جائے گا اور انہیں اطلاع دی جائے گی»، یعنی کسٹمر کو اپنے ہی ٹیپ کے بارے میں email ملے گی۔ note شامل کرنے سے order.updated چلتا ہے یا نہیں، یہ test نہیں ہوا۔ اگر چلے تو status guard اسے سنبھال لیتا ہے۔

منسوخی کے لیے PUT /wp-json/wc/v3/orders/<id> اور {"status": "cancelled"} استعمال کریں۔ WooCommerce منسوخی کی کوئی مدت نافذ نہیں کرتا، اس لیے guard آپ کے code میں ہوتا ہے۔ منسوخی صرف تب ہونے دیں جب status، pending، on-hold یا processing ہو، اور اگر آپ کا shipping plugin shipments کو الگ نشان زد کرتا ہے تو اسے بھی چیک کریں۔

منسوخی سے ادائیگی واپس نہیں ہوتی۔ woocommerce_order_status_cancelled پر core، wc_maybe_increase_stock_levels کو کال کرتا ہے، جو stock صرف تب بحال کرتا ہے جب آرڈر پر _order_stock_reduced flag ہو (wc-stock-functions.php، پڑھا گیا 2026-11-25)۔ refunds ایک الگ قدم ہے، اس لیے ادا شدہ آرڈر پر Cancel ٹیپ کسی شخص تک بھی پہنچنا چاہیے۔

مکمل سروس

یہ Node 18+ فائل npm install express کے بعد چلتی ہے۔ یہ ping کا جواب دیتی ہے، دونوں webhooks verify کرتی ہے، status کی ہر تبدیلی پر ایک پیغام بھیجتی ہے، اور ٹیپس سنبھالتی ہے۔ production میں lastStatus کو ایک table میں رکھیں، ورنہ restart پر موجودہ status دوبارہ بھیج دیا جائے گا۔

// woo-whatsapp.js. Node 18+. npm install express
const crypto = require("crypto");
const express = require("express");

const {
  WC_URL, WC_KEY, WC_SECRET, WC_WEBHOOK_SECRET,
  WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN,
  CONSENT_META_KEY = "_wc_other/yourstore/whatsapp-updates",
  COUNTRY_CODES = '{"US":"1","GB":"44","ES":"34","MX":"52","BR":"55"}',
  CARRIER_NAME = "our carrier", PORT = "3000",
} = process.env;

const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const CALLING_CODES = JSON.parse(COUNTRY_CODES);
const CANCELLABLE = new Set(["pending", "on-hold", "processing"]);

const lastStatus = new Map();   // order id -> status we last acted on
const seenEvents = new Set();   // `${id}:${status}:${date_modified_gmt}`
const byWamid = new Map();      // template wamid -> order id
const answered = new Map();     // order id -> "confirm" | "cancel"
const seenMessages = new Set(); // Meta messages[].id

const rawBuffer = (req) => (Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0));
const safeEqual = (a, b) => {
  const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? "");
  return x.length === y.length && crypto.timingSafeEqual(x, y);
};
const handOff = (orderId, reason, detail) => console.log("needs_person", { orderId, reason, detail });

const wcAuth = "Basic " + Buffer.from(`${WC_KEY}:${WC_SECRET}`).toString("base64");
async function wc(method, path, body) {
  const res = await fetch(`${WC_URL}/wp-json/wc/v3${path}`, {
    method,
    headers: { Authorization: wcAuth, "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!res.ok) throw new Error(`wc ${method} ${path} ${res.status}`);
  return res.json();
}
const addNote = (id, note) => wc("POST", `/orders/${id}/notes`, { note, customer_note: false });

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) }));
const template = (to, name, components) => ({ to, type: "template", template: { name, language: { code: "en_US" }, components } });
const quickReply = (index, payload) => ({ type: "button", sub_type: "quick_reply", index, parameters: [{ type: "payload", payload }] });

function normalizePhone(raw, country) {
  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;
  const code = CALLING_CODES[country];
  return code && digits.length >= 6 ? code + digits.replace(/^0+/, "") : null;
}

const hasConsent = (order) =>
  (order.meta_data ?? []).some((m) => m.key === CONSENT_META_KEY && String(m.value) === "1");

const MESSAGES = {
  processing: (o, to) => template(to, "order_confirm_v1", [
    { type: "body", parameters: named({ customer_name: o.billing?.first_name || "there", order_number: o.number, order_total: `${o.total} ${o.currency}` }) },
    quickReply(0, `confirm:${o.id}`),
    quickReply(1, `cancel:${o.id}`),
  ]),
  "on-hold": (o, to) => template(to, "order_on_hold_v1", [
    { type: "body", parameters: named({ order_number: o.number }) },
  ]),
  completed: (o, to) => template(to, "order_shipped_v1", [
    { type: "body", parameters: named({ order_number: o.number, carrier: CARRIER_NAME }) },
    { type: "button", sub_type: "url", index: 0, parameters: [{ type: "text", text: String(o.id) }] },
  ]),
  cancelled: (o, to) => template(to, "order_cancelled_v1", [
    { type: "body", parameters: named({ order_number: o.number }) },
  ]),
};

async function onOrder(order) {
  const key = `${order.id}:${order.status}:${order.date_modified_gmt}`;
  if (seenEvents.has(key)) return;
  seenEvents.add(key);
  if (lastStatus.get(order.id) === order.status) return; // no change, or our own write echoing back
  lastStatus.set(order.id, order.status);

  const build = MESSAGES[order.status];
  if (!build || !hasConsent(order)) return;
  const phone = normalizePhone(order.billing?.phone, order.billing?.country);
  if (!phone) return handOff(order.id, "no_usable_phone", null);

  const wamid = await waSend(build(order, phone));
  byWamid.set(wamid, order.id);
  await addNote(order.id, `WhatsApp "${order.status}" message sent (${wamid}).`).catch((err) => handOff(order.id, "note_failed", err.message));
}

async function onTap(msg) {
  if (seenMessages.has(msg.id)) return;
  seenMessages.add(msg.id);
  const orderId = byWamid.get(msg.context?.id);
  if (!orderId) return handOff(null, "unmatched_message", { id: msg.id, type: msg.type });
  if (msg.type !== "button") return handOff(orderId, "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(orderId, "unreadable_button", msg.button);

  const order = await wc("GET", `/orders/${orderId}`);
  const phone = normalizePhone(order.billing?.phone, order.billing?.country);
  if (answered.has(orderId)) {
    return waText(phone, `Order ${order.number} was already handled. Reply here if that looks wrong.`);
  }

  if (action === "confirm") {
    answered.set(orderId, "confirm");
    await addNote(orderId, "Customer confirmed the order on WhatsApp.").catch((err) => handOff(orderId, "note_failed", err.message));
    return waText(phone, `Thanks. Order ${order.number} is confirmed.`);
  }

  if (!CANCELLABLE.has(order.status)) {
    handOff(orderId, "cancel_not_allowed", order.status);
    return waText(phone, `Order ${order.number} can no longer be cancelled here. A person from our team will reply.`);
  }
  answered.set(orderId, "cancel");
  lastStatus.set(order.id, "cancelled"); // so the echo of our own PUT sends no template
  try {
    await wc("PUT", `/orders/${orderId}`, { status: "cancelled" });
  } catch (err) {
    answered.delete(orderId);
    lastStatus.set(order.id, order.status);
    handOff(orderId, "cancel_failed", err.message);
    return waText(phone, `We got your request for order ${order.number}. A person from our team will confirm it here.`);
  }
  await addNote(orderId, "Customer cancelled the order on WhatsApp.").catch((err) => handOff(orderId, "note_failed", err.message));
  if (order.status !== "pending") handOff(orderId, "check_refund", order.total); // cancel does not refund
  return waText(phone, `Order ${order.number} is cancelled. Reply here if you have a question about it.`);
}

const app = express();

app.post("/woo/webhook", express.raw({ type: "*/*" }), (req, res) => {
  const buf = rawBuffer(req);
  const signature = req.get("x-wc-webhook-signature");
  if (!signature && /^webhook_id=\d+$/.test(buf.toString("utf8").trim())) {
    return res.sendStatus(200); // activation ping: unsigned, form-encoded
  }
  const digest = crypto.createHmac("sha256", WC_WEBHOOK_SECRET).update(buf).digest("base64");
  if (!safeEqual(digest, signature)) return res.sendStatus(401);
  res.sendStatus(200);

  const topic = req.get("x-wc-webhook-topic");
  if (topic !== "order.updated" && topic !== "order.created") return;
  const order = JSON.parse(buf.toString("utf8"));
  onOrder(order).catch((err) => handOff(order.id, "order_event_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 buf = rawBuffer(req);
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(buf).digest("hex");
  if (!safeEqual(expected, req.get("x-hub-signature-256"))) return res.sendStatus(401);
  res.sendStatus(200);
  const body = JSON.parse(buf.toString("utf8"));
  for (const entry of body.entry ?? []) {
    for (const change of entry.changes ?? []) {
      for (const msg of change.value?.messages ?? []) {
        onTap(msg).catch((err) => handOff(null, "tap_failed", err.message));
      }
    }
  }
});

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

COUNTRY_CODES، billing.country کے ISO ملک کو calling code سے map کرتا ہے۔ جن ممالک میں آپ فروخت کرتے ہیں ان کے لیے اسے بڑھائیں۔ Meta والا حصہ X-Hub-Signature-256 verification کے مطابق ہے۔

جب کچھ ناکام ہو

اگر 2xx کے بعد WhatsApp send کوئی error دے تو وہ کسی شخص کے پاس جاتی ہے، اور status پہلے ہی ریکارڈ ہو چکا ہوتا ہے۔ WooCommerce ویسے بھی retry نہ کرتا۔ اگر آپ کی سروس بند ہو تو deliveries ناکام ہوتی ہیں اور ان پانچ میں گنی جاتی ہیں جو webhook کو بند کر دیتی ہیں۔ آپ کا cron چیک اور reconciliation کا چکر ہی بحالی کا واحد راستہ ہیں۔

جو کسٹمر ٹیپ نہ کرے اس کا آرڈر جیسا ہے ویسا رہتا ہے۔ سروس خاموشی پر کبھی منسوخ نہیں کرتی۔ جواب نہ آنے کی handling آرڈر کی تصدیق والے مضمون سے لیں۔ completed آرڈر پر Cancel ٹیپ کو ایک جواب ملتا ہے اور وہ کسی شخص کے حوالے ہوتا ہے، status کبھی نہیں بدلتا۔

Z-API Omni کہاں کام آتا ہے

Omni کسی WooCommerce integration کو دستاویز نہیں کرتا، اس لیے اوپر والی سروس ہی bridge رہتی ہے۔ WhatsApp کی طرف یہی ٹیمپلیٹس POST https://api.omni.z-api.io/v1/channels/{channelId}/messages سے، Bearer Secret Key کے ساتھ جاتے ہیں، اور اس کے docs میں quick reply کا payload component موجود ہے۔ ٹیپ کی inbound شکل ابھی دستاویز نہیں ہوئی۔ ایک subscription میں WhatsApp، Messenger، Instagram اور Telegram شامل ہیں، اس لیے store کے مالک کے لیے Telegram پر alert بھی اسی اکاؤنٹ سے چل سکتا ہے۔ قیمت فی نمبر ہے: 1 سے 10 نمبروں کے لیے US$29 ماہانہ، 11 سے 50 کے لیے US$26، 51 سے 100 کے لیے US$23، اور 100 سے زیادہ پر US$20۔ QR connection پر فی پیغام کوئی لاگت نہیں، اور Meta کی آفیشل API پر Meta کی فیس آگے منتقل ہوتی ہے۔

دستاویزات دیکھیں

Z-API Omni ٹیم