# Kapıda ödemeli siparişleri sevkiyattan önce WhatsApp ile doğrulayın

> Kapıda ödemeli siparişi WhatsApp'ta doğrulayın: Shopify'da sevkiyatı bekletin, Confirm, Change address ve Cancel butonlu utility şablonu gönderin, yanıt yoksa arayın.

Published 2026-11-27. Z-API Omni team.

Kapıda ödeme doğrulama mesajı, alıcıdan sevkiyattan önce kapıda ödemeli (COD) siparişi, ödenecek tutarı ve adresi onaylamasını isteyen bir WhatsApp utility şablonudur. Sipariş geldiği anda bir fulfillment bekletmesi (hold) koyun. Şablonu Confirm (onayla), Change address (adresi değiştir) ve Cancel (iptal et) butonlarıyla gönderin ve bekletmeyi yalnızca onaylanmış bir yanıtta kaldırın. Yanıt gelmezse sipariş otomatik iptale değil, bir arama kuyruğuna gider.

Buton başına payload'lar ve `context.id` eşleşmesiyle genel Confirm ve Cancel döngüsü, [Confirm ve Cancel butonlu WhatsApp sipariş onayı](/academy/tr/articles/whatsapp-order-confirmation-confirm-cancel-buttons/) yazısında. Bu sayfa kapıda ödemenin bunun üstüne ihtiyaç duyduklarını ekler: Shopify'da sevkiyatı engellemek, adresi değiştirmek ve bir kişiye devretmek. Shopify'ın webhook sözleşmesi ve token'ı [Shopify sipariş webhook'larından WhatsApp'a](/academy/tr/articles/shopify-order-webhook-whatsapp-notifications/) yazısında.

## Mesaj neden utility sayılır

Meta'nın sipariş yönetimi hedefi şöyledir: "Belirli sipariş veya işlem ayrıntılarını kullanarak bir müşteriyle bir siparişi ya da işlemi onaylayın, güncelleyin veya iptal edin." Örneği şöyledir: "{{order_number}} numaralı siparişiniz onaylandı. Paketiniz yola çıktığında size haber vereceğiz" ([şablon kategorilendirme, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)).

Bir COD kontrolü bu hedefe uyar. Alıcı siparişi az önce vermiştir ve mesaj siparişin numarasını, tutarını ve adresini adlandırır. Meta'nın sayfası "cash on delivery", "COD", "address" veya "verification" kelimelerinden hiç söz etmez; yani uyum adı konmuş bir kuraldan değil, sipariş yönetimi hedefinden gelir.

Gövdeyi sade tutun. Meta "promosyon içeren bir sipariş güncellemesini" karma içerik sayar ve bu onu pazarlama yapar. Peşin ödemeye indirim, ürün önerisi veya değerlendirme isteği bu şablona girmez.

Template Library'de eşleşen üç kullanım durumu var: `ORDER_CONFIRMATION`, `ORDER_ACTION_NEEDED` ve `ORDER_OR_TRANSACTION_CANCEL`. Meta'nın sayfası bunların gövde metnini göstermiyor. Onlara `GET /message_template_library?topic=ORDER_MANAGEMENT&industry=E_COMMERCE` ile göz atabilirsiniz ([Template Library, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library)). Bu sayfa özel bir şablon kullanır, çünkü üç hızlı yanıta ihtiyacı var.

## Shopify'da COD siparişini tespit edin

`orders/create` konusuna abone olun. Shopify'a göre bu konu "şu kapsamlardan en az birini gerektirir: read_orders, read_marketplace_orders." Ardından siparişten `paymentGatewayNames` değerini okuyun. Shopify bunu "sipariş için kullanılan tüm ödeme ağ geçitlerinin adlarından oluşan bir liste" olarak tanımlar ve örnek olarak "Shopify Payments" ile "Cash on Delivery (COD)" değerlerini verir ([Order nesnesi, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order)).

Shopify'ın sayfası bir satıcının bu ağ geçidini yeniden adlandırıp adlandıramayacağını söylemiyor. Servis, varsayılan olarak Shopify'ın örneğine ayarlanmış, yapılandırılabilir bir dizeyle (`COD_GATEWAY`) eşleştirme yapar. Canlıya almadan önce bir test COD siparişi verin ve değeri kontrol edin.

