WhatsApp· 8 min read

WhatsApp back-in-stock alerts for customers who asked


A back-in-stock alert is a WhatsApp message telling a customer that a product they asked about can be bought again. Meta’s categorization page never mentions restock alerts, and its closest examples are marketing. So design the alert as a marketing template. Send it only to people who opted in to this category, once per request, when your stock goes from zero to more than zero.

A “Notify me” form records the request with its consent text. Shopify’s inventory_levels/update webhook tells you stock changed. Your service sends one marketing template with a cart link and a “Stop alerts” button. The tap or the link comes back to you. An orders/create webhook with that variant marks the request converted.

What Meta’s categorization page says, and what it leaves out

None of these words appear on Meta’s template categorization page (accessed 2026-11-27): “stock”, “restock”, “back in stock”, “inventory”, “availability” or “waitlist”. No Meta page cited here classifies this alert directly.

The nearest rules all point to marketing. The retargeting objective covers messages that “Promote or recommend offers, products, or services”, and Meta adds “These are marketing even if requested by users.” Its example row is a user-requested availability alert: “We found a {{car}} that meets your saved search. Log in to our app to view.” Meta files that row as marketing.

The utility test asks for more than a request. A utility template “Must be non-promotional, not containing any promotional or persuasive intent.” It must also be “specific to or requested by the user”, “clearly related to their order, account, services, or transactions.” A restock alert is requested, but its aim is a new sale.

Meta’s one stock case filed as utility involves an order already placed: “Unfortunately, one item from your order {{number}} is backordered.” It continues “We will follow up with an estimated ship date” and offers a refund. Stock news about an existing order is utility. Stock news that invites a new purchase is marketing.

The Template Library offers no way around this. Library templates have “already been categorized as utility or authentication”, and none covers restocks (Template Library, accessed 2026-11-27).

Meta recommends “Obtaining separate opt-in by specific message category” (getting opt-in, accessed 2026-11-27). A “Notify me” form is the natural place for that, because the person states exactly what they want. Name your store and the channel in the label: “Message me on WhatsApp from SHOP_NAME when this item is back in stock.”

Store one row per request with the variant ID, the phone in international format, the exact consent text, the timestamp, the page URL and a status. Shopify has no native back-in-stock subscriber list, so this table is yours. More collection patterns are in how to collect WhatsApp opt-in.

That consent covers an alert about this product. It doesn’t cover your newsletter, and it ends when the alert is sent.

The inventory event is per location

Subscribe to inventory_levels/update. Shopify’s topic list says it “Occurs whenever an inventory level is updated. Requires the read_inventory scope” (webhook topics, accessed 2026-11-27). Shopify’s reference sample looks like this:

{
  "inventory_item_id": 271878346596884015,
  "location_id": 24826418,
  "available": 10,
  "updated_at": "2021-12-31T19:00:00-05:00",
  "admin_graphql_api_id": "gid://shopify/InventoryLevel/24826418?inventory_item_id=271878346596884015"
}

available is the count at one location, not across the store. A restock at one warehouse and a sale at another arrive as two deliveries. If you alert on every update with available > 0, a customer gets a message each time any location changes.

Keep your own state instead. Store the last available per location, sum it per inventory item, and act only on the edge from a total of zero to a total above zero. Ignore a delivery whose updated_at is older than the one you stored for that location, because deliveries can arrive out of order.

Seed that state when you deploy. The service below starts empty and treats an unknown total as zero, which is correct for an item someone is waiting on.

Map the inventory item to a variant

The webhook names an inventory item, and your requests name a variant. Shopify marks InventoryItem.variant as deprecated without naming a replacement. Use the variants connection, a ProductVariantConnection, with read_inventory or read_products (InventoryItem, accessed 2026-11-27). The service caches the answer per item.

Write a custom MARKETING template. The body names the product and reminds the customer they asked. A URL button opens the cart, and a quick reply lets them stop. Replace SHOP_NAME and the domain before you run this.

