WhatsApp· 7 min di lettura

Stato degli ordini WooCommerce su WhatsApp con i webhook, senza plugin


Punta un webhook WooCommerce con topic order.updated verso il tuo servizio e verifica X-WC-Webhook-Signature. Poi invia un modello utility WhatsApp solo quando lo stato dell’ordine è diverso dall’ultimo per cui hai inviato un messaggio. WooCommerce non invia lo stato precedente, e la documentazione non descrive nuovi tentativi. Rispondi a ogni consegna con un 2xx rapido e salva tu l’ultimo stato. Le risposte dei clienti tornano come note private sull’ordine tramite la REST API.

Il ciclo delle risposte (payload delle risposte rapide, abbinamento su context.id, aggiornamenti condizionali, silenzio) è in conferma d’ordine su WhatsApp con i pulsanti Confirm e Cancel. La versione per Shopify è webhook degli ordini Shopify verso WhatsApp. Questa pagina copre ciò che WooCommerce fa in modo diverso, in base alla sua documentazione e al sorgente del core in class-wc-webhook.php (trunk, letto il 2026-11-25).

Crea il webhook

Usa WooCommerce > Settings > Advanced > Webhooks, oppure la REST API. I topic degli ordini sono «order.created, order.updated e order.deleted» (webhook della REST API, consultato il 2026-11-25), e il sorgente aggiunge 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"'"
}'

Scegli un secret senza &, <, > né virgolette. Il sorgente firma applicando wp_specialchars_decode() al secret salvato, quindi eventuali entità HTML al suo interno cambierebbero la chiave.

Perché order.updated e non order.created

Il checkout a blocchi crea prima l’ordine come checkout-draft, e il codice dei webhook salta le bozze (DRAFT, AUTO_DRAFT, CHECKOUT_DRAFT, NEW). Secondo la nostra lettura del sorgente, la prima consegna per un ordine reale può quindi arrivare come order.updated. Non l’abbiamo confermato su un negozio reale. Iscriversi a order.updated e basarsi su status funziona in entrambi i casi.

Com’è fatta una consegna

Ogni consegna è una POST con gli header X-WC-Webhook-Source, -Topic, -Resource, -Event, -Signature, -ID e -Delivery-ID. Il body è trim( wp_json_encode( $payload ) ). La firma è base64_encode( hash_hmac( 'sha256', $payload, wp_specialchars_decode( $secret, ENT_QUOTES ), true ) ) calcolata su quel body. SHA-256 è il default, e un filtro può cambiarlo.

Verifica sui byte grezzi. La firma non copre alcun timestamp, e l’ID di consegna è un hash dell’ID del webhook e del secondo corrente. Nessuno dei due aiuta con la deduplica, quindi costruisci una tua chiave con ID dell’ordine, stato e date_modified_gmt.

Il ping di attivazione non ha firma

Quando un webhook viene salvato come attivo, WooCommerce invia un ping con il body codificato come form webhook_id=<ID> e nessun header di firma. Una risposta diversa da 2xx produce “Error: Delivery URL returned response code”. Rispondi al ping con 200 e non fare altro. Rifiutarlo perché manca la firma blocca l’attivazione.

Il payload viene costruito al momento della consegna

Per impostazione predefinita le consegne girano in modo asincrono tramite Action Scheduler. Quando il job parte, deliver() chiama build_payload(), che legge l’ordine da /wc/v3/orders/<id> in quel momento. Il body mostra l’ordine com’è al momento della consegna, non al momento dell’evento. Un commento nel sorgente dice anche «Make webhooks unique - only schedule one webhook every 10 minutes» (rendi unici i webhook: pianificane solo uno ogni 10 minuti).

Due cambi di stato ravvicinati possono quindi arrivare come una sola consegna, oppure come due che mostrano entrambe l’ultimo stato. Il payload non ha un campo per lo stato precedente. Salva per ogni ordine lo stato per cui hai inviato l’ultimo messaggio, e agisci solo quando quello nuovo è diverso. La stessa regola assorbe le tue scritture: un PUT a cancelled attiva woocommerce_update_order, e il tuo servizio riceve quel cambiamento come webhook. L’ordine degli eventi in generale è trattato in webhook fuori ordine.

Nessun nuovo tentativo, e cinque errori lo disattivano

Il codice del core non mostra alcun nuovo tentativo. Le consegne fallite contano solo verso un limite: if ( $failures > apply_filters( 'woocommerce_max_webhook_delivery_failures', 5 ) ), e lo stato del webhook diventa disabled. La documentazione dice lo stesso: «Dopo 5 consegne fallite consecutive (definite da un codice di risposta HTTP diverso da 2xx)», dopodiché lo riattivi tramite REST.

Restituisci 2xx prima di qualsiasi chiamata WhatsApp, e metti il lavoro in coda. Esegui un cron che legge lo status del webhook e manda un avviso quando vale disabled. Né la documentazione né il codice del core descrivono un reinvio, quindi un passaggio di riconciliazione sugli ordini modificati di recente chiude il buco. Lo schema di idempotenza è in webhook duplicati e idempotenza.

Associa ogni stato a un messaggio utility

Ogni messaggio qui sotto riguarda l’ordine del cliente e non contiene offerte, e questo lo mantiene dentro la definizione utility di Meta. Meta tratta come marketing «un aggiornamento dell’ordine con una promozione» (categorizzazione dei modelli, consultato il 2026-11-25). I valori di status vengono dalla REST API (ordini, consultato il 2026-11-25).

