DEV Community

Cover image for Click-to-WhatsApp Ads in Code: Referral Payloads, the Free Entry Point Window and Conversion Events
WAPGROWAI for WAPGROWAI

Posted on

Click-to-WhatsApp Ads in Code: Referral Payloads, the Free Entry Point Window and Conversion Events

A Click-to-WhatsApp ad ends where most ads end: a person taps a button. What happens next is your code's job. The first message arrives with a referral object that says which ad it came from, and that object is the only time you'll be told. If you answer inside 24 hours, Meta opens a window in which your messages to that person are free. And if the lead later buys, Meta can only learn that from you, through the Conversions API, using a click ID you had to save on that first message.

Most integrations drop all three. The ad context is never stored, nobody knows which leads are about to lose the free window, and the ad optimises for chats instead of sales. This post builds the missing pieces in TypeScript: capturing the referral, finding the leads that need an answer now, reading free messages from status webhooks, and sending conversion events back.

The code was run with node --experimental-strip-types and 12 tests. Meta facts are from its developer docs as of November 2026.

What arrives with an ad click

When someone messages you from a Click-to-WhatsApp ad, the inbound message carries a referral object. Per Meta's messages webhook reference:

{
  "from": "919820011223",
  "id": "wamid.HBgM...",
  "timestamp": "1764493200",
  "type": "text",
  "text": { "body": "Hello! Can I get more info on this?" },
  "referral": {
    "source_url": "https://fb.me/3cr4Wqqkv",
    "source_id": "120208000000000",
    "source_type": "ad",
    "headline": "Free demo class",
    "body": "Book a free demo class this week",
    "media_type": "image",
    "image_url": "https://...",
    "ctwa_clid": "ARAkLkA8rmlFeiCktEJQ",
    "welcome_message": { "text": "Hi! Which course are you interested in?" }
  }
}
Enter fullscreen mode Exit fullscreen mode

The fields that matter most:

  • source_id is the ad ID: the key for any "which ad brought this lead" report.
  • headline and body are the ad's copy. Show them to whoever answers the chat, so they know what the customer saw.
  • ctwa_clid is the click ID, "a personal identifier, unique per click". You need it later to tell Meta about conversions. It's missing for one case: since October 2025, ads shown in WhatsApp Status don't include it.

Meta doesn't document whether referral repeats on later messages. Its Conversions API guide simply says "Upon receiving the ctwa_clid, store it with the conversation." Treat the first message as your only chance.

Two more details: from is omitted when the customer has adopted a WhatsApp username, so key leads by from_user_id when it's there; and the default prefilled message ("Hello! Can I get more info on this?") is what most ad leads send first, so a keyword bot that waits for "price" or "course" won't see one.

Capturing the lead

// The `referral` object on an inbound message that came from an ad.
export type Referral = {
  source_url?: string;
  source_id?: string; // the ad ID
  source_type?: string;
  headline?: string;
  body?: string;
  media_type?: "image" | "video";
  ctwa_clid?: string; // missing for ads shown in WhatsApp Status
  welcome_message?: { text?: string };
};

export type InboundMessage = {
  id: string;
  from?: string; // omitted when the user has a username
  from_user_id?: string;
  timestamp: string; // unix seconds, as a string
  referral?: Referral;
};

export type AdLead = {
  customer: string;
  adId: string | null;
  headline: string | null;
  ctwaClid: string | null;
  firstMessageAt: number;
  firstReplyAt: number | null;
};

export type LeadStore = {
  get: (customer: string, adId: string | null) => Promise<AdLead | null>;
  save: (lead: AdLead) => Promise<void>;
  openFor: (customer: string) => Promise<AdLead[]>;
};

export const customerKey = (m: { from?: string; from_user_id?: string }): string => {
  const key = m.from_user_id ?? m.from;
  if (!key) throw new Error("message has neither from nor from_user_id");
  return key;
};