The 12-hour TTL is the marketing minimum on Meta’s time-to-live page (accessed 2026-11-27), and it applies to sends through the Marketing Messages API. It suits an alert, because a restock can sell out again within a day.

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": "restock_alert_v1",
  "category": "MARKETING",
  "language": "en_US",
  "parameter_format": "NAMED",
  "message_send_ttl_seconds": 43200,
  "components": [
    {
      "type": "BODY",
      "text": "The item you asked about, {{product_name}}, is back in stock at SHOP_NAME. Tap below to open it in your cart.",
      "example": { "body_text_named_params": [ { "param_name": "product_name", "example": "Trail jacket - Blue / M" } ] }
    },
    {
      "type": "BUTTONS",
      "buttons": [
        { "type": "URL", "text": "Open cart", "url": "https://shop.example.com/r/{{1}}", "example": ["https://shop.example.com/r/q8Rk2LmZ0pXa"] },
        { "type": "QUICK_REPLY", "text": "Stop alerts" }
      ]
    }
  ]
}'

The URL button carries the request ID and points at your redirect. The redirect records the click and sends the customer to Shopify’s cart permalink, https://{shop}/cart/{variant_id}:1?storefront=true. Without ?storefront=true, the permalink goes straight to checkout (cart permalinks, accessed 2026-11-27).

Don’t promise to hold the item. Shopify documents no reservation or cart-hold API, and a permalink reserves nothing. If you want a soft hold, it has to live in your own stock logic.

Send it as marketing, with every marketing rule

Send to POST /<PHONE_NUMBER_ID>/marketing_messages. It takes the same body as /messages and returns messages[].id. Cloud API stops supporting marketing messages on October 13, 2027, and accounts created from April 13, 2027 can’t send marketing there at all (MM API overview, accessed 2026-11-27). The endpoint and its options are in the Marketing Messages API guide.

The rules from abandoned checkout recovery apply here unchanged. A per-user marketing limit fails the send with 131049, and Meta says to “wait at least 24 hours before attempting to resend.” The same page says “WhatsApp does not currently deliver marketing template messages to WhatsApp users with United States phone numbers” (per-user limits, accessed 2026-11-27).

“Starting March 2027, 131066 will be returned instead of 131049,” per Meta’s MM API changelog (accessed 2026-11-27). A user who stopped marketing makes your send fail with 131050, and a user_preferences webhook carries the stop or resume.

A restock alert is one of the few marketing sends where a single retry makes sense. The customer still wants the item. The service retries once, 24 hours after a 131049 or 131066, and only if the item is still in stock. Opt-out storage is in WhatsApp marketing opt-outs.

Who gets the alert, and in what order

On a restock edge, the service sends to waiting requests for that variant in the order they arrived. Each request is one-shot: after the send it moves to notified and never sends again.

If ten people wait for two units, all ten get the alert. Some stores prefer to cap each edge at a multiple of the units available and leave the rest waiting. That is a business choice, and Meta’s pages say nothing about it. A capped design needs another trigger for the people left waiting, because stock that stays above zero produces no new edge.

The reply, the click and the order

A “Stop alerts” tap arrives as a messages webhook with type: "button", a button.payload and a context.id equal to the template’s message ID (button webhook, accessed 2026-11-27). The service sets the payload to stop_alerts:<request_id> and also accepts the button text. It removes every open request from that phone and replies in the window the tap opened. A typed “stop” does the same.

A tap on the URL button hits /r/<request_id>, which records clickedAt and redirects. An orders/create with that variant and the same phone marks the request converted and tags the order whatsapp-restock-alert. Order phones can be empty or formatted differently, so expect to miss some matches. Shopify’s phone fields are covered in Shopify order webhooks to WhatsApp.

The complete service

This Node 18+ file runs with npm install express. It verifies Shopify’s HMAC and Meta’s X-Hub-Signature-256, dedupes on X-Shopify-Webhook-Id and Meta’s message IDs, and uses the Admin GraphQL API, version 2026-10. State lives in memory for the example. Put /notify-me behind your storefront’s own protection, such as a captcha, before it goes live.

// back-in-stock.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,
  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 requests = new Map();      // request id -> row
const users = new Map();         // phone -> { stopped, prefTs }
const levels = new Map();        // inventory item id -> Map(location id -> { available, at })
const variantCache = new Map();  // inventory item id -> [{ id, name }]
const byWamid = new Map();       // template wamid -> request id

const user = (phone) => {
  if (!users.has(phone)) users.set(phone, { stopped: false, prefTs: 0 });
  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;
}

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 VARIANTS = `query variants($id: ID!) {
  inventoryItem(id: $id) { variants(first: 10) { nodes { legacyResourceId displayName } } } }`;
const TAGS_ADD = `mutation tagsAdd($id: ID!, $tags: [String!]!) {
  tagsAdd(id: $id, tags: $tags) { node { id } userErrors { field message } } }`;

