# Avviso di consegna fallita su WhatsApp con pulsanti per riprogrammare

> Trasforma il webhook taskFailed di Onfleet in un modello utility WhatsApp con le risposte Reschedule e Leave with neighbor, poi clona il task per il nuovo tentativo.

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

Quando un autista segna una consegna come fallita, invia un modello UTILITY che nomina l'ordine. Offri tre risposte rapide: Reschedule (Riprogramma), Leave with neighbor (Lascia al vicino), Fix my address (Correggi il mio indirizzo). Il tocco torna come messaggio `button` con un payload impostato da te, così sai a quale task appartiene. Poi riscrivi la risposta nel sistema di consegna: in Onfleet, clona il task fallito con una nuova finestra o nuove note.

Questo articolo costruisce quel ciclo con Onfleet come piattaforma di consegna e la WhatsApp Cloud API dal lato di Meta. I pulsanti generici per gli ordini sono trattati in [conferma d'ordine con i pulsanti Confirm e Cancel](/academy/it/articles/whatsapp-order-confirmation-confirm-cancel-buttons/). La versione promemoria dello stesso schema è in [promemoria degli appuntamenti con Confirm e Reschedule](/academy/it/articles/whatsapp-appointment-reminders-confirm-reschedule/). [Un messaggio «tecnico in arrivo»](/academy/it/articles/field-service-technician-on-the-way-whatsapp/) lo applica agli interventi sul campo, con codici del cancello e richieste di riprogrammazione che tornano come risposte.

## L'evento: il webhook taskFailed di Onfleet

Onfleet invia un webhook per ogni trigger, e `taskFailed` è il trigger `4` ([webhook di Onfleet, consultato il 2026-11-25](https://docs.onfleet.com/reference/webhooks.md)). Ogni richiesta contiene `time`, `triggerId` e `triggerName`. Gli oggetti completi arrivano in `data`, per esempio `data.task`, con `taskId` accanto a seconda del trigger. Onfleet avverte che «tutte le altre proprietà non pertinenti al trigger possono essere fornite come `null`», e la sua pagina non mostra un payload di esempio per `taskFailed`.

L'oggetto task contiene ciò che serve al messaggio ([ottenere un singolo task, consultato il 2026-11-25](https://docs.onfleet.com/reference/get-single-task.md)):

| Campo | A cosa ti serve |
| --- | --- |
| `completionDetails.success` | `false` in un tentativo fallito |
| `completionDetails.failureReason` | Una stringa libera; Onfleet non documenta un elenco di valori |
| `failureNotes` | La nota dell'autista |
| `recipients[].phone` | E.164, per esempio `+16502837547` |
| `recipients[].skipSMSNotifications` | Se gli SMS di Onfleet sono disattivati |
| `shortId`, `trackingURL` | Il riferimento che il cliente riconosce |
| `metadata` | I tuoi campi, come l'opt-in WhatsApp |

Non ramificare sui valori di `failureReason`. L'esempio di Onfleet mostra `"NONE"` e nient'altro, quindi registra la stringa e lascia che sia la scelta del cliente a guidare il passo successivo. I timestamp sono millisecondi dall'epoch, e i telefoni vengono restituiti «sempre» in E.164 ([tipi di dati, consultato il 2026-11-25](https://docs.onfleet.com/reference/data-types-and-response-formats.md)). Togli il `+` prima di inviare.

### Firma, validazione e timeout di 10 secondi

Onfleet firma ogni richiesta in `X-Onfleet-Signature` con HMAC-SHA512 sul body grezzo ([secret, consultato il 2026-11-25](https://docs.onfleet.com/reference/secrets.md)). Il secret di Dashboard > Configuration > API & Webhook è una stringa esadecimale. Decodificalo da esadecimale in byte prima di calcolare l'HMAC, altrimenti ogni firma fallirà.

Quando crei il webhook, Onfleet invia `GET <url>?check=<random>` senza firma. Restituisci la stringa con HTTP 200; la pagina di Onfleet dice che «HTTP 204 non è accettato» ([validazione, consultato il 2026-11-25](https://docs.onfleet.com/reference/validation.md)). Il timeout è di 10 secondi. Onfleet ritenta una richiesta andata in timeout ogni 30 secondi e disattiva il webhook dopo 300 errori consecutivi. Restituisci prima 200 e fai il lavoro dopo, oppure dietro una coda.

### Se tracci i corrieri con EasyPost

EasyPost è adatto quando i pacchi viaggiano con corrieri che non gestisci tu. Il suo evento `tracker.updated` contiene `result`, il Tracker, il cui `status` include `out_for_delivery`, `failure` e `return_to_sender` ([guida ai webhook, consultato il 2026-11-25](https://docs.easypost.com/guides/webhooks-guide)). Il campo `status_detail` aggiunge valori come `delivery_exception` e `refused` ([tracker, consultato il 2026-11-25](https://docs.easypost.com/docs/trackers)). Quale di questi indichi un tentativo fallito lo decidi tu.

Per questo scopo EasyPost è in sola lettura. Non permette di riprogrammare, quindi la risposta va al tuo record di consegna. Le richieste portano `X-Hmac-Signature` quando imposti un secret per il webhook, e i passaggi di verifica sono nell'[articolo di EasyPost sulla validazione HMAC](https://support.easypost.com/hc/en-us/articles/39826034964237-Webhook-HMAC-Validation). EasyPost si aspetta una risposta «entro sette secondi».

## Il messaggio: un modello utility a cui il cliente può rispondere

Un avviso di consegna fallita rientra nel caso utility Order Management di Meta: «Confermare, aggiornare o annullare un ordine o una transazione con un cliente» ([categorizzazione dei modelli, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization.md)). Riguarda un solo ordine ed è attivato da quell'ordine. Aggiungi uno sconto o un cross-sell e Meta lo tratta come contenuto misto, cioè marketing. Le regole sono in [le categorie dei modelli](/academy/it/articles/whatsapp-template-categories-marketing-utility-authentication/).

Meta penalizza un modello con la categoria sbagliata per gradi. Si parte con un avviso scritto, poi un limite di frequenza sui modelli utility per almeno 7 giorni. Segue una restrizione utility di 7 giorni, 30 in caso di recidiva, durante la quale «Tutti i modelli utility approvati … vengono ricategorizzati come `MARKETING`». L'ultimo gradino è una restrizione del portfolio aziendale di 30 giorni.

### Template Library o modello personalizzato

La [Template Library](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-library.md) di Meta (consultata il 2026-11-25) accetta `DELIVERY_FAILED` come filtro `usecase`. L'unico modello mostrato per intero è `delivery_failed_2_form`, categoria UTILITY, con un pulsante Flow etichettato "Reschedule". Il suo corpo dice «Non siamo riusciti a consegnare oggi l'ordine {{1}}. {{2}} per programmare un altro tentativo di consegna.» Meta aggiunge che «I moduli sono disponibili solo per gli account a cui sono stati aumentati i limiti di messaggistica», e il testo della libreria non si può modificare. I dettagli sono in [l'articolo sulla Template Library](/academy/it/articles/whatsapp-template-library-prebuilt-templates/).

Un modello personalizzato ti dà tre risposte invece di una. Meta consente fino a 10 pulsanti di risposta rapida, con etichette di «massimo 25 caratteri» ([componenti, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/components.md)). Le risposte rapide e gli altri tipi di pulsante devono stare in due gruppi separati.

Imposta un time-to-live breve. I modelli utility hanno per default 30 giorni, e `message_send_ttl_seconds` accetta da 30 a 43.200 secondi ([time-to-live, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live.md)). Un messaggio non consegnato entro il TTL viene scartato. Tre ore evitano che un avviso «oggi non ti abbiamo trovato» arrivi la mattina dopo. La riclassificazione azzera il TTL, quindi controllalo dopo ogni cambio di categoria.

```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": "delivery_missed_today",
    "language": "en_US",
    "category": "UTILITY",
    "message_send_ttl_seconds": 10800,
    "components": [
      {
        "type": "BODY",
        "text": "We could not deliver order {{1}} today. Choose what happens next and we will update the delivery.",
        "example": { "body_text": [["8812"]] }
      },
      {
        "type": "BUTTONS",
        "buttons": [
          { "type": "QUICK_REPLY", "text": "Reschedule" },
          { "type": "QUICK_REPLY", "text": "Leave with neighbor" },
          { "type": "QUICK_REPLY", "text": "Fix my address" }
        ]
      }
    ]
  }'
```

La pagina di Meta sul TTL dice di impostare il campo su `/<PHONE_NUMBER_ID>/message_templates`. I modelli appartengono al WhatsApp Business Account, quindi la chiamata qui sopra usa l'ID della WABA.

## La risposta: cosa ti invia ogni tocco

Un tocco sulla risposta rapida di un modello arriva come `type: "button"`, attivato quando «Un utente WhatsApp tocca un pulsante di risposta rapida in un messaggio modello» ([webhook button, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button.md)). Contiene `button.payload`, `button.text` e `context.id`, il wamid del modello. `from` manca quando l'utente ha adottato uno username, mentre `from_user_id` è sempre presente.

Puoi impostare il payload per ogni invio con un componente `button` con `sub_type: "quick_reply"`. Meta documenta quel payload come il «Valore da includere nei webhook dei messaggi (`messages.button.payload`) quando il pulsante viene toccato» nella sua [pagina sui modelli carosello](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/marketing-templates/media-card-carousel-templates.md). Mettici l'ID del task di Onfleet. Questo messaggio è costruito a partire dall'elenco dei campi del riferimento:

```json
{
  "from": "16502837547",
  "from_user_id": "BSUID_OF_THE_USER",
  "id": "wamid.INBOUND_MESSAGE_ID",
  "timestamp": "1795608000",
  "type": "button",
  "context": { "from": "BUSINESS_NUMBER", "id": "wamid.TEMPLATE_MESSAGE_ID" },
  "button": { "payload": "resched:TASK_ID", "text": "Reschedule" }
}
```

Il tocco apre la finestra di 24 ore, quindi i messaggi successivi possono essere messaggi di sessione. Reschedule invia pulsanti di risposta con due fasce orarie, e la scelta arriva come `interactive.button_reply` con il tuo `id`. Fix my address invia un `location_request_message` con `action.name: "send_location"` ([messaggi di richiesta della posizione, consultato il 2026-11-25](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/location-request-messages.md)). La risposta è `type: "location"` con `latitude` e `longitude`, più `context.id`.

L'indice della documentazione di Meta elenca una pagina sul modello di richiesta della posizione, ma il 2026-11-25 restituiva pagina non trovata. Questo ciclo chiede la posizione solo dopo il tocco, dentro la finestra. Il messaggio di richiesta e le regole della sua finestra sono trattati in [messaggi di posizione e contatti](/academy/it/articles/whatsapp-location-contacts-messages/).

## Il servizio: arriva il webhook, parte il modello, si clona il task

Questo servizio Node 18 riceve i webhook di Onfleet e di Meta, verifica entrambe le firme e invia il modello. Clona il task appena il cliente sceglie. Per brevità lo stato vive in memoria; in produzione usa tabelle di database con chiavi univoche.

```js
// delivery-loop.mjs. Run: npm install express && node delivery-loop.mjs
// Env: ONFLEET_API_KEY, ONFLEET_WEBHOOK_SECRET (hex), WA_TOKEN, PHONE_NUMBER_ID,
//      APP_SECRET, VERIFY_TOKEN, PORT
import crypto from 'node:crypto';
import express from 'express';

const env = process.env;
const GRAPH = `https://graph.facebook.com/v26.0/${env.PHONE_NUMBER_ID}/messages`;
const ONFLEET = 'https://onfleet.com/api/v2';
const onfleetAuth = 'Basic ' + Buffer.from(`${env.ONFLEET_API_KEY}:`).toString('base64');

const seen = new Set();       // processed event keys
const tasks = new Map();      // taskId -> { phone, shortId, state }
const outbound = new Map();   // wamid we sent -> taskId
const optedOut = new Set();   // phones that replied STOP
const ACTIONS = { 'Reschedule': 'resched', 'Leave with neighbor': 'neighbor', 'Fix my address': 'address' };

const app = express();

function sameHex(expected, received) {
  const a = Buffer.from(expected, 'hex');
  const b = Buffer.from(String(received || ''), 'hex');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

async function call(url, init, tries = 3) {
  for (let i = 1; ; i++) {
    const res = await fetch(url, init);
    if (res.ok) return res.status === 204 ? null : res.json();
    const retryable = res.status === 429 || res.status >= 500;
    if (!retryable || i >= tries) throw new Error(`${init.method} ${url} -> ${res.status} ${await res.text()}`);
    await new Promise((r) => setTimeout(r, 1000 * 2 ** i));
  }
}

async function sendWhatsApp(message) {
  const body = await call(GRAPH, {
    method: 'POST',
    headers: { Authorization: `Bearer ${env.WA_TOKEN}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ messaging_product: 'whatsapp', recipient_type: 'individual', ...message }),
  });
  return body.messages?.[0]?.id; // accepted by the API, not yet delivered
}

const onfleet = (path, method = 'GET', body) => call(`${ONFLEET}${path}`, {
  method,
  headers: { Authorization: onfleetAuth, 'Content-Type': 'application/json' },
  body: body ? JSON.stringify(body) : undefined,
});

// TODO:test Onfleet does not say whether a failed task accepts a metadata update.
async function addNote(taskId, name, value) {
  const task = await onfleet(`/tasks/${taskId}`);
  const metadata = (task.metadata ?? []).filter((m) => m.name !== name);
  metadata.push({ name, type: 'string', value, visibility: ['api'] });
  await onfleet(`/tasks/${taskId}`, 'PUT', { metadata }); // send the full array
}

// TODO:test Onfleet does not say whether a failed task can be cloned.
async function cloneTask(taskId, overrides) {
  return onfleet(`/tasks/${taskId}/clone`, 'POST', {
    options: { includeMetadata: true, includeBarcodes: false, includeDependencies: false },
    overrides,
  });
}

function tomorrow(fromHour, toHour) { // server time zone; use the destination's in production
  const day = new Date();
  day.setDate(day.getDate() + 1);
  const after = new Date(day); after.setHours(fromHour, 0, 0, 0);
  const before = new Date(day); before.setHours(toHour, 0, 0, 0);
  return { completeAfter: after.getTime(), completeBefore: before.getTime() };
}

const hasOptIn = (task) => (task.metadata ?? []).some((m) => m.name === 'whatsapp_opt_in' && m.value === true);

async function handleOnfleet(event) {
  if (event.triggerId !== 4) return; // taskFailed
  const task = event.data?.task;
  const taskId = event.taskId ?? task?.id;
  if (!task || !taskId || seen.has(`failed:${taskId}`)) return;
  seen.add(`failed:${taskId}`);
  if (task.completionDetails?.success !== false) return;
  const recipient = task.recipients?.[0];
  const phone = recipient?.phone?.replace(/^\+/, '');
  if (!phone || optedOut.has(phone) || !hasOptIn(task)) return;
  if (!recipient.skipSMSNotifications) console.warn(`task ${task.shortId}: Onfleet SMS is also on`);
  console.log('failed', task.shortId, task.completionDetails?.failureReason, task.failureNotes);

  tasks.set(taskId, { phone, shortId: task.shortId, state: 'asked' });
  const wamid = await sendWhatsApp({
    to: phone,
    type: 'template',
    template: {
      name: 'delivery_missed_today',
      language: { code: 'en_US' },
      components: [
        { type: 'body', parameters: [{ type: 'text', text: task.shortId }] },
        ...['resched', 'neighbor', 'address'].map((action, i) => ({
          type: 'button', sub_type: 'quick_reply', index: String(i),
          parameters: [{ type: 'payload', payload: `${action}:${taskId}` }],
        })),
      ],
    },
  });
  outbound.set(wamid, taskId);
}

async function finish(taskId, t, overrides, note) {
  t.state = 'done';
  let clone;
  try {
    clone = await cloneTask(taskId, overrides);
  } catch (err) {
    await sendWhatsApp({ to: t.phone, type: 'text', text: { body: 'Thanks. A dispatcher will confirm the new attempt.' } });
    throw err; // logged by the caller; the failed task stays in the dispatcher's queue
  }
  await addNote(taskId, 'whatsapp_outcome', `${note} (new task ${clone.shortId})`);
  await sendWhatsApp({ to: t.phone, type: 'text', text: { body: `Done. Track the new attempt here: ${clone.trackingURL}` } });
}

async function handleReply(msg) {
  if (seen.has(msg.id)) return;
  seen.add(msg.id);
  const user = msg.from_user_id; // always present; msg.from is omitted for users with a username
  const mine = (t) => (msg.from && t.phone === msg.from) || (user && t.userId === user);
  let action; let taskId; let extra;
  if (msg.type === 'button') {
    [action, taskId] = String(msg.button?.payload ?? '').split(':');
    if (!taskId) { action = ACTIONS[msg.button?.text]; taskId = outbound.get(msg.context?.id); }
  } else if (msg.type === 'interactive' && msg.interactive?.type === 'button_reply') {
    [action, taskId, extra] = String(msg.interactive.button_reply.id).split(':');
  } else if (msg.type === 'location') {
    action = 'location'; taskId = outbound.get(msg.context?.id);
  } else if (msg.type === 'text') {
    const text = msg.text?.body?.trim() ?? '';
    if (/^stop$/i.test(text)) {
      const phone = msg.from ?? [...tasks.values()].find(mine)?.phone;
      if (phone) optedOut.add(phone); else console.warn('STOP from an unmatched user', user); // a person handles it
      return;
    }
    const waiting = [...tasks].find(([, t]) => mine(t) && t.state === 'await_neighbor');
    if (!waiting) return; // free text without a pending question goes to a person
    [taskId] = waiting; action = 'neighbor_text'; extra = text;
  }
  const t = tasks.get(taskId);
  if (!t || t.state === 'done') return;
  if (user) t.userId = user; // lets later free text and STOP match without msg.from
  const stamp = new Date().toISOString();

  if (action === 'resched') {
    t.state = 'await_slot';
    await sendWhatsApp({ to: t.phone, type: 'interactive', interactive: {
      type: 'button',
      body: { text: `Pick a new window for order ${t.shortId}.` },
      action: { buttons: [
        { type: 'reply', reply: { id: `slot:${taskId}:am`, title: 'Tomorrow morning' } },
        { type: 'reply', reply: { id: `slot:${taskId}:pm`, title: 'Tomorrow afternoon' } },
      ] },
    } });
  } else if (action === 'slot') {
    const window = extra === 'am' ? tomorrow(9, 13) : tomorrow(14, 18);
    await finish(taskId, t, window, `Rescheduled by customer via WhatsApp at ${stamp}`);
  } else if (action === 'neighbor') {
    t.state = 'await_neighbor';
    await sendWhatsApp({ to: t.phone, type: 'text', text: { body: "Reply with the neighbor's name and door number. The driver will hand it only to that person." } });
  } else if (action === 'neighbor_text') {
    const notes = `Leave with neighbor: ${extra.slice(0, 200)}. Approved by +${t.phone} via WhatsApp at ${stamp}.`;
    await finish(taskId, t, { notes, ...tomorrow(9, 18) }, notes);
  } else if (action === 'address') {
    t.state = 'await_location';
    const wamid = await sendWhatsApp({ to: t.phone, type: 'interactive', interactive: {
      type: 'location_request_message',
      body: { text: `Share the exact spot for order ${t.shortId}. A dispatcher checks it before the next attempt.` },
      action: { name: 'send_location' },
    } });
    outbound.set(wamid, taskId);
  } else if (action === 'location') {
    t.state = 'done';
    const { latitude, longitude } = msg.location ?? {};
    await addNote(taskId, 'customer_location', `${latitude},${longitude} shared at ${stamp}`);
    await sendWhatsApp({ to: t.phone, type: 'text', text: { body: 'Thanks. A dispatcher will confirm the new attempt.' } });
  }
}

app.get('/onfleet', (req, res) => res.status(200).type('text/plain').send(String(req.query.check ?? '')));

app.post('/onfleet', express.raw({ type: '*/*' }), (req, res) => {
  const key = Buffer.from(env.ONFLEET_WEBHOOK_SECRET, 'hex');
  const expected = crypto.createHmac('sha512', key).update(req.body).digest('hex');
  if (!sameHex(expected, req.get('X-Onfleet-Signature'))) return res.sendStatus(401);
  res.sendStatus(200); // inside Onfleet's 10-second timeout
  let event;
  try { event = JSON.parse(req.body.toString('utf8')); } catch { return; }
  handleOnfleet(event).catch((err) => console.error('onfleet', err.message));
});

app.get('/whatsapp', (req, res) => {
  const ok = req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === env.VERIFY_TOKEN;
  return ok ? res.send(req.query['hub.challenge']) : res.sendStatus(403);
});

app.post('/whatsapp', express.raw({ type: '*/*' }), (req, res) => {
  const expected = crypto.createHmac('sha256', env.APP_SECRET).update(req.body).digest('hex');
  const received = String(req.get('X-Hub-Signature-256') || '').replace(/^sha256=/, '');
  if (!sameHex(expected, received)) return res.sendStatus(401);
  res.sendStatus(200);
  let body;
  try { body = JSON.parse(req.body.toString('utf8')); } catch { return; }
  for (const entry of body.entry ?? []) {
    for (const change of entry.changes ?? []) {
      for (const msg of change.value?.messages ?? []) {
        handleReply(msg).catch((err) => console.error('reply', err.message));
      }
    }
  }
});

app.listen(Number(env.PORT) || 3000);
```

Imposta `whatsapp_opt_in` come voce di metadata booleana quando crei il task dal checkout. Il formato dei metadata di Onfleet è `{name, type, value, visibility}` ([metadata, consultato il 2026-11-25](https://docs.onfleet.com/reference/metadata.md)). Onfleet non dice se un aggiornamento unisce o sostituisce l'array, quindi `addNote` legge il task e rimanda l'array completo.

Onfleet consente solo modifiche a `notes` e `metadata` sui task attivi, e solo a `metadata` e `customFields` su quelli completati ([aggiornare un task, consultato il 2026-11-25](https://docs.onfleet.com/reference/update-task.md)). La sua pagina non tratta i task falliti. Un task fallito sembra un task completato con `success: false`, quindi la chiamata sui metadata dovrebbe funzionare, ma provala. Lo stesso vale per la clonazione di un task fallito, di cui la [pagina sulla clonazione dei task](https://docs.onfleet.com/reference/clone-task.md) non parla.

La clonazione accetta `overrides` come `notes`, `completeAfter` e `completeBefore`. Entrambi gli orari devono essere nel futuro, in millisecondi, e `completeBefore` deve venire dopo `completeAfter`. La risposta contiene i nuovi `id`, `shortId`, `trackingURL` e `sourceTaskId`. Fix my address non clona in automatico. Salva il punto sul task originale per un dispatcher, perché una nuova destinazione deve essere controllata da una persona.

## Gestione degli errori: duplicati, silenzio, opt-out e nuovi tentativi

Onfleet manda un SMS al destinatario a meno che non sia impostato `skipSMSNotifications`, quindi un cliente può ricevere un SMS e un messaggio WhatsApp per lo stesso tentativo fallito. Imposta il flag sui task il cui cliente ha dato l'opt-in a WhatsApp. Il servizio registra un avviso quando trova il flag disattivato.

Onfleet ritenta le richieste andate in timeout ogni 30 secondi, quindi il servizio usa come chiave l'ID del task fallito. Meta può consegnare lo stesso messaggio più di una volta, quindi il servizio salta ogni `id` di messaggio già visto.

Se il cliente non risponde mai, sul task non cambia nulla. Il modello viene scartato se non viene consegnato entro tre ore. Se viene consegnato e ignorato, il task fallito resta nella coda del dispatcher secondo la tua procedura abituale. Non inviare un secondo modello per lo stesso task.

Nell'uso reale due tocchi possono competere: un cliente tocca Reschedule, poi Leave with neighbor. Il controllo su `state` fa vincere la prima azione completata e ignora le altre. In un database, rendilo un aggiornamento atomico sulla riga del task.

Una risposta STOP finisce in una lista di opt-out che blocca gli invii futuri. Il servizio salva `from_user_id` al primo tocco, così STOP e il nome del vicino trovano comunque una corrispondenza quando manca `from`. Il trigger `SMSRecipientOptOut` di Onfleet, il `17`, copre solo il suo canale SMS. Il consenso per WhatsApp è separato e va raccolto al checkout, come in [come raccogliere l'opt-in WhatsApp](/academy/it/articles/whatsapp-opt-in-how-to-collect-consent/).

"Leave with neighbor" sposta la responsabilità del pacco. Il servizio scrive nelle note del nuovo task chi l'ha approvato, da quale numero e quando. Sono i tuoi termini a stabilire se quell'approvazione basta.

Le chiamate a Graph e a Onfleet ritentano su 429 e 5xx con backoff, e si fermano sugli altri 4xx. Anche i messaggi successivi costano. Dal 2026-10-01 Meta addebita i messaggi di servizio oltre i 1.000 per numero al mese, e i modelli utility dentro la finestra sono a pagamento. I dettagli sono in [gli addebiti di Meta sui messaggi di servizio](/academy/it/articles/meta-whatsapp-service-message-charges-october-2026/).

## Dove si colloca Z-API Omni

Sull'API ufficiale di Meta, il modello parte da una sola route, `POST /v1/channels/{channelId}/messages` con `content.type: "TEMPLATE"`. I modelli si creano sulla WABA con `message_send_ttl_seconds`, dove `-1` significa 30 giorni. La documentazione mostra pulsanti `QUICK_REPLY` nei modelli. Non mostra un `payload` per pulsante al momento dell'invio né il webhook prodotto da un tocco, quindi la richiesta qui sotto invia solo il parametro del corpo e il tocco va provato. Le risposte in testo libero sono documentate come `MESSAGE_RECEIVED`, mentre le richieste di posizione sono segnate «In sviluppo». I webhook sono inclusi senza limiti e portano `x-webhook-delivery-id` per la deduplica. Il prezzo è per numero, US$29 al mese da 1 a 10 numeri, e le tariffe di Meta vengono riaddebitate sulla connessione ufficiale.

<!-- TODO:test Omni snippet: send delivery_missed_today on a META_WHATSAPP channel; check the 200 messageId and the webhook shape when the customer taps a quick reply -->
```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":"16502837547"},"content":{"type":"TEMPLATE","attachments":[{"template":{"name":"delivery_missed_today","language":{"policy":"deterministic","code":"en_US"},"components":[{"type":"body","parameters":[{"type":"text","text":"8812"}]}]}}]}}'
```

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

*Il team di Z-API Omni*