// One lead per customer per ad. A second click on the same ad keeps the first record and
// stores the newest click ID.
export const captureReferral = async (store: LeadStore, msg: InboundMessage): Promise<AdLead | null> => {
  const r = msg.referral;
  if (!r) return null;
  const customer = customerKey(msg);
  const adId = r.source_id ?? null;
  const at = Number(msg.timestamp) * 1000;
  const existing = await store.get(customer, adId);
  const lead: AdLead = existing
    ? { ...existing, ctwaClid: r.ctwa_clid ?? existing.ctwaClid }
    : { customer, adId, headline: r.headline ?? null, ctwaClid: r.ctwa_clid ?? null, firstMessageAt: at, firstReplyAt: null };
  await store.save(lead);
  return lead;
};
Enter fullscreen mode Exit fullscreen mode

One lead per customer per ad. A second tap on the same ad keeps the original timestamp, so "time to first reply" stays honest, and stores the newest click ID.

Route the first reply by ad, not by keyword

Most ad leads open with the ad's prefilled text, so the message itself says nothing about what they want. The ad does. A business running three ads (a demo-class offer, a fee-discount offer, a general brand ad) wants three different first replies and possibly three different teams. Map ad IDs to a flow and a team, with a fallback for ads you haven't mapped and for leads with no ad ID:

// Route the first reply by ad, not by keyword: the first message is usually the ad's prefilled
// text, so the ad ID is the only reliable signal of what the person wants.
export type AdRoute = { flow: string; team: string };
export const routeFor = (lead: AdLead, routes: Record<string, AdRoute>, fallback: AdRoute): AdRoute =>
  (lead.adId && routes[lead.adId]) || fallback;
Enter fullscreen mode Exit fullscreen mode

Keep the map in configuration, not code, because the marketing team creates ads faster than you deploy. An unmapped ad should fall back to a general menu, never to silence.

The 24 hours that decide the cost

The free entry point window is the reason to treat ad leads differently from other chats. From Meta's pricing page:

  • If a user messages you from a Click-to-WhatsApp ad on the Android or iOS app (not desktop or web), and you respond inside the 24-hour customer service window, that response "is not charged and opens a Free Entry Point (“FEP”) window, starting from the time when you responded."
  • "The FEP window may remain open for up to 7 days."
  • "While open, Meta does not charge for marketing, utility, authentication or service messages." Meta Business Agent messages are the exception.
  • The window belongs to "the business and WhatsApp user pair", not to the Messaging account that paid for the ad.

Meta's marketing site still describes a free period of "3 days (72 hours)", the wording from the older conversation-based pricing. The developer page, dated for the October 2026 pricing, says up to 7 days from your reply.

The engineering consequence: the window only opens if someone answers within 24 hours. An ad lead that sits unanswered for a day costs you the free window and the lead. So the inbox needs a view sorted by how much of the 24 hours is left:

const DAY = 24 * 60 * 60 * 1000;

// The free entry point window only opens if you reply inside the 24-hour customer service
// window. Ad leads nobody has answered yet, most urgent first.
export const unansweredAdLeads = (leads: AdLead[], now: number) =>
  leads
    .filter((l) => l.firstReplyAt === null && now - l.firstMessageAt < DAY)
    .map((l) => ({ ...l, minutesLeft: Math.floor((l.firstMessageAt + DAY - now) / 60_000) }))
    .sort((a, b) => a.minutesLeft - b.minutesLeft);

export const recordReply = async (store: LeadStore, customer: string, at: number) => {
  for (const lead of await store.openFor(customer)) {
    if (lead.firstReplyAt === null) await store.save({ ...lead, firstReplyAt: at });
  }
};
Enter fullscreen mode Exit fullscreen mode

Put this list at the top of the inbox, or alert on it. It's the cheapest conversion fix in the whole funnel.

Seeing which messages were free

You don't have to compute the window yourself; Meta tells you per message. In status webhooks, the pricing object marks a message sent inside an open window with type: "free_entry_point" and category: "referral_conversion":

// Status webhooks say whether a message went out free inside the window.
// Use pricing.type and pricing.category; `billable` is on its way out.
export type Pricing = { type?: string; category?: string; pricing_model?: string; billable?: boolean };
export const isFreeEntryPoint = (p: Pricing | undefined): boolean =>
  p?.type === "free_entry_point" || p?.category === "referral_conversion";