async function variantsFor(itemId) {
  if (variantCache.has(itemId)) return variantCache.get(itemId);
  const data = await admin(VARIANTS, { id: `gid://shopify/InventoryItem/${itemId}` });
  const list = (data.inventoryItem?.variants?.nodes ?? []).map((v) => ({ id: String(v.legacyResourceId), name: v.displayName }));
  variantCache.set(itemId, list);
  return list;
}

const totalFor = (itemId) => [...(levels.get(itemId)?.values() ?? [])].reduce((n, l) => n + Math.max(0, l.available), 0);

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

// ---- Inventory edge ----
async function onInventoryLevel(p) {
  const itemId = String(p.inventory_item_id), locId = String(p.location_id);
  const at = Date.parse(p.updated_at ?? "") || Date.now();
  const locs = levels.get(itemId) ?? new Map();
  const prev = locs.get(locId);
  if (prev && at < prev.at) return;                       // older delivery for this location
  const before = totalFor(itemId);
  locs.set(locId, { available: Number(p.available ?? 0), at });
  levels.set(itemId, locs);
  const after = totalFor(itemId);
  if (!(before <= 0 && after > 0)) return;                // act only on the zero-to-positive edge

  for (const variant of await variantsFor(itemId)) {
    const waiting = [...requests.values()]
      .filter((r) => r.variantId === variant.id && r.status === "waiting")
      .sort((a, b) => a.createdAt - b.createdAt);         // first come, first served
    for (const row of waiting) await sendAlert(row, variant.name, itemId);
  }
}

async function sendAlert(row, productName, itemId) {
  row.status = "sending";
  Object.assign(row, { productName, itemId });
  if (SKIP_PREFIXES.split(",").filter(Boolean).some((p) => row.phone.startsWith(p))) {
    return void (row.status = "skipped_us_prefix");
  }
  if (user(row.phone).stopped) return void (row.status = "removed");
  try {
    const wamid = await graph("marketing_messages", {
      to: row.phone,
      type: "template",
      template: {
        name: "restock_alert_v1",
        language: { code: "en_US" },
        components: [
          { type: "body", parameters: [{ type: "text", parameter_name: "product_name", text: productName }] },
          { type: "button", sub_type: "url", index: 0, parameters: [{ type: "text", text: row.id }] },
          { type: "button", sub_type: "quick_reply", index: 1, parameters: [{ type: "payload", payload: `stop_alerts:${row.id}` }] },
        ],
      },
    });
    Object.assign(row, { status: "notified", wamid, sentAt: Date.now(), attempts: row.attempts + 1 });
    byWamid.set(wamid, row.id);
  } catch (err) {
    row.status = "send_error";                            // a person decides; no blind resend
    handOff("send_failed", { request: row.id, error: err.message });
  }
}

// One retry, 24 hours after a per-user limit, only while the item is still in stock.
setInterval(() => {
  for (const row of requests.values()) {
    if (row.status !== "limited" || row.retryAt > Date.now()) continue;
    if (row.attempts >= 2) { row.status = "gave_up"; continue; }
    if (totalFor(row.itemId) > 0) sendAlert(row, row.productName, row.itemId);
    else row.status = "waiting";                          // sold out again: wait for the next edge
  }
}, 60 * 1000);

