WhatsApp· 8 min read

WhatsApp failed delivery notice with reschedule buttons


When a driver marks a delivery as failed, send a UTILITY template that names the order. Offer three quick replies: Reschedule, Leave with neighbor, Fix my address. The tap comes back as a button message carrying a payload you set, so you know which task it belongs to. Then write the answer back to the delivery system: in Onfleet, clone the failed task with a new window or new notes.

This post builds that loop with Onfleet as the delivery platform and the WhatsApp Cloud API on Meta’s side. Generic order buttons are covered in order confirmation with Confirm and Cancel buttons. The reminder version of the same pattern is in appointment reminders with Confirm and Reschedule. A technician on-the-way message applies it to field service jobs, with gate codes and reschedule requests coming back as replies.

The event: Onfleet’s taskFailed webhook

Onfleet fires one webhook per trigger, and taskFailed is trigger 4 (Onfleet webhooks, accessed 2026-11-25). Every request carries time, triggerId and triggerName. Full objects arrive in data, for example data.task, with taskId alongside depending on the trigger. Onfleet warns that “all other properties not relevant to the trigger may be provided as null”, and its page shows no sample payload for taskFailed.

The task object holds what the message needs (get single task, accessed 2026-11-25):

Field What you use it for
completionDetails.success false on a failed attempt
completionDetails.failureReason A free string; Onfleet documents no list of values
failureNotes The driver’s note
recipients[].phone E.164, for example +16502837547
recipients[].skipSMSNotifications Whether Onfleet’s own SMS is off
shortId, trackingURL The reference the customer recognizes
metadata Your own fields, such as the WhatsApp opt-in

Don’t branch on failureReason values. Onfleet’s sample shows "NONE" and nothing else, so log the string and let the customer’s choice drive the next step. Timestamps are milliseconds since the epoch, and phones are “always” returned in E.164 (data types, accessed 2026-11-25). Strip the + before you send.

Signature, validation and the 10-second timeout

Onfleet signs each request in X-Onfleet-Signature with HMAC-SHA512 over the raw body (secrets, accessed 2026-11-25). The secret from Dashboard > Configuration > API & Webhook is a hex string. Hex-decode it to bytes before you compute the HMAC, or every signature will fail.

When you create the webhook, Onfleet sends GET <url>?check=<random> without a signature. Echo the string with HTTP 200; Onfleet’s page says “HTTP 204 is not accepted” (validation, accessed 2026-11-25). The timeout is 10 seconds. Onfleet retries a timed-out request every 30 seconds and disables the webhook after 300 consecutive failures. Return 200 first and do the work after, or behind a queue.

If you track carriers through EasyPost

EasyPost fits when parcels move through carriers you don’t dispatch. Its tracker.updated event carries result, the Tracker, whose status includes out_for_delivery, failure and return_to_sender (webhooks guide, accessed 2026-11-25). The status_detail field adds values such as delivery_exception and refused (trackers, accessed 2026-11-25). Which of them means a failed attempt is your call.

EasyPost is read-only for this purpose. It has no reschedule write-back, so the reply goes to your own delivery record. Requests carry X-Hmac-Signature when you set a webhook secret, and the verification steps are on EasyPost’s HMAC validation article. EasyPost expects a response “within seven seconds”.

The message: a utility template the customer can answer

A failed-delivery notice fits Meta’s Order Management utility case: “Confirm, update, or cancel an order or transaction with a customer” (template categorization, accessed 2026-11-25). It is specific to one order and triggered by that order. Add a discount or a cross-sell and Meta treats it as mixed content, which makes it marketing. The rules are in template categories.

Meta penalizes a miscategorized template on a ladder. It starts with a written warning, then utility rate-limiting for at least 7 days. Next comes a utility restriction of 7 days, 30 for repeats, during which “All approved utility templates … are recategorized to MARKETING”. The last step is a 30-day business portfolio restriction.

Template Library or a custom template

Meta’s Template Library (accessed 2026-11-25) accepts DELIVERY_FAILED as a usecase filter. The one template shown in full there is delivery_failed_2_form, category UTILITY, with a Flow button labeled “Reschedule”. Its body reads “We were unable to deliver order {{1}} today. Please {{2}} to schedule another delivery attempt.” Meta adds that “Forms are only available to accounts who have had their message limits increased”, and library text can’t be edited. Details are in the template library post.

A custom template gives you three answers instead of one. Meta allows up to 10 quick-reply buttons, with labels of “25 characters maximum” (components, accessed 2026-11-25). Quick replies and other button types must sit in two separate groups.

Set a short time-to-live. Utility templates default to 30 days, and message_send_ttl_seconds accepts 30 to 43,200 seconds (time-to-live, accessed 2026-11-25). A message not delivered within the TTL is dropped. Three hours keeps a “we missed you today” notice from landing tomorrow morning. Reclassification clears the TTL, so check it after any category change.

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

