# WhatsApp API: campaigns, inbox, flows, commerce

> Campaigns, message reports, Team Inbox chats, opt-out, auto-responses, flows and commerce over the WhatsApp API.

Everything an operator does day to day in the dashboard is available over the
same API-key authenticated service, `pingx.whatsapp.v1.WhatsAppService`
(REST prefix `/whatsapp/v1/`, also callable as Connect/gRPC). This page covers
the calls added on top of numbers, messages, templates, media, webhook and
contacts. For contact labels see [contact-labels-api.md](https://docs.pingx.ai/contact-labels.md).

Base URL `https://api.pingx.ai`. Authenticate with an API key carrying the
`whatsapp` scope (or `whatsapp:read` / `whatsapp:write`):

```
Authorization: Bearer $PINGX_API_KEY
```

The organization always comes from the key; you never send it. A campaign,
chat, flow or batch id that belongs to another organization is reported as
`NOT_FOUND`.

## Conventions

* **Read vs write.** Calls whose RPC name starts with `Get`/`List` are reads
  (HTTP GET, need `whatsapp:read`); everything else is a write (need
  `whatsapp:write`). The bare `whatsapp` scope grants both.
* **Numbers.** `phone_number_id` selects which connected number to act on
  (see `GET /whatsapp/v1/numbers`). Optional while you have one number,
  required once you have several. In REST it is a query parameter for
  GET/DELETE and a body field otherwise. Phone numbers are E.164 digits; a
  leading `+` is accepted (URL-encode it as `%2B` inside a path).
* **Times** are RFC 3339 UTC (`2026-03-01T09:30:00Z`).
* **JSON names** are lowerCamelCase in REST (`pageSize`, `phoneNumberId`).
* **Pagination.** `page_size` + `page_token` in, `next_page_token` out. Pass
  the token back unchanged; empty means last page. Tokens are opaque.
* **Request size** is capped at 32 MiB.
* **Errors** use standard codes: `INVALID_ARGUMENT` (bad input),
  `NOT_FOUND`, `FAILED_PRECONDITION` (wrong state, e.g. template not
  approved), `RESOURCE_EXHAUSTED`, `UNAUTHENTICATED`, `PERMISSION_DENIED`.
  Some sends report a business refusal as `success:false` with a `message`
  instead (e.g. outside the 24-hour window, insufficient credits).
* **Billing.** Template sends from campaigns and free-text replies from
  `SendChatMessage` go through the same metering as `SendMessage` and the
  dashboard, so credits are charged and enforced identically.
* **Idempotency.** Create/send calls are not idempotent; retry only after
  checking (for example `ListCampaigns`). Set/Update/Delete/Block/Unblock/
  Cancel/MarkRead calls are idempotent.

## Endpoints

| RPC | Method and path | Scope |
|---|---|---|
| CreateCampaign | `POST /campaigns` | write |
| AddCampaignRecipients | `POST /campaigns/{campaign_id}/recipients:add` | write |
| StartCampaign | `POST /campaigns/{campaign_id}:start` | write |
| GetCampaign | `GET /campaigns/{campaign_id}` | read |
| ListCampaigns | `GET /campaigns` | read |
| CancelCampaign | `POST /campaigns/{campaign_id}:cancel` | write |
| ListMessageReports | `GET /message-reports` | read |
| ListInboundMessages | `GET /inbound-messages` | read |
| GetMessageStats | `GET /message-stats` | read |
| ListChats | `GET /chats` | read |
| ListChatMessages | `GET /chats/{contact}/messages` | read |
| SendChatMessage | `POST /chats/{contact}/messages` | write |
| MarkChatRead | `POST /chats/{contact}:markRead` | write |
| AssignChat | `POST /chats/{contact}:assign` | write |
| GetOptOutConfig / SetOptOutConfig | `GET` / `PUT /opt-out-config` | read / write |
| ListBlockedNumbers | `GET /blocked-numbers` | read |
| BlockNumber | `POST /blocked-numbers` | write |
| UnblockNumber | `DELETE /blocked-numbers/{mobile_number}` | write |
| ListAutoResponses / CreateAutoResponse | `GET` / `POST /auto-responses` | read / write |
| UpdateAutoResponse / DeleteAutoResponse | `PUT` / `DELETE /auto-responses/{auto_response_id}` | write |
| ListFlows / CreateFlow | `GET` / `POST /flows` | read / write |
| GetFlow | `GET /flows/{flow_id}` | read |
| UpdateFlow / DeleteFlow | `PUT` / `DELETE /flows/{flow_id}` | write |
| DuplicateFlow | `POST /flows/{flow_id}:duplicate` | write |
| SetFlowActive | `POST /flows/{flow_id}:setActive` | write |
| GetCommerceSettings / SetCommerceSettings | `GET` / `PUT /commerce/settings` | read / write |
| ConnectCatalog | `POST /commerce/catalogs:connect` | write |
| CreateCatalog | `POST /commerce/catalogs` | write |
| ListProductBatches / CreateProductBatch | `GET` / `POST /commerce/product-batches` | read / write |
| GetProductBatch | `GET /commerce/product-batches/{product_batch_id}` | read |
| SetProductBatchLive | `POST /commerce/product-batches/{product_batch_id}:setLive` | write |
| DeleteProductBatch | `DELETE /commerce/product-batches/{product_batch_id}` | write |

All paths are under `/whatsapp/v1`.

## Campaigns

A campaign sends one approved template to many recipients, rate limited by a
background worker. Flow: create (draft), add recipients in chunks of up to
5000, start, then poll.

```bash
B=https://api.pingx.ai/whatsapp/v1
H="Authorization: Bearer $PINGX_API_KEY"

# 1. draft
curl -s -X POST $B/campaigns -H "$H" -H 'Content-Type: application/json' -d '{
  "name": "March promo", "templateName": "promo_march", "language": "en_US",
  "category": "MARKETING", "ratePerSec": 20 }'
# -> {"campaignId":"c_123","ratePerSec":20}

# 2. recipients (repeat for more chunks; duplicates and opted-out are skipped)
curl -s -X POST $B/campaigns/c_123/recipients:add -H "$H" -H 'Content-Type: application/json' -d '{
  "recipients": [ {"mobile":"+15551234567","bodyParams":["Ana","20%"]} ] }'
# -> {"accepted":1,"duplicates":0,"skippedOptedOut":0,"total":1}

# 3. start, then poll
curl -s -X POST $B/campaigns/c_123:start -H "$H" -H 'Content-Type: application/json' -d '{}'
curl -s $B/campaigns/c_123 -H "$H"      # status, counters, delivered/read, first 100 failures
curl -s -X POST $B/campaigns/c_123:cancel -H "$H" -H 'Content-Type: application/json' -d '{}'
```

Statuses: `draft`, `queued`, `running`, `completed`, `cancelled`, `failed`.
Set `scheduledAt` (RFC 3339) on create to hold the campaign until then.
`sent` means Meta accepted the message; `delivered`/`read`/`deliveryFailed`
(from `GetCampaign`) are the later webhook results. `ListCampaigns` returns the
200 most recent campaigns, newest first.

## Reports, stats and exports

`GET /message-reports` is the per-message delivery log. **It replaces the
dashboard's CSV export** (`/whatsapp/report/export.csv`), which only works
with a browser session: loop on `nextPageToken` to export a time range.

```bash
curl -s "$B/message-reports?from=2026-03-01T00:00:00Z&to=2026-04-01T00:00:00Z&status=failed&pageSize=200" -H "$H"
curl -s "$B/message-reports?pageToken=$TOKEN&pageSize=200" -H "$H"   # next page; repeat the same filters
curl -s "$B/inbound-messages?from=2026-03-01T00:00:00Z&pageSize=50" -H "$H"
curl -s "$B/message-stats?from=2026-03-01T00:00:00Z&to=2026-03-08T00:00:00Z" -H "$H"
```

`GetMessageStats` needs both `from` and `to`; it returns the funnel
(initiated, sent, delivered, read, failed, replies) and a 7-day daily series.

## Team Inbox chats

```bash
curl -s "$B/chats?assigneeFilter=unassigned&pageSize=50" -H "$H"
curl -s "$B/chats/%2B15551234567/messages?pageSize=50" -H "$H"   # newest page first
curl -s -X POST "$B/chats/%2B15551234567/messages" -H "$H" -H 'Content-Type: application/json' -d '{"body":"Thanks, on it!"}'
curl -s -X POST "$B/chats/%2B15551234567:markRead" -H "$H" -H 'Content-Type: application/json' -d '{}'
curl -s -X POST "$B/chats/%2B15551234567:assign" -H "$H" -H 'Content-Type: application/json' -d '{"assigneeId":"user_abc"}'
```

* Free-text replies work only inside the 24-hour window after the customer's
  last message (`outsideServiceWindow` on the messages call tells you).
  Outside it, `SendChatMessage` returns `success:false`; send an approved
  template with `POST /messages` instead.
* API keys have no user: `assigneeFilter:"mine"` and `assigneeId:"me"` are
  rejected. `assigneeId` must be a member of the organization and, on the
  public API, is accepted only where the gateway has the member directory
  configured; empty `assigneeId` always unassigns.
* Inbox agents (the restricted dashboard role) cannot use these public
  routes; they use the dashboard's own inbox calls.

## Opt-out, blocked numbers, auto-responses

```bash
curl -s -X PUT $B/opt-out-config -H "$H" -H 'Content-Type: application/json' -d '{
  "matchType":"exact","optoutKeywords":["STOP"],"optoutResponse":"You are unsubscribed.","optoutActive":true,
  "optinKeywords":["START"],"optinResponse":"Welcome back!","optinActive":true }'
curl -s -X POST $B/blocked-numbers -H "$H" -H 'Content-Type: application/json' -d '{"mobileNumber":"+15551234567"}'
curl -s -X DELETE "$B/blocked-numbers/%2B15551234567" -H "$H"
curl -s -X POST $B/auto-responses -H "$H" -H 'Content-Type: application/json' -d '{
  "title":"Opening hours","matchType":"contains","keywords":["hours"],"responseText":"We open 9-5.","active":true }'
```

`PUT` calls replace the whole configuration: send every field.

## Flows

Flows are multi-step automations started by a keyword. Typical sequence:
`POST /flows` (empty, inactive) then `PUT /flows/{id}` with the graph, then
`POST /flows/{id}:setActive {"active":true}`. `PUT` validates the whole graph
and returns `INVALID_ARGUMENT` listing the problems; activation validates
again.

The `graph` is the Flow Builder canvas JSON, stored verbatim:

```json
{
  "nodes": [
    {"id":"n1","type":"start","position":{"x":0,"y":0},"data":{"matchType":"exact","keywords":["hi"]}},
    {"id":"n2","type":"buttons","position":{"x":0,"y":120},"data":{"text":"Pick one","buttons":[{"id":"a","label":"Sales"},{"id":"b","label":"Support"}]}},
    {"id":"n3","type":"sendMessage","position":{"x":0,"y":240},"data":{"text":"Sales will call you."}}
  ],
  "edges": [
    {"id":"e1","source":"n1","target":"n2","sourceHandle":null,"targetHandle":null},
    {"id":"e2","source":"n2","target":"n3","sourceHandle":"a","targetHandle":null}
  ]
}
```

One `start` node (with keywords) is required. `sourceHandle` picks the
branch: `true`/`false` for `condition`, the button or row `id` for `buttons`
and `list`. Node types and `data` fields are listed in the proto comment on
the `Flow` message (start, sendMessage, question, input, buttons, list,
dynamicList, media, multiMedia, askMedia, askLocation, askAddress, template,
condition, setAttribute, addTag, delay, apiRequest, connectFlow,
catalogMessage, product, multiProducts, orderDetails). The safest way to
author a graph is to `GET` one built in the dashboard and copy its shapes.

## Commerce

```bash
curl -s $B/commerce/settings -H "$H"        # connected catalog + connectable catalogs
curl -s -X POST $B/commerce/catalogs:connect -H "$H" -H 'Content-Type: application/json' -d '{"catalogId":"123","catalogName":"Shop"}'
curl -s -X POST $B/commerce/product-batches -H "$H" -H 'Content-Type: application/json' -d '{
  "name":"Spring","items":[{"retailerId":"sku-1","name":"Shirt","price":"19.99","currency":"USD","imageUrl":"https://example.com/a.jpg"}] }'
curl -s -X POST $B/commerce/product-batches/b1:setLive -H "$H" -H 'Content-Type: application/json' -d '{"live":true}'
```

Meta credentials are never returned by any call.

## Deliberately not in the API

* Setup of the account through the browser (embedded signup): use
  `POST /numbers:connect`.
* `SendTestMessage`, `SendMetaTestMessage`: development helpers; use
  `POST /messages` (real send) instead. Meta quality rating and messaging
  tier are already on `GET /numbers`.