Enter fullscreen mode Exit fullscreen mode

Use pricing.type and pricing.category, as Meta's status webhook reference recommends; the billable flag "will be deprecated in a future versioned release." Since v24, the conversation object only appears on webhooks for messages sent inside a free entry point window, with an ID that's unique per window, which is handy for counting windows per ad.

Sending conversions back to Meta

Without conversion data, the ad optimises for what Meta can see: people who started a chat. The Conversions API for Business Messaging lets you report what happened afterwards, such as a lead qualified or an order paid, tied to the click.

Setup, once per WhatsApp account:

  1. Your app needs the whatsapp_business_manage_events permission, with advanced access.
  2. POST /{WABA_ID}/dataset creates the dataset, or returns the existing one: "If there is already an existing dataset_id associated with the Whatsapp Business Account, it will return that ID."
  3. Events go to POST /{DATASET_ID}/events.

Each event carries action_source: "business_messaging", messaging_channel: "whatsapp", and user_data with your whatsapp_business_account_id and the ctwa_clid, which Meta says not to hash. Meta lists 14 event names for business messaging, including LeadSubmitted, QualifiedLead, OrderCreated and Purchase.

export type ConversionEvent = {
  event_name: "LeadSubmitted" | "QualifiedLead" | "Purchase" | "OrderCreated";
  event_time: number; // unix seconds
  event_id: string;
  action_source: "business_messaging";
  messaging_channel: "whatsapp";
  user_data: { whatsapp_business_account_id: string; ctwa_clid: string };
  custom_data?: { currency: string; value: number };
};

const MAX_AGE_S = 7 * 24 * 60 * 60;

// Build an event Meta can attribute, or say why not. One stale event fails the whole request,
// so age is checked here rather than discovered there.
export const conversionFor = (
  lead: AdLead,
  e: { name: ConversionEvent["event_name"]; at: number; ref: string; value?: { currency: string; amount: number } },
  wabaId: string,
  now: number,
): { event: ConversionEvent } | { skip: "no_click_id" | "too_old" } => {
  if (!lead.ctwaClid) return { skip: "no_click_id" };
  const eventTime = Math.floor(e.at / 1000);
  if (Math.floor(now / 1000) - eventTime > MAX_AGE_S) return { skip: "too_old" };
  return {
    event: {
      event_name: e.name,
      event_time: eventTime,
      event_id: `${e.name}:${e.ref}`,
      action_source: "business_messaging",
      messaging_channel: "whatsapp",
      user_data: { whatsapp_business_account_id: wabaId, ctwa_clid: lead.ctwaClid },
      ...(e.value ? { custom_data: { currency: e.value.currency, value: e.value.amount } } : {}),
    },
  };
};
Enter fullscreen mode Exit fullscreen mode

Three rules are built into that function:

  • No click ID, no event. Meta has a fallback that matches hashed customer details, but it "attributes an event to an ad interaction from the past seven days" and "is available in a subset of countries". Status-ad leads have no click ID at all. Skipping them is honest; guessing isn't.
  • Seven days, or the whole batch fails. Meta's general Conversions API rules say event_time "can be up to 7 days before you send an event", and if any event in a request is older, "we return an error for the entire request". The business-messaging guide doesn't state a limit of its own, so we apply the general one to be safe, and check age before we batch.
  • Events are about the chat. Meta's guide says these events "should only represent customer interactions that occur in the messaging thread, not conversions that occur on other channels." A purchase on your website after the chat belongs to your web pixel, not here.

Deduplication: do it yourself

Meta's pages disagree. The general Conversions API docs say a repeated event_id and event_name is collapsed to the first copy; the business-messaging guide says "Meta does not assist with deduplicating events for Conversions API for Business Messaging". Don't depend on either. Keep an outbox keyed by event_id, and only mark events sent after Meta accepts the batch:

