Attribute WhatsApp sales to Click to WhatsApp ads
Flownally exposes the ad and the click ID on the message. Joining them to orders and reporting happen in your systems.
How does Click to WhatsApp attribution work?
Ad tap → first customer message → message.created → ad_clicks row → order → attributed_orders row → revenue per ad
- The shopper taps a Click to WhatsApp ad and sends a message. Meta attaches a
referralto that message only. - Flownally stores the referral on the message: the click ID in
attribution, the ad incontexts. - Your webhook consumer inserts one row per click.
- Your order pipeline resolves the order to a conversation and picks the newest click before the order time.
- Your server records the order against the click, and your reports aggregate by ad.
Requirements
| Item | Detail |
|---|---|
| Flownally API key | Service account key with conversation:read, contact:list, contact:read. See Authentication. |
| Webhook | Verified endpoint subscribed to message.created. See Set up and verify webhooks. |
| Storage | Two tables: clicks and attributed orders, defined below. |
Data contract
A customer message that came from an ad carries an about context, and usually attribution. Trimmed message.created delivery:
{
"id": "evt_d7pjmuk9lfdk4tgvlnpg",
"type": "message.created",
"timestamp": "2026-04-30T10:35:00.412305Z",
"data": {
"conversationId": "cnv_d7pigoip4tfcdebp5mlg",
"inboxId": "ibx_d7pi2efp0k7nba4e1mt0",
"message": {
"id": "msg_d7pj3rljs4umccbo6tdg",
"conversationId": "cnv_d7pigoip4tfcdebp5mlg",
"kind": "message",
"senderType": "customer",
"content": {
"type": "text",
"text": { "body": "Is the linen shirt still available in M?" }
},
"contexts": [
{
"relation": "about",
"reference": {
"type": "resource",
"resourceType": "ad",
"channel": "whatsapp",
"externalId": "120208123456780123"
},
"resourceSnapshot": {
"resourceType": "ad",
"subtype": "image",
"title": "Linen shirts, 20% off",
"text": "Summer linen in six colours.",
"permalink": "https://fb.me/2ZulEu42P",
"mediaUrl": "https://scontent.whatsapp.net/…",
"thumbnailUrl": "",
"capturedAt": "2026-04-30T10:34:58.000000Z"
}
}
],
"attribution": {
"clickId": "ARAkLkA8rmlFeiCktEJQ-QTwRiyYHAFDLMNDBH0CD3qpjd0HR4irJ6LEkR7JwFF4XvnO2E4Nx0"
},
"createdAt": "2026-04-30T10:35:00.412305Z"
}
}
}| Field | Meta source | Notes |
|---|---|---|
message.attribution.clickId | referral.ctwa_clid | Omitted when Meta sends none (WhatsApp Status ads). Personal data. MessageAttribution |
contexts[].relation | about for the ad. A replyTo context can also be present. | |
contexts[].reference.resourceType | referral.source_type | ad, or post for a promoted post. Other values are read as ad. |
contexts[].reference.externalId | referral.source_id | Meta ad or post ID. The context is omitted when Meta sends none. |
resourceSnapshot.subtype | referral.media_type | image, video, or unknown. |
resourceSnapshot.title | referral.headline | Optional. |
resourceSnapshot.text | referral.body | Primary text. |
resourceSnapshot.permalink | referral.source_url | |
resourceSnapshot.mediaUrl, thumbnailUrl | image_url / video_url, thumbnail_url | Meta CDN URLs. They expire; see the note on copying media under Store every click. |
resourceSnapshot.capturedAt | message timestamp | Time the message was sent, or received if unknown. |
Invariants:
attributionand theaboutcontext are independent: either can be present without the other.- Both are set only on the first customer message after a tap. Later messages in the conversation carry neither.
- The same fields are on the Message returned by Get message and List conversation messages, so a missed delivery can be recovered by listing the conversation.
The click ID is personal data
Meta defines ctwa_clid as a personal identifier, unique per click. Store it with your customer data, exclude it from logs, and never put it in a URL. Delete it when your attribution window has passed and when you erase the contact.
Subscribe to message.created
Add message.created to eventTypes with PATCH /webhooks and verify the endpoint (Set up the endpoint).
The receiver verifies the signature on the raw body (Verify webhook signatures), enqueues the event and returns 204. Process events asynchronously. Delivery is at-least-once and unordered: deduplicate on the webhook-id header (equal to the payload id) and don't assume arrival order.
Store every click
Schema: one row per click, keyed by the message that carried it. Rows are never updated, so a later tap can't change what an earlier order was attributed to.
create table ad_clicks (
message_id text primary key,
conversation_id text not null,
contact_id text,
inbox_id text not null,
click_id text,
ad_id text,
ad_title text,
received_at timestamptz not null
);
create index ad_clicks_conversation_time on ad_clicks (conversation_id, received_at desc);Insert per event. Redeliveries hit the primary key and change nothing:
insert into ad_clicks (message_id, conversation_id, contact_id, inbox_id, click_id, ad_id, ad_title, received_at)
values ($1, $2, $3, $4, $5, $6, $7, $8)
on conflict (message_id) do nothing;The consumer extracts the click from customer messages only:
// ad-clicks.js
function adContext(message) {
return (message.contexts ?? []).find(
(context) =>
context.relation === "about" &&
context.reference.type === "resource" &&
context.reference.channel === "whatsapp" &&
["ad", "post"].includes(context.reference.resourceType),
);
}
// Returns the click to store, or null when the message didn't come from an ad.
export function adClickFrom(event) {
const { message, conversationId, inboxId } = event.data;
if (message.senderType !== "customer") return null;
const clickId = message.attribution?.clickId;
const ad = adContext(message);
if (!clickId && !ad) return null;
return {
messageId: message.id,
conversationId,
contactId: event.data.contact?.id ?? event.data.conversation?.contactId ?? null,
inboxId,
clickId: clickId ?? null,
adId: ad?.reference.externalId ?? null,
adTitle: ad?.resourceSnapshot?.title ?? null,
receivedAt: message.createdAt,
};
}
// Your queue worker.
export async function handleMessageCreated(event) {
const click = adClickFrom(event);
if (click) await db.saveAdClick(click); // The insert above.
}contactId is nullable: a conversation may not be linked to a contact yet. The join key is conversationId.
To keep the ad image for reports, download it when you store the click: mediaUrl and thumbnailUrl expire. Fetch only https URLs on Meta's CDN hosts (*.fbcdn.net, *.whatsapp.net), and only from events whose signature you verified.
Resolve an order to a click
| Order source | Join |
|---|---|
| In chat (agent, bot or checkout link) | The conversation is known. Take its newest click with received_at before the order time. |
| Store checkout | Order phone (E.164) → contact via cf_phone search → contact's WhatsApp conversations → newest click with received_at before the order time. |
Phone search follows Sync store customers and phone numbers; Get contact returns conversations.
const FLOWNALLY_API = "https://api.flownally.com/v1";
const headers = {
Authorization: `Bearer ${process.env.FLOWNALLY_API_TOKEN}`,
"Content-Type": "application/json",
};
// phone is the order's phone number in E.164. Returns the click, or null.
export async function clickForOrder(phone, orderedAt) {
const search = await fetch(`${FLOWNALLY_API}/contacts:search`, {
method: "POST",
headers,
signal: AbortSignal.timeout(10_000),
body: JSON.stringify({
query: {
match: "all",
conditions: [
{ type: "customFieldText", fieldId: "cf_phone", operator: "equals", value: phone },
{ type: "archiveStatus", status: "all" },
],
},
pageSize: 1,
}),
});
if (!search.ok) throw new Error(`Flownally API returned ${search.status}`);
const { contacts } = await search.json();
if (contacts.length === 0) return null;
const response = await fetch(`${FLOWNALLY_API}/contacts/${contacts[0].id}`, {
headers,
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error(`Flownally API returned ${response.status}`);
const contact = await response.json();
const conversationIds = contact.conversations
.filter((conversation) => conversation.channel === "whatsapp")
.map((conversation) => conversation.conversationId);
// Your database: the newest click in these conversations received before orderedAt.
return db.latestAdClick(conversationIds, orderedAt);
}Known misses: a shopper who chats from one number and checks out with another doesn't match, and the order stays unattributed. Apply your own click-to-order window and ignore older clicks.
Record the order against the click
Store one row per attributed order, with the ad copied onto it, so revenue reports read only this table:
create table attributed_orders (
order_id text primary key,
conversation_id text not null,
click_id text,
ad_id text,
ad_title text,
total numeric not null,
currency text not null,
ordered_at timestamptz not null
);When an order is paid, resolve its conversation (previous section) and insert the row. The click is chosen by order time, not arrival time, so a late or retried order webhook still gets the click that preceded the order. order_id as the primary key makes retries idempotent:
insert into attributed_orders (order_id, conversation_id, click_id, ad_id, ad_title, total, currency, ordered_at)
select $1, c.conversation_id, c.click_id, c.ad_id, c.ad_title, $2, $3, $4
from ad_clicks c
where c.conversation_id = $5
and c.received_at <= $4
and c.received_at > $4 - interval '28 days' -- your click-to-order window
order by c.received_at desc
limit 1
on conflict (order_id) do nothing;Run it from the code path that already handles paid orders, for example the Shopify orders/create webhook in Send Shopify order updates on WhatsApp or the woocommerce_order_status_changed hook in Send WooCommerce order updates on WhatsApp.
Report revenue per ad
Revenue comes from attributed_orders only, grouped by currency so amounts are never summed across currencies. Conversations come from ad_clicks, counted once per ad:
with conversations as (
select ad_id, max(ad_title) as ad_title, count(distinct conversation_id) as conversations
from ad_clicks
where ad_id is not null
and received_at >= $1 and received_at < $2
group by ad_id
),
revenue as (
select ad_id, currency, count(*) as orders, sum(total) as revenue
from attributed_orders
where ad_id is not null
and ordered_at >= $1 and ordered_at < $2
group by ad_id, currency
)
select c.ad_id, c.ad_title, c.conversations, r.currency, coalesce(r.orders, 0) as orders, r.revenue
from conversations c
left join revenue r on r.ad_id = c.ad_id
order by c.ad_id, r.currency;An ad with no orders in the period has one row with a null currency. Rank ads within one currency, not across currencies.
Verify the integration
- Tap one of your Click to WhatsApp ads from a test phone and send a message.
- Get message:
attribution.clickIdand anaboutcontext withresourceType: "ad"are present. ad_clickshas a row for the conversation.- Place an order with the same phone number;
attributed_ordershas a row with the ad'sad_id.
Troubleshooting
| Symptom | Cause | Action |
|---|---|---|
No attribution and no about context | The conversation didn't start from an ad, or this isn't the first message after the tap. | Check the conversation's first customer message with List conversation messages. |
about context without attribution | Meta sent no ctwa_clid (Status ads). | Attribute by ad_id; click_id stays null. |
| Ad image no longer loads | mediaUrl and thumbnailUrl are expiring Meta CDN URLs. | Copy the asset when you store the click (see Store every click). |
FAQ
Who can read the click ID?
Any principal that can read the message through the REST API, and your webhook endpoint. The Flownally inbox shows the ad the chat started from, but not the click ID.
Messenger and Instagram ads?
Not covered. attribution is set only for Click to WhatsApp ads.
What happens when a shopper taps a second ad?
The second tap produces a new referral on the next first message and a new ad_clicks row. An order is attributed to the newest click before it, so earlier orders keep their ad.