# Aggiornamenti su resi e rimborsi Shopify via WhatsApp

> Webhook dei resi Shopify come aggiornamenti utility su WhatsApp: il cliente sceglie rimborso su carta o credito in negozio, e returnProcess applica la scelta.

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

Un aggiornamento sullo stato di un reso è un modello utility che dice al cliente a che punto è il suo reso: richiesto, approvato, rifiutato o rimborsato. In Shopify, iscriviti a `returns/request`, `returns/approve`, `returns/decline`, `returns/close` e `refunds/create`. Quei payload contengono solo ID, quindi interroga il `Return` e il relativo ordine con GraphQL per ottenere il telefono. All'approvazione, invia un modello UTILITY personalizzato con due risposte rapide, "Refund to card" (Rimborso su carta) e "Store credit" (Credito in negozio). Salva il tocco nella tua tabella dei resi, applica un tag all'ordine con `tagsAdd`, e applica la scelta quando chiami `returnProcess`.

Il contratto dei webhook, il controllo HMAC e il token di accesso sono gli stessi di [webhook degli ordini Shopify verso WhatsApp](/academy/it/articles/shopify-order-webhook-whatsapp-notifications/), quindi questa pagina rimanda lì invece di ripeterli. La logica di abbinamento dei tocchi viene da [conferma d'ordine con i pulsanti Confirm e Cancel](/academy/it/articles/whatsapp-order-confirmation-confirm-cancel-buttons/).

## Gli eventi che Shopify invia per un reso

Shopify elenca questi topic per i resi: `returns/request`, `returns/approve`, `returns/decline`, `returns/process`, `returns/close`, `returns/cancel`, `returns/update`, `returns/reopen`, più `refunds/create` e due topic di logistica inversa ([app per i resi, consultato il 2026-11-27](https://shopify.dev/docs/apps/build/orders-fulfillment/returns-apps)). «I webhook dei resi sono disponibili solo nella GraphQL Admin API», dalla versione 2023-01. La stessa pagina dice che «Puoi restituire solo articoli che sono stati evasi», quindi un reso segue sempre un'evasione.

Il ciclo gira su questi topic:

| Topic | Stato nel payload | Cosa invii |
| --- | --- | --- |
| `returns/request` | `requested` | `return_requested_v1`, senza pulsanti |
| `returns/approve` | `open` | `return_approved_v1` con le due risposte rapide |
| `returns/decline` | `declined` | `return_declined_v1`, senza pulsanti |
| `returns/close` | `closed` | Niente. Segna il tuo record come chiuso |
| `refunds/create` | nessuno | `return_refunded_v1`, a meno che il tuo servizio non l'abbia già inviato |

L'esempio di `returns/request` nel [riferimento dei webhook](https://shopify.dev/docs/api/webhooks/latest?reference=toml) di Shopify (consultato il 2026-11-27) è questo. Sono valori di esempio di Shopify:

```json
{
  "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` aggiunge `decline: { reason, note }`, dove la nota di esempio di Shopify dice «Come discusso al telefono, la finestra di reso di 30 giorni è terminata». Non incollare quella nota in testo libero in una variabile del modello. Tieni fisso il testo del modello, e lascia che sia una persona a spiegare il rifiuto in chat se il cliente risponde.

`returns/close` è più corto e ha una forma diversa: `{ id, admin_graphql_api_id, order_id, status: "closed" }`. Contiene `order_id`, non un oggetto `order`, quindi il codice che legge `payload.order.id` si rompe. L'esempio di `refunds/create` contiene l'`id` del rimborso, il suo `order_id`, una `note`, `refund_line_items` e le transazioni. Non era disponibile un esempio di `returns/process`.

### I payload contengono ID, non telefoni

Nessuno di questi payload ha un telefono, un cliente o il dettaglio delle righe. Recuperali con una query GraphQL sull'oggetto `Return`, che «Richiede lo scope di accesso `read_returns` o `read_marketplace_returns`» ([Return, consultato il 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/objects/Return)). Leggi `order { phone customer { defaultPhoneNumber { phoneNumber } } shippingAddress { phone } }` e normalizza il primo valore utilizzabile, come in [formato dei numeri di telefono](/academy/it/articles/whatsapp-phone-number-format-e164-normalization/). La stessa query ti dà `returnLineItems`, che servirà più avanti a `returnProcess`.

L'enum `ReturnStatus` di Shopify ha cinque valori: `REQUESTED`, `OPEN`, `DECLINED`, `CLOSED` («Il reso è stato completato») e `CANCELED` ([ReturnStatus, consultato il 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/enums/ReturnStatus)). `returnApproveRequest` porta un reso a `OPEN`. `returnProcess` lo chiude «quando tutti gli articoli sono stati elaborati ed è stata presa una decisione sul riassortimento».

## I messaggi: quattro modelli utility

Gli aggiornamenti sui resi superano il test utility di Meta. Meta chiede contenuti «non promozionali», «specifici per l'utente o da lui richiesti» ed «essenziali o critici per l'utente» ([categorizzazione dei modelli, consultato il 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization)). La riga Order Management di quella pagina contiene perfino un esempio di rimborso: «Abbiamo ricevuto il tuo articolo dall'ordine {{order_number}}. Il tuo rimborso di ${{amount}} è stato elaborato. Grazie per averci scelto».

La stessa pagina classifica «un aggiornamento dell'ordine con una promozione» come marketing. Quindi non aggiungere mai a questi modelli un coupon per «tornare a comprare» o un suggerimento di prodotto. Le regole e il costo di una ricategorizzazione sono in [categorie dei modelli](/academy/it/articles/whatsapp-template-categories-marketing-utility-authentication/).

La Template Library ha un caso d'uso `RETURN_CONFIRMATION`, e i modelli della libreria devono essere `UTILITY` con «contenuto fisso che non può essere modificato» ([Template Library, consultato il 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library)). La pagina di Meta non mostra il corpo di quel tipo. Consideralo il tipo corrispondente della libreria e scrivi modelli personalizzati, come spiegato in [WhatsApp Template Library](/academy/it/articles/whatsapp-template-library-prebuilt-templates/).

Dai al messaggio di approvazione un TTL breve. Per i modelli utility il valore predefinito è 30 giorni, e `message_send_ttl_seconds` accetta da 30 a 43.200 secondi ([time-to-live, consultato il 2026-11-27](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live)). Le 12 ore qui sotto sono una nostra scelta; Meta non raccomanda alcun valore. Una richiesta di «scegliere il metodo di rimborso» che arriva giorni dopo, quando lo staff ha già elaborato il reso, confonde soltanto il cliente.

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

Crea allo stesso modo i due modelli senza pulsanti. `return_requested_v1` dice "We got your return request for order {{order_number}}. We will message you here once it is reviewed." (Abbiamo ricevuto la tua richiesta di reso per l'ordine {{order_number}}. Ti scriveremo qui appena l'avremo esaminata.) `return_declined_v1` dice "Your return request for order {{order_number}} was not approved. Reply here and our team will explain the next step." (La tua richiesta di reso per l'ordine {{order_number}} non è stata approvata. Rispondi qui e il nostro team ti spiegherà il passo successivo.) Inviali solo ai clienti con un opt-in WhatsApp. Il consenso SMS di Shopify è un record diverso, come spiega l'articolo su Shopify, e le regole dell'opt-in sono in [come raccogliere l'opt-in WhatsApp](/academy/it/articles/whatsapp-opt-in-how-to-collect-consent/).

## La risposta: un tocco su un metodo di rimborso

Al momento dell'invio, ogni risposta rapida riceve un payload come `refund:card:123134564567890` o `refund:credit:123134564567890`. Il tocco arriva come webhook `messages` con `type: "button"`, `button.payload`, `button.text` e `context.id`, il wamid del modello. Abbina su `context.id`, perché Meta omette `from` quando l'utente ha uno username e nessun numero di telefono disponibile. La struttura completa è nell'articolo sulla conferma d'ordine.

Il tocco apre la finestra di 24 ore, quindi la risposta «Ricevuto, credito in negozio» può essere testo libero. Un cliente che invece scrive una domanda va a una persona. Un cliente che cambia idea tocca di nuovo, e nella tua tabella vale l'ultimo tocco finché il reso non viene elaborato.

## La scrittura: la tua tabella, un tag, poi returnProcess

Shopify non ha un campo per il metodo di rimborso preferito. Salva la scelta nella tua tabella dei resi, che è il record che il tuo codice leggerà dopo. Poi aggiungi un tag all'ordine con `tagsAdd`, per esempio `refund-pref:store-credit`, così lo staff vede la scelta nell'admin. `tagsAdd` aggiunge senza sovrascrivere, a differenza di `orderUpdate`, come mostra l'articolo su Shopify.

Applica la scelta quando il reso viene elaborato. `returnProcess` «Richiede lo scope di accesso `write_returns` o `write_marketplace_returns`» ([returnProcess, consultato il 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/mutations/returnProcess)). L'input di esempio di Shopify rimborsa tramite `financialTransfer.issueRefund.orderTransactions`, ciascuna con un `transactionAmount` e il `parentId` della `OrderTransaction` originale. La risposta restituisce `returnProcess.return.id` e `userErrors`.

Il credito in negozio passa da `refundMethods`. `ReturnProcessRefundInput` ha `orderTransactions` (obbligatorio), `refundMethods` e `allowOverRefunding` ([ReturnProcessRefundInput, consultato il 2026-11-27](https://shopify.dev/docs/api/admin-graphql/latest/input-objects/ReturnProcessRefundInput)). `RefundMethodInput.storeCreditRefund` accetta un `amount` e un `expiresAt` facoltativo. Shopify precisa che «I rimborsi emessi come credito in negozio non possono superare l'importo pagato». Shopify non mostra un esempio completo di credito in negozio, quindi il body per il credito nel servizio non è stato provato. In particolare, non è stato provato se Shopify accetta un elenco `orderTransactions` vuoto.

Imposta `notifyCustomer: false`. Con `true`, Shopify manda un'email al cliente, e il tuo messaggio WhatsApp glielo direbbe una seconda volta.

L'importo resta una decisione dello staff. Ispezione, costi di riassortimento e spedizione lo cambiano, quindi il servizio espone un endpoint interno che il tuo back office chiama con l'ID del reso e l'importo. Il tocco del cliente decide il metodo, e una persona decide la cifra. Se il cliente non ha mai toccato, il servizio rimborsa sul metodo di pagamento originale. Quel default è una nostra scelta.

## Il servizio completo

Questo file per Node 18+ gira con `npm install express`. Verifica le firme di entrambi i webhook, deduplica consegne, eventi di reso e messaggi di Meta, e scrive tramite la Admin GraphQL API, versione 2026-10. Nell'esempio lo stato vive in memoria; in produzione usa tabelle con chiavi univoche.

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

Il messaggio di rimborso avvenuto parte da un solo punto per ogni reso. L'endpoint interno lo invia quando è il tuo servizio ad aver elaborato il reso. `refunds/create` lo invia quando lo staff ha rimborsato dall'admin di Shopify, e passa a una persona quando i campi delle transazioni nel payload non si riescono a leggere. Lo attiva anche un rimborso su quell'ordine che non fa parte del reso. Se il tuo staff emette rimborsi di questo tipo, invia il messaggio di rimborso solo dall'endpoint interno.

## Quando qualcosa fallisce

Se il cliente non tocca mai, nulla resta in attesa di lui. Lo staff elabora il reso come al solito, e il servizio rimborsa sul metodo di pagamento originale. Il TTL di 12 ore scarta un messaggio di approvazione che non è stato consegnato in tempo, e Meta non indica alcun codice di errore per quello scarto.

Shopify può consegnare lo stesso webhook più di una volta, quindi il servizio salta un `X-Shopify-Webhook-Id` ripetuto. Il servizio usa anche come chiave di ogni messaggio l'ID del reso più lo stato, così uno stato ripetuto non invia mai un secondo messaggio. Meta può reinviare un tocco, quindi il servizio salta un `messages[].id` ripetuto. Un invio fallito rimuove la chiave dell'evento e va a una persona, perché Shopify ha già ricevuto il suo 200 e non ritenterà.

Una risposta STOP aggiunge sia il telefono sia il `from_user_id` a un elenco di opt-out che ogni invio controlla. Registrala anche nella tua tabella dei consensi, così l'ordine successivo non la riattiva.

Se `returnProcess` restituisce `userErrors`, l'endpoint risponde 422 e lascia il reso aperto, con il tag che mostra ancora la scelta del cliente. Una persona lo elabora poi nell'admin. La pagina di Shopify non dice quale webhook scatta quando lo staff crea un reso già aperto con `returnCreate`, quindi prova quel percorso prima di fare affidamento su `returns/approve`.

## Dove si colloca Z-API Omni

Omni non ha un'integrazione Shopify documentata, quindi il servizio qui sopra resta il ponte. Sull'API ufficiale di Meta, i modelli partono tramite `POST https://api.omni.z-api.io/v1/channels/{channelId}/messages` con una Secret Key `Bearer`, e la creazione dei modelli accetta `message_send_ttl_seconds`. Un canale disconnesso restituisce `422` con `subCode: CHANNEL_DISCONNECTED`, e il messaggio non viene inviato. Le risposte in testo libero arrivano come `MESSAGE_RECEIVED`, ma la documentazione non mostra ancora la struttura in arrivo di un tocco su una risposta rapida.

Un solo abbonamento copre WhatsApp, Messenger, Instagram e Telegram, da US$29 per numero al mese da 1 a 10 numeri fino a US$20 oltre 100. I webhook sono inclusi senza limite. Sulla connessione ufficiale, le tariffe di Meta vengono riaddebitate.

<!-- TODO:test Omni snippet: send return_refunded_v1 on a META_WHATSAPP channel; check whether named body params need parameter_name, and the inbound JSON of a quick-reply tap on return_approved_v1 -->
```bash
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"}]}]}}]}}'
```

[Vedi la documentazione](https://developer.omni.z-api.io/en)

*Il team di Z-API Omni*
