# Attribute WhatsApp sales to Click to WhatsApp ads

:::summary Quick answer
Read the `about` context (the ad) and `message.attribution.clickId` (Meta's `ctwa_clid`) from `message.created` and store one row per click. When an order is paid, attribute it to the conversation's newest click before the order time, and keep the ad on the order row. Revenue per ad is then a query over your orders.

**The referral is present only on the first customer message after the ad tap. Capture it on arrival; it is not repeated.**
:::

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**

1. The shopper taps a Click to WhatsApp ad and sends a message. Meta attaches a `referral` to that message only.
2. Flownally stores the referral on the message: the click ID in `attribution`, the ad in `contexts`.
3. Your webhook consumer inserts one row per click.
4. Your order pipeline resolves the order to a conversation and picks the newest click before the order time.
5. 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](/api/authentication). |
| Webhook | Verified endpoint subscribed to `message.created`. See [Set up and verify webhooks](/api/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:

```json
{
  "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](/api/reference/schemas/message-attribution) |
| `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:

- `attribution` and the `about` context 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](/api/reference/schemas/message) returned by [Get message](/api/reference/messaging/get-message) and [List conversation messages](/api/reference/messaging/list-conversation-messages), so a missed delivery can be recovered by listing the conversation.

:::callout 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`](/api/reference/webhooks#update-webhook-settings) and verify the endpoint ([Set up the endpoint](/api/webhooks#set-up-the-endpoint)).

The receiver verifies the signature on the raw body ([Verify webhook signatures](/api/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.

```sql
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:

```sql
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:

:::code Read the click from message.created
```js
// 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.
}
```

```python
# ad_clicks.py
def ad_context(message):
    for context in message.get("contexts", []):
        reference = context["reference"]
        if (
            context["relation"] == "about"
            and reference["type"] == "resource"
            and reference.get("channel") == "whatsapp"
            and reference.get("resourceType") in ("ad", "post")
        ):
            return context
    return None


# Returns the click to store, or None when the message didn't come from an ad.
def ad_click_from(event):
    data = event["data"]
    message = data["message"]
    if message["senderType"] != "customer":
        return None

    click_id = message.get("attribution", {}).get("clickId")
    ad = ad_context(message)
    if not click_id and not ad:
        return None

    return {
        "message_id": message["id"],
        "conversation_id": data["conversationId"],
        "contact_id": (data.get("contact") or {}).get("id")
        or (data.get("conversation") or {}).get("contactId"),
        "inbox_id": data["inboxId"],
        "click_id": click_id,
        "ad_id": ad["reference"]["externalId"] if ad else None,
        "ad_title": (ad.get("resourceSnapshot") or {}).get("title") if ad else None,
        "received_at": message["createdAt"],
    }


# Your queue worker.
def handle_message_created(event):
    click = ad_click_from(event)
    if click:
        db.save_ad_click(click)  # The insert above.
```

```php
<?php
// ad_clicks.php
function adContext(array $message): ?array
{
    foreach ($message['contexts'] ?? [] as $context) {
        $reference = $context['reference'];
        if (
            $context['relation'] === 'about'
            && $reference['type'] === 'resource'
            && ($reference['channel'] ?? null) === 'whatsapp'
            && in_array($reference['resourceType'] ?? null, ['ad', 'post'], true)
        ) {
            return $context;
        }
    }
    return null;
}

// Returns the click to store, or null when the message didn't come from an ad.
function adClickFrom(array $event): ?array
{
    $data = $event['data'];
    $message = $data['message'];
    if ($message['senderType'] !== 'customer') {
        return null;
    }

    $clickId = $message['attribution']['clickId'] ?? null;
    $ad = adContext($message);
    if ($clickId === null && $ad === null) {
        return null;
    }

    return [
        'messageId' => $message['id'],
        'conversationId' => $data['conversationId'],
        'contactId' => $data['contact']['id'] ?? $data['conversation']['contactId'] ?? null,
        'inboxId' => $data['inboxId'],
        'clickId' => $clickId,
        'adId' => $ad['reference']['externalId'] ?? null,
        'adTitle' => $ad['resourceSnapshot']['title'] ?? null,
        'receivedAt' => $message['createdAt'],
    ];
}