// ---- Meta events ----
function onStatus(s) {
  const row = requests.get(byWamid.get(s.id));
  if (!row || s.status !== "failed") return;
  const codes = (s.errors ?? []).map((e) => Number(e.code));
  if (codes.includes(131050)) {
    user(row.phone).stopped = true;
    row.status = "removed";
  } else if (codes.includes(131049) || codes.includes(131066)) {
    Object.assign(row, { status: "limited", retryAt: Date.now() + DAY_MS });
  } else {
    row.status = "failed";
    handOff("alert_failed", { request: row.id, 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;
  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 row = requests.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("stop_alerts:") || msg.button?.text === "Stop alerts");
  if (!tapped && typed !== "stop") return handOff("inbound_message", { from: msg.from, type: msg.type });

  const phone = row?.phone ?? msg.from;
  if (!phone) return handOff("stop_without_phone", { id: msg.id });
  for (const r of requests.values()) {
    if (r.phone === phone && ["waiting", "limited", "notified"].includes(r.status)) r.status = "removed";
  }
  await sendText(phone, "Done. We removed your stock alerts and won't message you about them again.");
}

// ---- Orders: conversion ----
async function onOrderCreated(order) {
  const phone = normalizePhone(order.phone ?? order.customer?.phone ?? order.shipping_address?.phone);
  if (!phone) return;
  const variantIds = new Set((order.line_items ?? []).map((li) => String(li.variant_id)));
  const hits = [...requests.values()].filter((r) => r.phone === phone && r.status === "notified" && variantIds.has(r.variantId));
  if (!hits.length) return;
  hits.forEach((r) => (r.status = "converted"));
  const data = await admin(TAGS_ADD, { id: order.admin_graphql_api_id, tags: ["whatsapp-restock-alert"] });
  if (data.tagsAdd.userErrors.length) handOff("tag_failed", data.tagsAdd.userErrors);
}

// ---- HTTP ----
const app = express();

app.post("/notify-me", express.json(), (req, res) => {
  const { variant_id, phone, consent_text, page_url } = req.body ?? {};
  const p = normalizePhone(phone);
  if (!variant_id || !p || !consent_text) return res.status(400).json({ error: "variant_id, phone and consent_text are required" });
  const open = [...requests.values()].find((r) => r.phone === p && r.variantId === String(variant_id) && r.status === "waiting");
  if (open) return res.json({ id: open.id });             // a second tap on "Notify me" changes nothing
  const row = {
    id: crypto.randomBytes(9).toString("base64url"), variantId: String(variant_id), phone: p,
    consentText: consent_text, consentAt: new Date().toISOString(), pageUrl: page_url ?? null,
    status: "waiting", createdAt: Date.now(), attempts: 0,
  };
  requests.set(row.id, row);
  res.status(201).json({ id: row.id });
});

app.get("/r/:id", (req, res) => {
  const row = requests.get(req.params.id);
  if (!row) return res.redirect(302, STORE_URL);
  row.clickedAt ??= Date.now();
  res.redirect(302, `${STORE_URL}/cart/${row.variantId}:1?storefront=true`);
});

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);
  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"));
  const job = topic === "inventory_levels/update" ? onInventoryLevel(payload)
    : topic === "orders/create" ? onOrderCreated(payload) : Promise.resolve();
  job.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}`));

Two concurrent deliveries for the same item can both see a zero total in a multi-process deployment. Run the edge check under a row lock or a single worker per inventory item. In the single process above, the sending status stops a second send to the same row.

When something fails

If your endpoint is down, Shopify retries 8 times over 4 hours. A subscription created through the Admin API is deleted after 8 consecutive failures (HTTPS webhooks, accessed 2026-11-27). A lost restock event means waiting customers hear nothing. Run a periodic job that checks stock for every variant with waiting requests. It also recovers an edge lost when the Admin API call in variantsFor fails.

If the send throws, the row moves to send_error and a person decides. The service doesn’t resend on its own, because the request may have reached Meta.

A failed status with a code other than 131049, 131050 or 131066 goes to a person with the codes attached. If no delivered status arrives within the 12-hour TTL, treat the message as dropped. Meta names no error code for that case.

If the product page and the WhatsApp number belong to different stores in your system, the consent text must name the store that sends. One store’s consent doesn’t cover another’s alert.

The same alert on Telegram

Telegram has no template categories. A bot can message a customer who started it and agreed to the alert, at any time. Use a deep link on the “Notify me” form so the start token carries the request ID. That pattern is in Telegram bot deep linking.

Don’t build this on WhatsApp product messages unless you already run a Meta catalog, because they need one. The details are in WhatsApp product messages.

Where Z-API Omni fits

Omni documents no Shopify integration and no scheduler, so the inventory state, the edge and the retry stay in your service. For the template, adapt its MARKETING “Cart recovery” example, which has a URL button and a quick reply, and send it with content.type: TEMPLATE. Its docs don’t say whether marketing templates go through /marketing_messages, or show 131049, 131050, user_preferences or a button tap reaching your webhook.

The QR connection has no templates. There, an INTERACTIVE_BUTTON message carries up to three buttons, and consent still applies.

{
  "recipient": { "identifier": "5511999999999" },
  "content": {
    "type": "INTERACTIVE_BUTTON",
    "body": { "message": "The item you asked about is back in stock. Reply below." },
    "attachments": [
      { "id": "open_cart", "title": "Send me the link" },
      { "id": "stop_alerts", "title": "Stop alerts" }
    ]
  }
}

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. The QR connection has no per-message cost, and Meta’s fees pass through on Meta’s official API.

View documentation

Z-API Omni team