Stato Modello Corrispondente nella Template Library Contenuto
processing order_confirm_v1 ORDER_CONFIRMATION Numero, totale, risposte rapide Confirm e Cancel
on-hold order_on_hold_v1 Nessuno indicato “Order {{order_number}} is on hold until we receive payment.” (ordine in sospeso fino alla ricezione del pagamento)
completed order_shipped_v1 SHIPMENT_CONFIRMATION Corriere e un pulsante URL di tracciamento
cancelled order_cancelled_v1 ORDER_OR_TRANSACTION_CANCEL “Order {{order_number}} has been cancelled.” (ordine annullato)

order_confirm_v1 viene creato nell’articolo sulla conferma d’ordine, e order_shipped_v1 in quello su Shopify. Crea gli altri due allo stesso modo, come UTILITY con un parametro con nome. Tieni il testo dell’ordine in sospeso sui fatti. Un promemoria di pagamento con toni di pressione è un messaggio diverso, con regole diverse. Due messaggi del negozio fuori da questa tabella hanno pagine proprie: gli avvisi di prodotto di nuovo disponibile, che sono marketing, e gli aggiornamenti su resi e rimborsi, che restano utility.

Raccogli il consenso WhatsApp al checkout

WooCommerce non ha un campo per il consenso WhatsApp. Nel checkout a blocchi, registrane uno con woocommerce_register_additional_checkout_field su woocommerce_init (campi aggiuntivi del checkout, consultato il 2026-11-25). L’etichetta deve nominare il negozio e dire cosa riceve il cliente, secondo le regole dell’opt-in WhatsApp. Questo codice va nel functions.php del tuo tema o in un piccolo plugin del sito che gestisci tu.

<?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',
    ) );
} );

Il valore viene salvato come meta dell’ordine _wc_other/yourstore/whatsapp-updates, con valori della casella "1", "0" o "". La documentazione di WooCommerce non dice se quella chiave compare nei meta_data della REST che il payload del webhook trasporta. Il servizio qui sotto la legge da meta_data e non invia nulla quando manca, quindi in caso di dubbio non invia. Il checkout classico con shortcode richiede invece gli hook del checkout.

Il telefono è testo libero

billing.phone è una semplice stringa, e la tabella degli ordini v3 non elenca alcun shipping.phone. Normalizzalo con billing.country prima dell’invio, come descritto in formato dei numeri di telefono WhatsApp.

Salva la risposta come nota privata

Aggiungi una nota con POST /wp-json/wc/v3/orders/<id>/notes e un body {"note": "..."} (note degli ordini, consultato il 2026-11-25). Imposta customer_note su false. Con true, «la nota sarà mostrata ai clienti e questi riceveranno una notifica», quindi il cliente riceverebbe un’email sul proprio tocco. Non è stato provato se l’aggiunta di una nota attivi order.updated. Se lo fa, il controllo sullo stato lo assorbe.

Annulla con PUT /wp-json/wc/v3/orders/<id> e {"status": "cancelled"}. WooCommerce non impone alcuna finestra di annullamento, quindi il controllo sta nel tuo codice. Consenti un annullamento solo mentre lo stato è pending, on-hold o processing, e controlla il tuo plugin di spedizione se segna le spedizioni a parte.

L’annullamento non rimborsa il pagamento. Su woocommerce_order_status_cancelled, il core chiama wc_maybe_increase_stock_levels, che ripristina le scorte solo quando l’ordine ha il flag _order_stock_reduced (wc-stock-functions.php, letto il 2026-11-25). I rimborsi sono un passaggio separato, quindi un tocco su Cancel per un ordine pagato deve arrivare anche a una persona.

Il servizio completo

Questo file per Node 18+ gira con npm install express. Risponde al ping, verifica entrambi i webhook, invia un messaggio per ogni cambio di stato e gestisce i tocchi. In produzione tieni lastStatus in una tabella, altrimenti un riavvio reinvia lo stato corrente.

// 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 associa il Paese ISO in billing.country a un prefisso telefonico. Estendilo per i Paesi in cui vendi. Il lato Meta segue la verifica di X-Hub-Signature-256.

Quando qualcosa fallisce

Se l’invio WhatsApp genera un errore dopo il 2xx, l’errore va a una persona, e lo stato è già registrato. WooCommerce comunque non avrebbe ritentato. Se il tuo servizio è giù, le consegne falliscono e contano verso le cinque che disattivano il webhook. Il controllo via cron e il passaggio di riconciliazione sono l’unico modo per recuperare.

Un cliente che non tocca mantiene l’ordine così com’è. Il servizio non annulla mai per silenzio. Porta qui la gestione delle mancate risposte dall’articolo sulla conferma d’ordine. Un tocco su Cancel per un ordine completed riceve una risposta e un passaggio a una persona, mai un cambio di stato.

Dove si colloca Z-API Omni

Omni non documenta un’integrazione con WooCommerce, quindi il servizio qui sopra resta il ponte. Sul lato WhatsApp, gli stessi modelli passano da POST https://api.omni.z-api.io/v1/channels/{channelId}/messages con una Secret Key Bearer, e la sua documentazione include il componente payload della risposta rapida. La struttura in arrivo di un tocco non è ancora documentata. Un solo abbonamento copre WhatsApp, Messenger, Instagram e Telegram, quindi un avviso per il titolare del negozio su Telegram può partire dallo stesso account. Il prezzo è per numero: US$29 al mese da 1 a 10 numeri, US$26 da 11 a 50, US$23 da 51 a 100, US$20 oltre 100. La connessione QR non ha costi per messaggio, e sull’API ufficiale di Meta le tariffe di Meta vengono riaddebitate.

Vedi la documentazione

Il team di Z-API Omni