An abandoned checkout recovery message is a WhatsApp template that reminds a shopper about a checkout they started and didn’t complete. Meta classes it as marketing, even when the shopper asked for it. Send it through the Marketing Messages API, only to people who opted in to marketing from your store on WhatsApp, and send at most one per checkout.
The loop on this page runs on Shopify. A checkouts/update webhook starts a timer. When the timer fires and no order exists, your service sends one marketing template with a link and a “Not interested” button. The link goes through your own redirect, so you see the click. An orders/create webhook with a matching checkout_token closes the loop and tags the order. The webhook contract and the Admin API token are in Shopify order webhooks to WhatsApp, and this page doesn’t repeat them.
Why a checkout reminder is marketing
Meta’s categorization page uses this exact case as a marketing example. Its sample row opens with “You left {{items}} in your cart” and goes on: “Don’t worry, we saved them. Checkout now below.” It sits under the retargeting objective, which covers messages sent “to users who might have visited your website, used your app or engaged with you.” Meta adds: “These are marketing even if requested by users” (template categorization, accessed 2026-11-27).
The utility test doesn’t rescue it. A checkout that never became an order is not a transaction, and the message’s aim is to get the sale. Labeling it UTILITY at submission does not change that.
So design for marketing from the start. That means marketing consent, the Marketing Messages API, per-user limits, the US exclusion and opt-out handling. Each one is a branch in the code below.
The consent you have to collect yourself
Shopify’s checkout payload carries buyer_accepts_marketing, buyer_accepts_sms_marketing and sms_marketing_phone. None of them is a WhatsApp opt-in. They record consent for email and SMS, so store your own WhatsApp consent instead.
Meta’s opt-in page says “Businesses must clearly state that a person is opting in to receive communication from the business,” and the business name must appear. It recommends “Obtaining separate opt-in by specific message category” (getting opt-in, accessed 2026-11-27). A checkbox reading “Send me reminders and offers from SHOP_NAME on WhatsApp” fits a marketing category. An order-updates checkbox does not.
Store the exact text the person saw, the timestamp, the page and the category. The service below keeps them in memory, keyed by phone and by Shopify customer ID. Collection patterns are in how to collect WhatsApp opt-in.
The checkout event, and the URL Shopify stops sending
Subscribe to checkouts/create and checkouts/update. Shopify’s topic list says each “Occurs whenever a checkout is” created or updated, and both “Requires the read_orders scope” (webhook topics, accessed 2026-11-27). A checkouts/delete delivery sends only id.
The fields you read are token, updated_at, completed_at, line_items, phone, email, customer.id and abandoned_checkout_url. Shopify’s sample has completed_at: null, which is the state you’re waiting on.
Shopify is withholding the recovery URL from many apps, on these dates: “Starting December 1, 2026 for public apps, and January 1, 2027 for custom apps.” From then, abandoned_checkout_url “is left out of the payload for apps without access to all four protected customer fields” (webhook reference, accessed 2026-11-27). The four are name, email, phone and address (protected customer data, accessed 2026-11-27). The GraphQL field AbandonedCheckout.abandonedCheckoutUrl follows the same rule and returns ACCESS_DENIED.
Build a fallback from the line items. Shopify’s cart permalink has the form https://my-shop-name.myshopify.com/cart/36485954240671:1, with pairs of variant ID and quantity separated by commas. It goes to checkout by default, and ?storefront=true lands on the cart page (cart permalinks, accessed 2026-11-27). The permalink rebuilds the cart from the line items. It is not the shopper’s original checkout.
The marketing template and its time-to-live
Write a custom MARKETING template with one URL button and one quick reply. The URL button ends in a {{1}} suffix that holds a random link ID you generate per checkout. It points at your redirect, not at Shopify. That gives you the click, keeps the checkout token out of the message, and lets you choose the destination at tap time. Suffix rules are in template URL buttons with a dynamic suffix.
Don’t copy Meta’s “we saved them” wording unless your store actually reserves stock. Shopify’s docs name no cart-hold feature.
Set a time-to-live at creation. For marketing templates the range is “12 hours to 30 days” and the default is 30 days. TTL applies to “marketing templates sent via Marketing Messages API for WhatsApp” (time-to-live, accessed 2026-11-27). The code below uses 24 hours, so a phone that was off all week never gets a stale reminder. Replace SHOP_NAME and the domain before you run it.
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": "checkout_reminder_v1",
"category": "MARKETING",
"language": "en_US",
"parameter_format": "NAMED",
"message_send_ttl_seconds": 86400,
"components": [
{
"type": "BODY",
"text": "You started a checkout at SHOP_NAME with {{cart_summary}}. Tap below to return to it.",
"example": { "body_text_named_params": [ { "param_name": "cart_summary", "example": "3 items" } ] }
},
{
"type": "BUTTONS",
"buttons": [
{ "type": "URL", "text": "Return to checkout", "url": "https://shop.example.com/r/{{1}}", "example": ["https://shop.example.com/r/k3J9xQ2mP0aZ"] },
{ "type": "QUICK_REPLY", "text": "Not interested" }
]
}
]
}'
Send through /marketing_messages
Send marketing templates to POST /<PHONE_NUMBER_ID>/marketing_messages. The body is the same as /messages, and the response carries messages[].id (send marketing messages, accessed 2026-11-27). The endpoint is send-only. Replies and statuses still arrive on your Cloud API webhook.
The dates make this the only path worth building. “Cloud API will stop supporting marketing messages on October 13, 2027.” From April 13, 2027, “Any new Messaging account created on or after this date will not be able to send marketing messages via Cloud API” (MM API overview, accessed 2026-11-27). The timeline is in the 2027 Cloud API marketing sunset.
The endpoint accepts an optional product_policy. Its default, CLOUD_API_FALLBACK, lets the send fall back to Cloud API, and STRICT means no fallback. Onboarding and the fallback are covered in the Marketing Messages API guide. The service below leaves the field out, so it gets the default.
Who you must not send to
Run the checks in this table before every send. Skip one and the message fails later on a status webhook, or it reaches someone who said no.
| Check | Meta’s rule | What the service does |
|---|---|---|
| Per-user limit | “WhatsApp may limit the number of marketing template messages a WhatsApp user receives.” A blocked send fails with 131049 | After 131049, no marketing to that user for 24 hours |
| US numbers | “WhatsApp does not currently deliver marketing template messages to WhatsApp users with United States phone numbers” | Skips numbers that start with a configurable prefix |
| Opt-out | 131050: “This recipient has chosen to stop receiving marketing messages on WhatsApp from your business” | Stops marketing until a resume arrives |
| Your own button | “Not interested” is your opt-out, not Meta’s | Stops checkout reminders to that user |
Sources: per-user limits and error codes, both accessed 2026-11-27.
Meta’s limits page says to “wait at least 24 hours before attempting to resend a marketing template message.” This service never resends a checkout reminder, because a day-old reminder for the same cart is noise. It only uses the 131049 to hold back the next checkout’s reminder.
Meta’s changelog says “Starting March 2027, 131066 will be returned instead of 131049” (MM API changelog, accessed 2026-11-27). The error reference gives 131066 as “Message was not delivered to this user.” Handle both codes the same way now, and the switch costs you nothing. The change is covered in WhatsApp error 131066.
The US prefix is blunt. Numbers starting with 1 include Canada and other countries that share the code. Meta’s page doesn’t say how it decides a number is from the United States. If you sell to Canada, replace the prefix check with an area-code list.
Opt-outs arrive two ways. A user_preferences webhook carries value: "stop" or "resume" with the user’s wa_id. A later send to that user fails with 131050 on the status webhook. Record both, and let only a newer resume clear a stop. The full pattern is in WhatsApp marketing opt-outs.
The reply and the click
A “Not interested” tap arrives as a messages webhook with type: "button". Meta’s sample has "button": {"payload": "Unsubscribe", "text": "Unsubscribe"} and a context.id holding the template’s message ID (button webhook, accessed 2026-11-27). The service sets the payload to not_interested:<link_id> at send time and falls back to the button text if the payload doesn’t parse.
The tap opens a customer service window, so the confirmation reply goes out as plain text through /messages. A typed “stop” gets the same treatment.
A tap on the URL button reaches your /r/<link_id> route. The service records the time and redirects to abandoned_checkout_url when Shopify sent one, or to the permalink otherwise. Count a click as interest and an order as the sale.
The sale arrives as orders/create. Its payload has checkout_token, which matches the checkout’s token. The service tags the order whatsapp-recovered with tagsAdd, plus whatsapp-clicked when the redirect saw a tap. A match proves the order came from a checkout you messaged. It doesn’t prove the message caused it, so report the two tags apart. Avoid orderUpdate here, because its tags input overwrites existing tags.
The complete service
This Node 18+ file runs with npm install express. It verifies Shopify’s X-Shopify-Hmac-Sha256 and Meta’s X-Hub-Signature-256, dedupes on X-Shopify-Webhook-Id and on Meta’s message IDs, and writes back through the Admin GraphQL API, version 2026-10. State lives in memory for the example, so swap the maps for tables. Protect /optin with your own authentication before it goes live.
// checkout-recovery.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,
DELAY_MINUTES = "60", SKIP_PREFIXES = "1", DEFAULT_COUNTRY_CODE = "", PORT = "3000",
} = process.env;
const STORE_URL = process.env.STORE_URL || `https://${SHOP}.myshopify.com`;
const ADMIN_URL = `https://${SHOP}.myshopify.com/admin/api/2026-10/graphql.json`;
const GRAPH = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}`;
const DAY_MS = 24 * 60 * 60 * 1000;
const seen = new Set(); // X-Shopify-Webhook-Id and Meta message ids
const consents = new Map(); // phone -> { text, at, sourceUrl, category }
const phoneByCustomer = new Map(); // Shopify customer id -> phone
const users = new Map(); // phone -> { stopped, prefTs, limitedUntil, recoveryOff }
const checkouts = new Map(); // checkout token -> record
const byWamid = new Map(); // template wamid -> checkout token
const byLink = new Map(); // link id -> checkout token
const orderByCheckout = new Map(); // checkout token -> order gid
const user = (phone) => {
if (!users.has(phone)) users.set(phone, { stopped: false, prefTs: 0, limitedUntil: 0, recoveryOff: false });
return users.get(phone);
};
const handOff = (reason, detail) => console.log("needs_person", { reason, detail });
const safeEqual = (a, b) => {
const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? "");
return x.length === y.length && crypto.timingSafeEqual(x, y);
};
function normalizePhone(raw) {
if (!raw || /[a-z]/i.test(raw)) return null;
const digits = String(raw).replace(/\D/g, "");
if (String(raw).trim().startsWith("+")) return digits.length >= 8 ? digits : null;
return DEFAULT_COUNTRY_CODE && digits.length >= 6 ? DEFAULT_COUNTRY_CODE + digits.replace(/^0+/, "") : null;
}
// Shopify Admin API: client credentials token, cached until shortly before expiry.
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 TAGS_ADD = `mutation tagsAdd($id: ID!, $tags: [String!]!) {
tagsAdd(id: $id, tags: $tags) { node { id } userErrors { field message } } }`;
async function addTags(gid, tags) {
const data = await admin(TAGS_ADD, { id: gid, tags });
if (data.tagsAdd.userErrors.length) throw new Error(JSON.stringify(data.tagsAdd.userErrors));
}
async function graph(path, body) {
const res = await fetch(`${GRAPH}/${path}`, {
method: "POST",
headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", ...body }),
});
const json = await res.json();
if (!res.ok) throw new Error(`Graph ${res.status}: ${JSON.stringify(json.error ?? json)}`);
return json.messages[0].id;
}
const sendText = (to, text) => graph("messages", { to, type: "text", text: { body: text } });
// ---- Shopify events ----
function onCheckout(c) {
if (!c.token) return;
const prev = checkouts.get(c.token);
const updatedAt = Date.parse(c.updated_at ?? "") || Date.now();
if (prev && updatedAt < prev.updatedAt) return; // older delivery, ignore
if (prev && prev.state !== "waiting") return; // already sent or skipped: one message per checkout
const items = (c.line_items ?? [])
.filter((li) => li.variant_id)
.map((li) => ({ variantId: String(li.variant_id), quantity: Number(li.quantity ?? 1) }));
const rec = prev ?? { token: c.token, linkId: crypto.randomBytes(9).toString("base64url"), state: "waiting" };
Object.assign(rec, {
id: String(c.id ?? rec.id ?? ""),
updatedAt,
dueAt: updatedAt + Number(DELAY_MINUTES) * 60 * 1000,
phone: normalizePhone(c.phone ?? c.sms_marketing_phone) ?? rec.phone ?? null,
customerId: c.customer?.id ? String(c.customer.id) : rec.customerId ?? null,
items,
recoveryUrl: c.abandoned_checkout_url ?? null, // absent without all four protected fields
completed: Boolean(c.completed_at),
});
checkouts.set(rec.token, rec);
byLink.set(rec.linkId, rec.token);
}
function onCheckoutDeleted(c) {
for (const rec of checkouts.values()) {
if (rec.id === String(c.id) && rec.state === "waiting") rec.state = "deleted";
}
}
async function onOrderCreated(order) {
const ct = order.checkout_token;
if (!ct) return;
orderByCheckout.set(ct, order.admin_graphql_api_id);
const rec = checkouts.get(ct);
if (!rec) return;
if (rec.state === "waiting") return void (rec.state = "ordered_before_send");
if (rec.state !== "sent") return;
rec.state = "recovered";
const tags = rec.clickedAt ? ["whatsapp-recovered", "whatsapp-clicked"] : ["whatsapp-recovered"];
await addTags(order.admin_graphql_api_id, tags);
}
// ---- The send ----
function skipReason(rec) {
if (rec.completed || orderByCheckout.has(rec.token)) return "ordered";
const phone = rec.phone ?? phoneByCustomer.get(rec.customerId);
if (!phone) return "no_phone";
const consent = consents.get(phone);
if (!consent || consent.category !== "cart_reminders") return "no_whatsapp_marketing_opt_in";
if (SKIP_PREFIXES.split(",").filter(Boolean).some((p) => phone.startsWith(p))) return "us_prefix";
const u = user(phone);
if (u.stopped) return "marketing_stopped";
if (u.recoveryOff) return "not_interested";
if (u.limitedUntil > Date.now()) return "per_user_limit";
if (!rec.items.length && !rec.recoveryUrl) return "no_link";
rec.to = phone;
return null;
}
async function sendReminder(rec) {
rec.state = "sending"; // the next sweep skips it
const reason = skipReason(rec);
if (reason) return void Object.assign(rec, { state: "skipped", skipReason: reason });
const count = rec.items.reduce((n, i) => n + i.quantity, 0) || 1;
try {
const wamid = await graph("marketing_messages", {
to: rec.to,
type: "template",
template: {
name: "checkout_reminder_v1",
language: { code: "en_US" },
components: [
{ type: "body", parameters: [{ type: "text", parameter_name: "cart_summary", text: `${count} item${count === 1 ? "" : "s"}` }] },
{ type: "button", sub_type: "url", index: 0, parameters: [{ type: "text", text: rec.linkId }] },
{ type: "button", sub_type: "quick_reply", index: 1, parameters: [{ type: "payload", payload: `not_interested:${rec.linkId}` }] },
],
},
});
Object.assign(rec, { state: "sent", wamid, sentAt: Date.now() });
byWamid.set(wamid, rec.token);
} catch (err) {
rec.state = "send_error"; // no retry: a duplicate is worse than a miss
handOff("send_failed", { token: rec.token, error: err.message });
}
}
setInterval(() => {
const now = Date.now();
for (const rec of checkouts.values()) {
if (rec.state === "waiting" && rec.dueAt <= now) sendReminder(rec);
}
}, 60 * 1000);
// ---- Meta events ----
function onStatus(s) {
const rec = checkouts.get(byWamid.get(s.id));
if (s.status !== "failed") return;
const codes = (s.errors ?? []).map((e) => Number(e.code));
const phone = rec?.to ?? s.recipient_id;
if (!phone) return handOff("failed_status_without_recipient", s.id);
const u = user(phone);
if (codes.includes(131050)) u.stopped = true;
if (codes.includes(131049) || codes.includes(131066)) u.limitedUntil = Date.now() + DAY_MS;
if (rec) Object.assign(rec, { state: "failed", errorCodes: codes });
}
function onPreference(p) {
if (p.category !== "marketing_messages" || !p.wa_id) return;
const u = user(p.wa_id);
if (Number(p.timestamp) < u.prefTs) return; // an older event never overrides a newer one
u.prefTs = Number(p.timestamp);
u.stopped = p.value === "stop";
}
async function onMessage(msg) {
if (seen.has(msg.id)) return;
seen.add(msg.id);
const rec = checkouts.get(byWamid.get(msg.context?.id));
const typed = msg.type === "text" ? String(msg.text?.body ?? "").trim().toLowerCase() : "";
const tapped = msg.type === "button" &&
(String(msg.button?.payload ?? "").startsWith("not_interested:") || msg.button?.text === "Not interested");
if (!tapped && typed !== "stop") return handOff("inbound_message", { from: msg.from, type: msg.type });
const phone = rec?.to ?? msg.from;
if (!phone) return handOff("opt_out_without_phone", { id: msg.id });
user(phone).recoveryOff = true;
if (rec) rec.state = "declined";
await sendText(phone, "Done. You won't get checkout reminders from us on WhatsApp again.");
}
// ---- HTTP ----
const app = express();
app.post("/optin", express.json(), (req, res) => {
const { phone, customer_id, consent_text, source_url } = req.body ?? {};
const p = normalizePhone(phone);
if (!p || !consent_text) return res.status(400).json({ error: "phone and consent_text are required" });
consents.set(p, { text: consent_text, at: new Date().toISOString(), sourceUrl: source_url ?? null, category: "cart_reminders" });
if (customer_id) phoneByCustomer.set(String(customer_id), p);
user(p).recoveryOff = false;
res.sendStatus(204);
});
app.get("/r/:linkId", (req, res) => {
const rec = checkouts.get(byLink.get(req.params.linkId));
if (!rec) return res.redirect(302, STORE_URL);
rec.clickedAt ??= Date.now();
if (rec.recoveryUrl) return res.redirect(302, rec.recoveryUrl);
const pairs = rec.items.map((i) => `${i.variantId}:${i.quantity}`).join(",");
res.redirect(302, pairs ? `${STORE_URL}/cart/${pairs}` : STORE_URL);
});
app.post("/shopify/webhooks", express.raw({ type: "*/*" }), (req, res) => {
const digest = crypto.createHmac("sha256", SHOPIFY_CLIENT_SECRET).update(req.body).digest("base64");
if (!safeEqual(digest, req.get("x-shopify-hmac-sha256"))) return res.sendStatus(401);
res.sendStatus(200); // inside Shopify's five seconds
const deliveryId = req.get("x-shopify-webhook-id");
if (seen.has(deliveryId)) return;
seen.add(deliveryId);
const topic = req.get("x-shopify-topic");
const payload = JSON.parse(req.body.toString("utf8"));
Promise.resolve()
.then(() => {
if (topic === "checkouts/create" || topic === "checkouts/update") return onCheckout(payload);
if (topic === "checkouts/delete") return onCheckoutDeleted(payload);
if (topic === "orders/create") return onOrderCreated(payload);
})
.catch((err) => handOff(`${topic}_failed`, err.message));
});
app.get("/whatsapp/webhook", (req, res) => {
const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
return ok ? res.send(req.query["hub.challenge"]) : res.sendStatus(403);
});
app.post("/whatsapp/webhook", express.raw({ type: "application/json" }), (req, res) => {
const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
if (!safeEqual(expected, req.get("x-hub-signature-256"))) return res.sendStatus(401);
res.sendStatus(200);
const body = JSON.parse(req.body.toString("utf8"));
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
const value = change.value ?? {};
if (change.field === "user_preferences") (value.user_preferences ?? []).forEach(onPreference);
if (change.field !== "messages") continue;
(value.statuses ?? []).forEach(onStatus);
for (const msg of value.messages ?? []) onMessage(msg).catch((err) => handOff("reply_failed", err.message));
}
}
});
app.listen(Number(PORT), () => console.log(`listening on ${PORT}`));
Subscribe the Meta app to the messages and user_preferences fields, or the opt-out branch never runs. The checkout’s line_items[].variant_id and quantity feed the permalink.
When something fails
If the send throws, the record moves to send_error and a person sees it. The service doesn’t retry, because a network error can hide a message Meta already accepted.
If your endpoint goes down, Shopify “retries 8 times over the next 4 hours”, and the X-Shopify-Webhook-Id check absorbs the repeats. After 8 consecutive failures, a subscription created through the Admin API is deleted (HTTPS webhooks, accessed 2026-11-27). Watch for that, or the reminders stop without an error.
A checkout that keeps changing pushes its own timer forward, because each checkouts/update resets dueAt. Once the reminder goes out, later updates change nothing.
Meta can accept a request and still fail the delivery. A failed status can arrive minutes later with 131049, 131050 or, from March 2027, 131066. If no delivered status arrives before the 24-hour TTL ends, Meta’s TTL page says to assume the message was dropped. It names no error code for that case.
A shopper who asked to hear about a sold-out product is a different loop, covered in WhatsApp back-in-stock alerts.
Where Z-API Omni fits
Omni documents no Shopify integration and no scheduler, so the timer and the webhooks above stay in your service. Its custom-model page has a MARKETING “Cart recovery” example with a URL button and a “Not interested” quick reply. Its body says items are “still reserved for 24 hours”, so edit that line unless your store reserves stock. The docs don’t say whether marketing templates go through /marketing_messages, and they don’t show Meta error codes or user_preferences reaching your webhook. Test those before you depend on them.
{
"name": "abandoned_cart",
"category": "MARKETING",
"language": "en_US",
"allow_category_change": true,
"parameter_format": "NAMED",
"components": [
{
"type": "BODY",
"text": "{{customer_name}}, you left {{item_count}} items in your cart. They are still reserved for 24 hours.",
"example": {
"body_text_named_params": [
{ "param_name": "customer_name", "example": "Marina" },
{ "param_name": "item_count", "example": "3" }
]
}
},
{
"type": "BUTTONS",
"buttons": [
{ "type": "URL", "text": "Complete purchase", "url": "https://yourstore.com/cart" },
{ "type": "QUICK_REPLY", "text": "Not interested" }
]
}
]
}
You send it with POST https://api.omni.z-api.io/v1/channels/{channelId}/messages and content.type: TEMPLATE. One subscription covers WhatsApp, Messenger, Instagram and Telegram, at US$29 per number per month for 1 to 10 numbers, down to US$20 above 100. Webhooks are included without limit. On Meta’s official API, Meta’s fees pass through. The QR connection has no per-message cost, and the opt-in rule still applies there.
Z-API Omni team