export type Outbox = { has: (eventId: string) => Promise<boolean>; mark: (eventIds: string[]) => Promise<void> };
export type PostEvents = (datasetId: string, data: ConversionEvent[]) => Promise<{ ok: boolean; error?: string }>;

// Meta's business-messaging guide says it doesn't deduplicate these events for you,
// so an outbox keyed by event_id makes retries safe.
export const sendConversions = async (post: PostEvents, outbox: Outbox, datasetId: string, events: ConversionEvent[]) => {
  const fresh: ConversionEvent[] = [];
  for (const e of events) if (!(await outbox.has(e.event_id)) && !fresh.some((f) => f.event_id === e.event_id)) fresh.push(e);
  if (!fresh.length) return { sent: 0 };
  const res = await post(datasetId, fresh);
  if (!res.ok) throw new Error(`conversions rejected: ${res.error ?? "unknown"}`);
  await outbox.mark(fresh.map((e) => e.event_id));
  return { sent: fresh.length };
};
Enter fullscreen mode Exit fullscreen mode

A deterministic event_id (Purchase:order-981) means a retry after a timeout, or the same webhook processed twice, can never report a sale twice.

Mistakes that cost ad leads

  • Treating ad leads like every other chat. The free window depends on answering within 24 hours, and a lead from a paid ad has already cost money. They belong at the top of the queue.
  • A keyword bot as the only first responder. "Hello! Can I get more info on this?" matches no keyword, so the lead gets nothing, or a generic menu that ignores the ad they tapped.
  • Not storing ctwa_clid on the first message. There's no documented way to get it later, so conversion reporting is impossible for every lead you didn't save.
  • Sending conversions from a nightly job without an age check. A batch that includes one event older than 7 days fails entirely, including the events that were fine.
  • Counting free messages yourself. The window opens from your first reply and is shared across the business and user pair; pricing.type already tells you which messages were free.
  • Reporting chats as the result. A cheap chat that never buys is not a good ad. Report qualified leads and purchases per ad, or the budget follows the wrong ads.

A report that's worth having

With leads, replies, free-window webhooks and conversions in your database, the ad report writes itself, per source_id:

  • leads (first messages from the ad);
  • answered within 24 hours, and the median time to first reply;
  • leads with a free window opened;
  • qualified leads and purchases, with revenue;
  • leads with no click ID (Status ads), reported separately.

That's the report most businesses running these ads don't have: not "how many chats did the ad start" but "how many paying customers, and how many did we lose by answering late".

What WAPGROWAI does today, and what it doesn't

Measured against this post, honestly:

  • Ad leads arrive in the shared inbox like any other chat, and the team can answer them from there. A Welcome Message rule (off by default) can greet people who start a new chat.
  • We don't read the referral object. The ad ID, the ad's headline and the click ID are discarded, so we can't show which ad a chat came from.
  • We have no view of ad leads sorted by time left in the 24-hour window, beyond the inbox's general handling of open and expired chats.
  • We don't read the pricing object on status webhooks, so we can't show which messages were free.
  • We don't send Conversions API events.

Every item in that list is what this post's code does, and it's the order we'd build it in.

Checklist

  • Store referral from the first message: ad ID, headline, body and ctwa_clid.
  • Key customers by from_user_id when from is missing.
  • Expect the default prefilled text as the first message, not a keyword.
  • Show unanswered ad leads sorted by time left in the 24-hour window.
  • Read free messages from pricing.type and pricing.category, not billable.
  • Create the dataset with POST /{WABA_ID}/dataset; send events to /{DATASET_ID}/events.
  • Send ctwa_clid unhashed; skip events without one rather than guessing.
  • Treat 7 days as the cutoff, and never let one old event sink a batch.
  • Use deterministic event_ids and your own outbox for deduplication.
  • Report per ad: leads, answered in time, windows opened, conversions, revenue.

WAPGROWAI is built by DI Solutions, a custom software and AI development company. This series covers what we've learned building WAPGROWAI on the WhatsApp Cloud API. Related: What does a WhatsApp message cost? Estimating and reconciling Cloud API charges in code and WhatsApp usernames will break your phone-keyed contacts.

Top comments (0)