Meta’s TTL page says to set the field on /<PHONE_NUMBER_ID>/message_templates. Templates belong to the WhatsApp Business Account, so the call above uses the WABA ID.

The reply: what each tap sends you

A tap on a template quick reply arrives as type: "button", triggered when “A WhatsApp user taps a quick-reply button in a template message” (button webhook, accessed 2026-11-25). It carries button.payload, button.text and context.id, the template’s wamid. from is omitted when the user has adopted a username, while from_user_id is always present.

You can set the payload per send with a button component of sub_type: "quick_reply". Meta documents that payload as the “Value to be included in messages webhooks (messages.button.payload) when the button is tapped” on its carousel templates page. Put the Onfleet task ID in it. This message is assembled from the reference’s field list:

{
  "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" }
}

The tap opens the 24-hour window, so the follow-ups can be session messages. Reschedule sends reply buttons with two slots, and the choice arrives as interactive.button_reply with your id. Fix my address sends a location_request_message with action.name: "send_location" (location request messages, accessed 2026-11-25). The answer is type: "location" with latitude and longitude, plus context.id.

Meta’s docs index lists a location request template page, but it returned page not found on 2026-11-25. This loop asks for a location only after the tap, inside the window. The request message and its window rules are covered in location and contact messages.

The service: webhook in, template out, task cloned

This Node 18 service receives Onfleet and Meta webhooks, verifies both signatures and sends the template. It clones the task once the customer chooses. State lives in memory to keep it short; use database tables with unique keys in production.

// 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);

Set whatsapp_opt_in as a boolean metadata entry when you create the task from checkout. Onfleet’s metadata format is {name, type, value, visibility} (metadata, accessed 2026-11-25). Onfleet doesn’t say whether an update merges or replaces the array, so addNote reads the task and sends the full array back.

Onfleet allows only notes and metadata changes on active tasks, and only metadata and customFields on completed ones (update task, accessed 2026-11-25). Its page doesn’t cover failed tasks. A failed task looks like a completed one with success: false, so the metadata call should work, but test it. The same goes for cloning a failed task, which the clone task page doesn’t address.

The clone takes overrides such as notes, completeAfter and completeBefore. Both times must be in the future, in milliseconds, and completeBefore must come after completeAfter. The response carries the new id, shortId, trackingURL and sourceTaskId. Fix my address doesn’t clone automatically. It stores the pin on the original task for a dispatcher, because a new destination should be checked by a person.

Failure handling: duplicates, silence, opt-out and retries

Onfleet texts the recipient unless skipSMSNotifications is set, so a customer can get an SMS and a WhatsApp message for the same failed attempt. Set the flag on tasks whose customer opted in to WhatsApp. The service logs a warning when it finds the flag off.

Onfleet retries timed-out requests every 30 seconds, so the service keys on the failed task ID. Meta can deliver the same message more than once, so the service skips any message id it has seen.

If the customer never answers, nothing changes on the task. The template is dropped if it isn’t delivered within three hours. If it’s delivered and ignored, the failed task stays in your dispatcher’s queue under your usual policy. Don’t send a second template for the same task.

Two taps race in real use: a customer taps Reschedule, then Leave with neighbor. The state check lets the first completed action win and ignores the rest. In a database, make that an atomic update on the task row.

A STOP reply goes to an opt-out list that blocks future sends. The service stores from_user_id at the first tap, so STOP and the neighbor’s name still match when from is missing. Onfleet’s SMSRecipientOptOut trigger, 17, covers its SMS channel only. Consent for WhatsApp is separate and should be captured at checkout, as in how to collect WhatsApp opt-in.

“Leave with neighbor” moves responsibility for the parcel. The service writes who approved it, from which number and when, into the new task’s notes. Your terms decide whether that approval is enough.

Graph and Onfleet calls retry on 429 and 5xx with backoff, and stop on other 4xx. The follow-ups cost money too. Since 2026-10-01, Meta charges service messages past 1,000 per number each month, and utility templates inside the window are charged. The details are in Meta’s service message charges.

Where Z-API Omni fits

On Meta’s official API, the template goes out through one route, POST /v1/channels/{channelId}/messages with content.type: "TEMPLATE". Templates are created on the WABA with message_send_ttl_seconds, -1 meaning 30 days. The docs show QUICK_REPLY buttons on templates. They don’t show a per-send button payload or the webhook a tap produces, so the request below sends only the body parameter and the tap needs testing. Free-text replies are documented as MESSAGE_RECEIVED, while location requests are marked “In development”. Webhooks are included without limit and carry x-webhook-delivery-id for deduplication. Pricing is per number, US$29 a month for 1 to 10 numbers, and Meta’s fees are passed through on the official connection.

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

View documentation

Z-API Omni team