# Conversions API for click-to-WhatsApp ads: send purchase events

> Report purchases from click-to-WhatsApp chats to Meta: ctwa_clid from the referral webhook, dataset setup, event names and the hashed fallback.

Published 2026-11-04. Z-API Omni team.

Store the `ctwa_clid` from the `referral` object of the first inbound message, then post it with the sale to `POST /{DATASET_ID}/events`. Set `action_source` to `business_messaging` and `messaging_channel` to `whatsapp`. That is Meta's Conversions API for Business Messaging ([Meta guide, accessed 2026-11-04](https://developers.facebook.com/docs/marketing-api/conversions-api/business-messaging)). It lets "Business Messaging Partners share their clients' data, for which they have permissions, directly from their servers". The stated goal is to help partners "understand and improve performance for their clients' ads that click to WhatsApp, Messenger or Instagram."

The guide is written for partners sending on behalf of clients, and every request carries a top-level `partner_agent` field with your partner name. Events "should only represent customer interactions that occur in the messaging thread." Purchase optimization works for Messenger and WhatsApp ads, "but is not available for Instagram ad optimization at this time."

## Where ctwa_clid comes from

When a user opens the chat from a click-to-WhatsApp ad, their message arrives in the Messages webhook with a `referral` object. It sits inside `messages[0]`, before `from`, `id` and `type` ([text message webhook reference, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)). The fields Meta documents in it:

| Field | Meta's description |
| --- | --- |
| `source_id` | Click to WhatsApp ad ID |
| `source_url` | Click to WhatsApp ad URL |
| `source_type` | `ad` in the example |
| `headline` and `body` | The ad's headline and primary text |
| `media_type` | `image` or `video`, with `image_url`, or `video_url` and `thumbnail_url` |
| `ctwa_clid` | Click to WhatsApp ad click ID |
| `welcome_message.text` | The ad's greeting text |

"The `ctwa_clid` property is omitted entirely for messages originating from an ad in WhatsApp Status." Treat it as optional, and use the hashed fallback below for those leads. The full referral payload and a table to store it are in [click-to-WhatsApp ads and the free entry point](/academy/articles/whatsapp-click-to-whatsapp-ads-free-entry-point/).

This function pulls the click ID out of a webhook body. It reads `from` with `from_user_id` (the business-scoped user ID) as fallback. Meta's ad example shows only `from`, so the fallback is a precaution.

```python
def ad_clicks(payload: dict):
    """Yield (sender, ctwa_clid, ad_id) for messages that came from a click-to-WhatsApp ad."""
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            for msg in change.get("value", {}).get("messages", []):
                ref = msg.get("referral")
                if not ref:
                    continue
                sender = msg.get("from") or msg.get("from_user_id")
                yield sender, ref.get("ctwa_clid"), ref.get("source_id")
```

Save the click ID against the conversation. When the order closes, you need it again. Other webhook fields are listed in [the webhook payload reference](/academy/articles/whatsapp-webhook-payload-reference-messages-statuses/).

## Access you need before the first event

The access token needs `whatsapp_business_management` and `whatsapp_business_manage_events`. The client must be on the Cloud API and onboarded through a login solution, either Embedded Signup or Facebook Login for Business. You get the client's WhatsApp Business Account ID "on completion of Embedded Signup flow", as covered in [onboarding clients with Embedded Signup](/academy/articles/whatsapp-embedded-signup-onboarding-clients/).

Your app also needs Full Access to the Marketing API, which Meta renamed from "Advanced Access". Meta's page disagrees with itself on the bar. A banner says the threshold dropped "from 1,500 to 500 Marketing API calls". The sections below it still ask for "1500 successful Marketing API calls with an error rate of less than 10%" within 15 days. Until Meta reconciles the two, plan for 1,500.

## Create or fetch the dataset

The guide says to "Use the `whatsapp_business_account_id` and `access_token` to create a dataset by making a `POST` call". A `GET` call to the same URL retrieves it. "The response will be an ID, which represents the `dataset_id`." Meta gives the URL but no curl or response sample for WhatsApp, so this call is built from that URL:

```bash
curl -X POST "https://graph.facebook.com/v26.0/<WHATSAPP_BUSINESS_ACCOUNT_ID>/dataset?access_token=<ACCESS_TOKEN>"
```

Store the returned `dataset_id` per client. After a successful send, the event shows in the client's Events Manager. As a partner, "you will need to instruct your advertiser on how to access their dataset in their Events Manager." The guide mentions no test events tool.

## The event payload