WooCommerce kullanıyorsanız COD sayfası "WooCommerce, COD kullanan siparişlerin durumunu ödeme tahsil edilene kadar _Processing_ olarak ayarlar" der ([cash on delivery, erişim tarihi 2026-11-27](https://woocommerce.com/document/cash-on-delivery/)). Sayfa bir ağ geçidi ID'si vermiyor. `payment_method` için olası değer `cod`, ama bunu bir test siparişinde kontrol edin. Woo imzalama ve geri yazma adımları [WhatsApp'ta WooCommerce sipariş durumu](/academy/tr/articles/woocommerce-order-status-whatsapp-webhooks/) yazısında.

## Bir şey göndermeden önce sevkiyatı bekletin

Önce siparişi bekletin, yoksa alıcı mesajı okurken depo kargoyu çıkarabilir. Siparişin her fulfillment order'ına `fulfillmentOrderHold` ile bir bekletme koyun. Bu mutation fulfillment order `id` değerini ve `reason`, `reasonNotes`, `notifyMerchant` ve `handle` içeren bir `fulfillmentHold` girdisini alır ([fulfillmentOrderHold, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/mutations/fulfillmentOrderHold)). Shopify'ın örnek yanıtı `"status":"ON_HOLD"` gösterir.

Mutation `write_merchant_managed_fulfillment_orders` veya `write_third_party_fulfillment_orders` gerektirir. Token'ın arkasındaki kullanıcının da siparişleri hazırlama ve gönderme iznine sahip olması gerekir. Bir `handle` vermek bekletmenize ad koyar ve Shopify aynı fulfillment order üzerinde aynı handle ile ikinci bir bekletmeyi reddeder.

Shopify'ın `FulfillmentHoldReason` enum'unda bekleyen bir müşteri onayı için değer yok ([FulfillmentHoldReason, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/enums/FulfillmentHoldReason)). `OTHER` kullanın ve `reasonNotes` değerini "Awaiting WhatsApp COD confirmation" yapın. Alıcı adres değişikliği istediğinde ikinci bir bekletme isterseniz `INCORRECT_ADDRESS` de mevcut.

Bekletmeyi `fulfillmentOrderReleaseHold(id, holdIds, externalId)` ile kaldırın. Shopify şöyle yazıyor: "Uygulamaların kaldırmak istedikleri bekletmelerin ID'lerini vermeleri önemle tavsiye edilir" ([fulfillmentOrderReleaseHold, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/mutations/fulfillmentOrderReleaseHold)). Servis oluşturduğu her bekletme ID'sini saklar ve yalnızca onları kaldırır.

## Şablon ve yaşam süresi

Üç hızlı yanıtlı özel bir `UTILITY` şablonu oluşturun. Meta'nın TTL sayfası utility aralığını "30 saniye ile 12 saat" olarak verir; değer şablonu oluştururken `message_send_ttl_seconds` ile ayarlanır ([time-to-live, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live)). Sayfa gönderim başına bir geçersiz kılma göstermiyor, bu yüzden en erken sevkiyat kesim saatinizden önce biten tek bir TTL seçin. Aşağıdaki kod 6 saat kullanır.

```bash
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" }
      ]
    }
  ]
}'
```

Şablonu yalnızca mağazanızı adlandıran bir WhatsApp onayı vermiş alıcılara gönderin. Shopify'ın SMS onayı sayılmaz. Onayı olmayan bir COD alıcısı doğrudan arama kuyruğuna gider. Servis bu onayı, sepetinizin veya checkout'unuzun ayarlaması gereken `whatsapp_order_updates` adlı bir sipariş not özniteliğinden okur.

## Üç yanıt ve geri yazmaları

Bir dokunuş `type: "button"`, `button.payload`, `button.text` ve şablonun mesaj ID'sine eşit bir `context.id` içeren bir `messages` webhook'u olarak gelir ([buton webhook'u, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button)). Servis her payload'ı `cod_confirm:<order_id>`, `cod_address:<order_id>` veya `cod_cancel:<order_id>` olarak ayarlar ve gerekirse etikete geri düşer.

| Dokunuş | Shopify'a geri yazma | Bekletme |
| --- | --- | --- |
| Confirm order | `cod-confirmed` ile `tagsAdd` | Kaldırılır |
| Change address | `cod-address-change-requested` ile `tagsAdd`, bir kişi yeni adresi kontrol edince `orderUpdate` | Adres güncellenene kadar kalır |
| Cancel order | Pencere içinde ikinci bir onaydan sonra `orderCancel` ve `cod-cancelled` | İptalden sonra önemsizdir |
| Son tarihe kadar yanıt yok | `cod-no-reply` ile `tagsAdd`, sipariş arama kuyruğuna girer | Kalır |

### Change address

Dokunuş bir müşteri hizmetleri penceresi açar, bu yüzden yeni adresi düz metinle isteyebilirsiniz. Yanıtı bir kişi okur ve yapılandırılmış bir adres girer. Servis ardından `write_orders` gerektiren `orderUpdate(input: {id, shippingAddress})` çağrısını yapar ([orderUpdate, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/mutations/orderUpdate)). Yalnızca `id` ve `shippingAddress` gönderin, çünkü o girdideki `tags` ve `note` mevcut değerlerin üzerine yazar.

Shopify'ın sayfası adres değişikliğinin hazırlanmamış siparişlerle sınırlı olup olmadığını söylemiyor. Bekletme siparişi hazırlanmamış durumda tutar, ama fulfillment order'ları bekletmede olan bir siparişte adres değişikliğini test edin.

<!-- TODO:test: orderUpdate shippingAddress on an order whose fulfillment orders are ON_HOLD -->

Meta'nın `address_message` özelliği sohbette yapılandırılmış bir adres toplar. Sayfası "Bu özellik yalnızca Hindistan merkezli işletmeler ve onların Hindistan'daki müşterileri için kullanılabilir" diyor ([adres mesajları, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/address-messages)). Yanıt, `response_json` bir JSON dizesi olacak şekilde `interactive.type: "nfm_reply"` olarak gelir. Başka yerlerde yapılandırılmış seçenek, adres formu içeren bir Flow'dur; [WhatsApp Flows](/academy/tr/articles/whatsapp-flows-forms-inside-chat/) yazısında ele alınıyor.

### Cancel

İlk dokunuşta iptal etmeyin. Pencere içinde "Yes, cancel" (evet, iptal et) ve "Keep my order" (siparişim kalsın) yanıt butonlarıyla bir kez daha sorun. Bu yanıt `interactive.button_reply.{id, title}` ile `type: "interactive"` olarak gelir. Meta'nın örneği `{"id":"cancel-button","title":"Cancel"}` şeklindedir ([interactive webhook'u, erişim tarihi 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/interactive)).

Ardından `orderCancel(orderId, reason: CUSTOMER, restock: true, notifyCustomer: false, staffNote)` çağrısını yapın. Bu bir iş (job) olarak çalışır, bu yüzden `job { id done }` değerini yoklayın. Hatalar `orderCancelUserErrors` içinde gelir ve Shopify "Bu işlem geri alınamaz" diye uyarır ([orderCancel, erişim tarihi 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/mutations/orderCancel)). Ödenmemiş bir COD siparişinde iade edilecek bir şey yoktur, bu yüzden servis `refundMethod` göndermez.

## Servisin tamamı

Bu Node 18+ dosyası `npm install express` ile çalışır. İki webhook'u da doğrular, `X-Shopify-Webhook-Id` ve Meta'nın mesaj ID'leri üzerinden tekilleştirir ve her siparişi koşullu durum geçişleriyle ilerletir. `ADMIN_KEY` ile korunan iki admin rotası, bir kişinin kontrol edilmiş bir adresi veya telefonla alınmış bir onayı uygulamasını sağlar. Örnekte durum bellekte tutulur.

```js
// 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}`));
```

Alıcının yazdığı adres bilinçli olarak bir kişiye gider. Serbest metin adresler, okunmadan bir siparişe yazılamayacak kadar çeşitlidir. Adres için bir Flow kurarsanız onun yanıtı serbest metnin ve admin rotasının yerini alır.

## Kimse yanıt vermediğinde

Alıcı dokunmadı diye bir COD siparişini asla iptal etmeyin. Telefon kapalı olabilir, alıcı mesajı kaçırmış olabilir ya da şablon başarısız olmuş olabilir. Son tarihte servis siparişi `cod-no-reply` ile etiketler, arama kuyruğuna ekler ve bekletmeyi korur. Şablonda bir `failed` durumu da hemen aynısını yapar.

Arama kuyruğunu siz yönetirsiniz. Bir kişi alıcıyı arayıp ardından `confirmed-by-call` rotasını kullanabilir ya da Shopify admin panelinde iptal edebilir. Aramanın WhatsApp'tan başlamasını istiyorsanız Meta'nın arama seçeneği [WhatsApp Business Calling API](/academy/tr/articles/whatsapp-business-calling-api/) yazısında ele alınıyor.

Geç gelen bir dokunuş yine çalışır. `call_queue` durumundaki bir sipariş Confirm, Change address ve Cancel kabul eder; böylece son tarihten sonra yanıt veren bir alıcı geri çevrilmez. Kuyruğu yöneten kişi aramadan önce siparişin etiketlerini kontrol etmelidir.

## Yinelemeler, yeniden denemeler ve zamanlama

Shopify başarısız bir teslimatı 4 saat içinde 8 kez yeniden dener ([HTTPS webhook'ları, erişim tarihi 2026-11-27](https://shopify.dev/docs/apps/build/webhooks/subscribe/https)). `X-Shopify-Webhook-Id` kontrolü tekrarlanan teslimatları durdurur, `orders.has(gid)` ise aynı siparişin ikinci kez teslim edilmesini durdurur. Meta da yeniden dener, bu yüzden servis `messages[].id` üzerinden tekilleştirir. Her durum değişikliği koşulludur; ikinci bir Confirm, ikinci bir bekletme kaldırma yerine kısa bir yanıt alır.

Bekletme başarısız olursa ya da hiç bekletme konmazsa şablon yine gider ve bir kişi `hold_failed` veya `no_hold_placed` log satırını görür. Depo yanıt gelmeden kargoyu çıkarabilir, bu yüzden o satırı acil sayın.

Son tarih ve TTL birlikte çalışır. 6 saatlik TTL ve 6 saatlik son tarihle, teslim edilmemiş bir şablon aşağı yukarı sipariş arama kuyruğuna girdiğinde sona erer. Meta, TTL'nin düşürdüğü bir mesaj için hata kodu belirtmez. Sevkiyat kesim saatiniz altı saatten yakınsa ikisini de kısaltın.

Şablonu veya iptal sorusunu çevirmeden önce iki buton türünün etiket uzunluklarını kontrol edin. Sınırlar [etkileşimli butonlar ve liste mesajları](/academy/tr/articles/whatsapp-interactive-buttons-list-messages-limits/) yazısında.

## Z-API Omni'nin yeri

Omni bir Shopify ya da WooCommerce entegrasyonu veya zamanlayıcı belgelemiyor, bu yüzden bekletme, son tarih ve arama kuyruğu sizin servisinizde kalır. Meta'nın resmi API'sinde özel model sayfası bir `UTILITY` şablonunun `quick_reply` payload bileşenini gösterir ve `message_send_ttl_seconds` utility için 30 ile 43200 arasını kabul eder. Flows (`INTERACTIVE_FLOW`, yalnızca Meta) bir adres formu için belgelenmiş bir `FORM_RESPONSE` döner. Buton dokunuşunun gelen biçimi belgelenmemiş.

QR bağlantısında `INTERACTIVE_BUTTON` en fazla üç buton taşır, yani üç seçeneğin hepsi sığar.

<!-- TODO:test Omni snippet: INTERACTIVE_BUTTON on the QR connection; inbound JSON of each tap; whether the button id comes back -->
```json
{
  "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" }
    ]
  }
}
```

Bağlantısı kopmuş bir kanal `subCode: CHANNEL_DISCONNECTED` ile `422` döner ve mesaj daha sonra gönderilmek üzere tutulmaz, bu yüzden bir arama kuyruğa alın. Tek abonelik WhatsApp, Messenger, Instagram ve Telegram'ı kapsar: 1 ila 10 numara için numara başına ayda US$29, 100'ün üzerinde US$20'ye kadar iner. QR bağlantısında mesaj başına maliyet yoktur; Meta'nın resmi API'sinde Meta'nın ücretleri olduğu gibi yansıtılır.

[Dokümantasyonu görüntüleyin](https://developer.omni.z-api.io/en)

*Z-API Omni ekibi*