// Your queue worker.
function handleMessageCreated(array $event): void
{
    $click = adClickFrom($event);
    if ($click !== null) {
        saveAdClick($click); // Your database: 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](/api/sync-store-customers); [Get contact](/api/reference/contacts/get-contact) returns `conversations`.

:::code Find the click for a store order
```js
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);
}
```

```python
import os

import requests

FLOWNALLY_API = "https://api.flownally.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FLOWNALLY_API_TOKEN']}"}


# phone is the order's phone number in E.164. Returns the click, or None.
def click_for_order(phone, ordered_at):
    search = requests.post(
        f"{FLOWNALLY_API}/contacts:search",
        headers=HEADERS,
        json={
            "query": {
                "match": "all",
                "conditions": [
                    {"type": "customFieldText", "fieldId": "cf_phone", "operator": "equals", "value": phone},
                    {"type": "archiveStatus", "status": "all"},
                ],
            },
            "pageSize": 1,
        },
        timeout=10,
    )
    search.raise_for_status()
    contacts = search.json()["contacts"]
    if not contacts:
        return None

    response = requests.get(f"{FLOWNALLY_API}/contacts/{contacts[0]['id']}", headers=HEADERS, timeout=10)
    response.raise_for_status()
    conversation_ids = [
        conversation["conversationId"]
        for conversation in response.json()["conversations"]
        if conversation["channel"] == "whatsapp"
    ]

    # Your database: the newest click in these conversations received before ordered_at.
    return db.latest_ad_click(conversation_ids, ordered_at)
```

```php
<?php
// $phone is the order's phone number in E.164. Returns the click, or null.
function clickForOrder(string $phone, string $orderedAt): ?array
{
    $client = new GuzzleHttp\Client([
        'base_uri' => 'https://api.flownally.com/v1/',
        'headers' => ['Authorization' => 'Bearer ' . getenv('FLOWNALLY_API_TOKEN')],
        'timeout' => 10,
    ]);

    $search = $client->post('./contacts:search', ['json' => [
        'query' => [
            'match' => 'all',
            'conditions' => [
                ['type' => 'customFieldText', 'fieldId' => 'cf_phone', 'operator' => 'equals', 'value' => $phone],
                ['type' => 'archiveStatus', 'status' => 'all'],
            ],
        ],
        'pageSize' => 1,
    ]]);
    $contacts = json_decode((string) $search->getBody(), true)['contacts'];
    if (!$contacts) {
        return null;
    }

    $response = $client->get("contacts/{$contacts[0]['id']}");
    $contact = json_decode((string) $response->getBody(), true);
    $conversationIds = array_column(
        array_filter($contact['conversations'], fn ($conversation) => $conversation['channel'] === 'whatsapp'),
        'conversationId',
    );

    // Your database: the newest click in these conversations received before $orderedAt.
    return 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:

```sql
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:

```sql
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](/api/shopify-order-updates) or the `woocommerce_order_status_changed` hook in [Send WooCommerce order updates on WhatsApp](/api/woocommerce-order-updates).

## 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:

```sql
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

1. Tap one of your Click to WhatsApp ads from a test phone and send a message.
2. [Get message](/api/reference/messaging/get-message): `attribution.clickId` and an `about` context with `resourceType: "ad"` are present.
3. `ad_clicks` has a row for the conversation.
4. Place an order with the same phone number; `attributed_orders` has a row with the ad's `ad_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](/api/reference/messaging/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.

## Related articles

- [Set up and verify webhooks](/api/webhooks)
- [Verify webhook signatures](/api/webhook-signatures)
- [Sync store customers and phone numbers](/api/sync-store-customers)
- [Send Shopify order updates on WhatsApp](/api/shopify-order-updates)
- [Send WooCommerce order updates on WhatsApp](/api/woocommerce-order-updates)