Four things are required. `action_source` is `business_messaging`. `messaging_channel` is `whatsapp`, `messenger` or `instagram`. `user_data` carries the channel's identifiers. `partner_agent` is your partner name. On WhatsApp, `user_data` holds `whatsapp_business_account_id` and `ctwa_clid`. Messenger uses `page_id` with `page_scoped_user_id`, and Instagram uses `instagram_business_account_id` with `ig_sid`.

Meta's WhatsApp sample, cleaned so it parses: the page has a `//` comment inside the JSON and an unquoted WABA ID placeholder. The example click ID is replaced by the placeholder its comment named.

```json
{
  "data": [
    {
      "event_name": "Purchase",
      "event_time": 1675999999,
      "action_source": "business_messaging",
      "messaging_channel": "whatsapp",
      "user_data": {
        "whatsapp_business_account_id": "<WHATSAPP_BUSINESS_ACCOUNT_ID>",
        "ctwa_clid": "<CLICK_TO_WHATSAPP_CLICK_ID>"
      },
      "custom_data": {
        "currency": "USD",
        "value": 123
      }
    }
  ],
  "partner_agent": "<PARTNER_NAME>"
}
```

`event_name` takes one of 14 values. The grouping below is ours. Meta lists them as one set.

| Group | Event names |
| --- | --- |
| Shopping | `Purchase`, `InitiateCheckout`, `AddToCart`, `ViewContent`, `CartAbandoned` |
| Orders | `OrderCreated`, `OrderShipped`, `OrderDelivered`, `OrderCanceled`, `OrderReturned` |
| Leads | `LeadSubmitted`, `QualifiedLead` |
| Feedback | `RatingProvided`, `ReviewProvided` |

The guide gives no age limit for `event_time`. The only time window it states is the seven days on the hashed path below.

## Send it from Python

This script uses only the standard library. It posts one event to the events endpoint and prints Meta's response.

```python
# send_event.py. Run:
# DATASET_ID=... ACCESS_TOKEN=... WABA_ID=... PARTNER_NAME=... python3 send_event.py CTWA_CLID 49.90 USD
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

DATASET_ID = os.environ["DATASET_ID"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
WABA_ID = os.environ["WABA_ID"]
PARTNER_NAME = os.environ["PARTNER_NAME"]

def send_event(ctwa_clid: str, value: float, currency: str, event_name: str = "Purchase") -> dict:
    body = {
        "data": [{
            "event_name": event_name,
            "event_time": int(time.time()),
            "action_source": "business_messaging",
            "messaging_channel": "whatsapp",
            "user_data": {"whatsapp_business_account_id": WABA_ID, "ctwa_clid": ctwa_clid},
            "custom_data": {"currency": currency, "value": value},
        }],
        "partner_agent": PARTNER_NAME,
    }
    query = urllib.parse.urlencode({"access_token": ACCESS_TOKEN})
    req = urllib.request.Request(
        f"https://graph.facebook.com/v26.0/{DATASET_ID}/events?{query}",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as err:
        raise SystemExit(f"{err.code}: {err.read().decode()}")

if __name__ == "__main__":
    print(send_event(sys.argv[1], float(sys.argv[2]), sys.argv[3]))
```

Deduplicate before calling it. "Meta does not assist with deduplicating events for Conversions API for Business Messaging." A webhook retry or a second order update can fire the same `Purchase` twice. Keep a table of sent events keyed on your order ID and event name, and skip any pair already in it. That table is our design, not a Meta requirement.

## When there is no ctwa_clid

Status ads and conversations you have no click ID for can still report conversions. Meta's instruction is to "send hashed customer information in `user_data` instead of `ctwa_clid`". Normalize each value and hash it with SHA-256 before sending, using keys such as `em` (email) or `ph` (phone). At least one of `em`, `ph`, `fn`, `ln`, `ct`, `st`, `zp`, `country`, `ge` or `db` is required. `external_id` "is not used for matching on this path".

Add `page_id` to `user_data` as well. Meta warns that "an event that omits `page_id` is rejected even when it carries valid customer information." The WhatsApp section doesn't say which Facebook Page that ID should point to.

This path is weaker. "Matching on hashed customer information is not guaranteed." It attributes an event to an ad interaction from the past seven days, and it works only in some countries.

Conversions from marketing messages use a different mechanism. Meta appends a click ID, usually `fbclid`, to call-to-action URLs and measures through the Pixel or the web Conversions API ([measure conversions, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/measure-conversion)). That setup belongs with the [Marketing Messages API](/academy/articles/whatsapp-marketing-messages-api/).

*Z-API Omni team*
