# API documentation

## Introduction

Airbox is a unified messaging API: one REST API to send and receive WhatsApp and Instagram messages from any system, built on Meta's official platform.

### How it works

- **Sign up**: your first workspace gets a test key, shown once.
- **Install the SDK** for your stack, or call the REST API directly.
- **Connect a number.** Your client opens a link and signs in with Meta, and their WhatsApp number or Instagram account joins their workspace. See [Connecting a client](https://airbox.kz/en/docs/connecting).
- **Send and receive.** `POST /v1/messages` sends, and every reply reaches your webhook as one signed `message.received` event.

### Where to next

- [Quickstart](https://airbox.kz/en/docs/quickstart): your first message in a few minutes.
- [Clients and workspaces](https://airbox.kz/en/docs/workspaces): how to run many clients from one account.
- [Channels](https://airbox.kz/en/docs/channels): what WhatsApp and Instagram allow, and how they differ.
- [Webhooks](https://airbox.kz/en/docs/webhooks): receiving replies and statuses.
- [API reference](https://airbox.kz/en/docs/api): every endpoint, field and error.

## Quickstart

### The fastest way

```prompt
Add Airbox to this project: sending and receiving WhatsApp and Instagram messages. Documentation for agents: https://airbox.kz/llms-full.txt. Take the key from AIRBOX_API_KEY, and if it is not set, ask me to sign up at https://app.airbox.kz/signup and copy the test key it shows
```

Prefer to do it yourself? Five steps.

### 1. Get your key

[Sign up](https://app.airbox.kz/signup): your first workspace gets a test key, shown once after you confirm your email. Copy it then, or create another under **API keys**. Keep it in an environment variable, never in code:

```bash
export AIRBOX_API_KEY=your_key
```

### 2. Install the SDK

Add the SDK for your stack. [SDKs](https://airbox.kz/en/docs/sdks) has a runnable example for each.

```bash Node.js
npm install @airboxhq/api
```

```bash PHP
composer require airboxhq/airbox-php
```

```bash Python
pip install airboxhq
```

```bash Go
go get github.com/airboxhq/airbox-go
```

```bash .NET
dotnet add package AirboxHQ
```

```bash Rust
cargo add airboxhq
```

### 3. Send a message

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.messages.sendText({
  to: "+77011234567",
  body: "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
  channel: "whatsapp",
}, { idempotencyKey: "order-1042" });

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->messages->sendText([
    'to' => '+77011234567',
    'body' => 'Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.',
    'channel' => 'whatsapp',
], ['idempotency_key' => 'order-1042']);

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.messages.send_text(
    to="+77011234567",
    body="Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
    channel="whatsapp",
    idempotency_key="order-1042",
)

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Messages.SendText(context.Background(), airbox.SendTextParams{
		To:      "+77011234567",
		Body:    "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
		Channel: "whatsapp",
	}, airbox.WithIdempotencyKey("order-1042"))
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Messages.SendTextAsync(
    new SendTextParams
    {
        To = "+77011234567",
        Body = "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
        Channel = "whatsapp",
    },
    new RequestOptions { IdempotencyKey = "order-1042" });

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;
use airboxhq::models::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .messages()
        .send_text(SendText {
            to: "+77011234567".into(),
            body: "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.".into(),
            channel: Some("whatsapp".into()),
            ..Default::default()
        })
        .idempotency_key("order-1042")
        .await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: order-1042" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}'
```

### 4. Receive replies

Set your webhook address on your account's **Webhook** page. Each customer message arrives there as a signed `message.received` event. Check the signature and answer at once:

```javascript Node.js
// npm install express standardwebhooks
import express from "express";
import { Webhook } from "standardwebhooks";

const webhook = new Webhook(process.env.WEBHOOK_SECRET);
const app = express();

app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  let event;

  try {
    event = webhook.verify(req.body, req.headers);
  } catch {
    return res.sendStatus(400);
  }

  res.sendStatus(200);
  console.log(event.type, event.workspace.id, event.data);
});

app.listen(3000);
```

```php PHP
<?php
// composer require standard-webhooks/standard-webhooks

require __DIR__.'/vendor/autoload.php';

$webhook = new \StandardWebhooks\Webhook(getenv('WEBHOOK_SECRET'));
$body = file_get_contents('php://input');

try {
    $webhook->verify($body, [
        'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
        'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
        'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
    ]);
} catch (Exception) {
    http_response_code(400);
    exit;
}

http_response_code(200);
$event = json_decode($body, true);
```

```python Python
# pip install flask standardwebhooks
import os

from flask import Flask, request
from standardwebhooks.webhooks import Webhook

app = Flask(__name__)
webhook = Webhook(os.environ["WEBHOOK_SECRET"])


@app.post("/webhooks")
def receive():
    try:
        webhook.verify(request.get_data(), dict(request.headers))
    except Exception:
        return "", 400

    event = request.get_json()
    return "", 200
```

```go Go
// go get github.com/standard-webhooks/standard-webhooks/libraries/go
package main

import (
	"io"
	"net/http"
	"os"

	standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)

func main() {
	webhook, err := standardwebhooks.NewWebhook(os.Getenv("WEBHOOK_SECRET"))
	if err != nil {
		panic(err)
	}

	http.HandleFunc("POST /webhooks", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(r.Body)
		if err != nil || webhook.Verify(body, r.Header) != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		w.WriteHeader(http.StatusOK)
	})

	http.ListenAndServe(":3000", nil)
}
```

```csharp .NET
// dotnet add package StandardWebhooks.StandardWebhooks
using StandardWebhooks;

var app = WebApplication.CreateBuilder(args).Build();
var webhook = new Webhook(Environment.GetEnvironmentVariable("WEBHOOK_SECRET")!);

app.MapPost("/webhooks", async (HttpRequest request) =>
{
    var body = await new StreamReader(request.Body).ReadToEndAsync();

    try
    {
        webhook.Verify(body, name => request.Headers[name!].ToString());
    }
    catch (Exception)
    {
        return Results.BadRequest();
    }

    return Results.Ok();
});

app.Run();
```

```rust Rust
// cargo add standardwebhooks axum tokio --features tokio/full
use axum::{body::Bytes, http::{HeaderMap, StatusCode}, routing::post, Router};
use standardwebhooks::Webhook;

async fn receive(headers: HeaderMap, body: Bytes) -> StatusCode {
    let secret = std::env::var("WEBHOOK_SECRET").unwrap();
    let webhook = Webhook::new(&secret).unwrap();

    match webhook.verify(&body, &headers) {
        Ok(()) => StatusCode::OK,
        Err(_) => StatusCode::BAD_REQUEST,
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/webhooks", post(receive));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

Then answer the customer with `POST /v1/messages`, `to` taken from `data.from`. See [Webhooks](https://airbox.kz/en/docs/webhooks).

### 5. Build before you connect

Until your client connects a number, your messages go to a simulator, so the whole integration can be built and tested first. See [Test mode](https://airbox.kz/en/docs/test-mode).

## Key concepts

The words these docs use, and what each one means here.

### Workspace

One business and everything it has: its channels, contacts, messages and API keys. As an integrator you run one workspace for each client. Its Workspace ID, on its Settings page, is what every webhook event names it by. See [Clients and workspaces](https://airbox.kz/en/docs/workspaces).

### API key

A key works in one workspace only. A live key starts with `abx_live_` and sends real messages. A test key starts with `abx_test_` and sends to the simulator. See [Making requests](https://airbox.kz/en/docs/api/requests).

### Channel

Where a message goes: `whatsapp` or `instagram`. A workspace has one WhatsApp number and one Instagram account at most. See [Channels](https://airbox.kz/en/docs/channels).

### Contact

A customer the workspace talks to. Each one has a `contact_id`, so you can tie their messages together in your system.

### Message

An incoming message is one a customer wrote. It arrives as the `message.received` event. A message of the workspace is one sent to a customer, and it moves through statuses from `queued` to `read`. See [Messages](https://airbox.kz/en/docs/api/messages).

### The 24-hour window

After a customer writes, you may answer with free text for 24 hours. Every new message from them starts the 24 hours again. Once they pass, WhatsApp takes only a template, and Instagram waits until the customer writes again.

### Template

A WhatsApp message with set wording that Meta approves before you can send it. You need one in two cases:

1. To message a customer who has never written to you.
2. To message a customer whose last message is more than 24 hours old.

A template to a number that has never written needs the customer's consent first. See [Send a template](https://airbox.kz/en/docs/api/send-template).

### Webhook

The address on your server where events arrive, signed: new messages, status changes and channel changes. One address serves all your workspaces. See [Webhooks](https://airbox.kz/en/docs/webhooks).

### Test mode

With a test key every message goes to a simulator. Nothing reaches customers or Meta, and you can write as a customer yourself. See [Test mode](https://airbox.kz/en/docs/test-mode).

## Clients and workspaces

Airbox is built for teams that connect messaging for their own clients. You keep one account, and each client gets a workspace of its own.

### How it fits together

- **Your account** is where you sign in, pay and set the webhook address.
- **A workspace** holds one client's channels, contacts and messages. Only you sign in to it. Your client never does.
- **An API key** belongs to one workspace and works only there.
- **One webhook address** receives the events of every workspace you run. Each event names its workspace.

### Adding a client

1. Open **Workspaces** and create a **New workspace** named after the client.
2. Under the workspace's **API keys**, create its key. Copy its **Workspace ID** from its **Settings**.
3. Send the client a link to connect their own number. See [Connecting a client](https://airbox.kz/en/docs/connecting).

### Keys and events in your system

Keep each client's key and Workspace ID with the client's record in your system, the key encrypted and never in code. To send for a client, use that client's key.

Every event carries `workspace`: its `id`, which is the Workspace ID and never changes, and its current `name`. Find the client by `workspace.id`.

```json
{
    "type": "message.received",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "from": "+77011234567",
        "name": "Asel",
        "channel": "whatsapp",
        "type": "text",
        "text": {
            "body": "Hello! When will my order be ready?"
        },
        "received_at": "2026-10-09T09:30:00+00:00",
        "free_text_until": "2026-10-10T09:30:00+00:00"
    }
}
```

### Billing

Each connected WhatsApp number or Instagram account is billed on its own, monthly from the day it connects. A workspace with nothing connected costs nothing. A connection left unpaid stops sending with `payment_required`, while incoming messages still arrive. See [Pricing](https://airbox.kz/en/pricing).

## Connecting a client

Your client connects their own WhatsApp number or Instagram account. They never sign in to Airbox: they open a link, accept the terms and log in to Meta.

### Make the link

On the client workspace's **Channels** page, under **Link for the client**, press **Create a link** and send it to the client in any messenger or by email. A link works once and for 7 days. One link is open at a time, and **Create a new one** replaces it.

### What the client does

1. Opens the link. The page names the workspace and who sent the link.
2. Accepts the terms of use and data processing.
3. Presses **Connect WhatsApp** and logs in to Facebook or Meta Business Suite, with access to the company's business account.
4. In Meta's window, picks the number from the WhatsApp Business app or adds a new one. Meta confirms a new number with a code by SMS or a call.

Meta's window is Meta's own, opened by Airbox as a verified Meta Tech Provider. The client's password stays with Meta.

For Instagram, the same page has **Connect Instagram**. It needs a professional account in a Meta business portfolio.

### The number can stay on the phone

A number taken from the WhatsApp Business app keeps working there, so your client's staff can still write from the phone. Those messages reach you with `sent_by: phone`, and `whatsapp.shared_with_phone_app` in `GET /v1/channels` is `true`. Such a number sends up to 20 messages a second instead of 80.

### Know when it is ready

A new channel is `pending` while Meta finishes, then `connected`. Each change comes to your webhook as a `channel.updated` event, and `GET /v1/channels` shows the state at any time. Billing for the connection starts the day it is added.

### Before the first message

- Meta charges for WhatsApp messages itself, so the client adds a card to their WhatsApp account at Meta. Without one, sends fail with `meta_payment` and `alerts` in `GET /v1/channels` shows `payment`.
- To write first, the client needs templates Meta approved, and each customer's consent recorded. See [Send a template](https://airbox.kz/en/docs/api/send-template).

### When a client leaves

A client cuts the connection by removing our app in Meta's settings. The channel turns `disconnected` and a `channel.updated` event arrives. Disconnect the number on the **Channels** page to stop its billing.

## Going live

What to check before your first client sends real messages.

### Your integration

- Sends with a live key, read from an environment variable or a secrets store.
- Sets an `Idempotency-Key` on every send, and retries only after a network error, 429 or 5xx.
- Handles errors by `error.code`, never by the message text.
- Sends a template once the 24-hour window is closed, and records consent before the first template to a new number.
- Logs `request_id` from every failed response.

### Your webhook

- Answers 2xx at once and does the work in the background.
- Checks the signature and rejects events more than 5 minutes old.
- Drops repeats by the `webhook-id` header.
- Finds the client by `workspace.id`.
- Passes the test event from the workspace's **Webhook deliveries** page.

### Your client's channel

- Is `connected` in `GET /v1/channels`, with no `alerts`.
- Has a working card at Meta for WhatsApp, and the templates you need approved.
- Has `limits.new_customers_per_day` in `GET /v1/channels` high enough for the customers you plan to write to first.

### After launch

- Watch `channel.updated` events: a channel cut off, or an alert such as `payment`.
- Watch `quality` in `GET /v1/channels`, or on the workspace's **Channels** page: a `low` rating means customers block or report the number.
- Keep each connection paid: an unpaid one stops sending with `payment_required`.

## Sending messages

Every message is one `POST /v1/messages`: who it goes to, on which channel, and what it says.

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.messages.sendText({
  to: "+77011234567",
  body: "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
  channel: "whatsapp",
}, { idempotencyKey: "order-1042" });

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->messages->sendText([
    'to' => '+77011234567',
    'body' => 'Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.',
    'channel' => 'whatsapp',
], ['idempotency_key' => 'order-1042']);

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.messages.send_text(
    to="+77011234567",
    body="Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
    channel="whatsapp",
    idempotency_key="order-1042",
)

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Messages.SendText(context.Background(), airbox.SendTextParams{
		To:      "+77011234567",
		Body:    "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
		Channel: "whatsapp",
	}, airbox.WithIdempotencyKey("order-1042"))
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Messages.SendTextAsync(
    new SendTextParams
    {
        To = "+77011234567",
        Body = "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.",
        Channel = "whatsapp",
    },
    new RequestOptions { IdempotencyKey = "order-1042" });

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;
use airboxhq::models::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .messages()
        .send_text(SendText {
            to: "+77011234567".into(),
            body: "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm.".into(),
            channel: Some("whatsapp".into()),
            ..Default::default()
        })
        .idempotency_key("order-1042")
        .await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: order-1042" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}'
```

### Text or template

| | Free text | Template |
| --- | --- | --- |
| When | Within 24 hours of the customer's last message | Any time |
| Writing first | No | Yes, once the customer has agreed |
| Channels | WhatsApp and Instagram | WhatsApp only |
| What it says | Anything, up to 4,096 characters | What Meta approved, with your values in its placeholders |
| Cost | On WhatsApp, 1,000 a month free for each number, then Meta's rate for service messages. Free on Instagram | Meta's rate for the template's category: marketing, utility or authentication |

Meta charges WhatsApp messages to the card on the client's own WhatsApp account, at its rate for each country, and only for those delivered. Airbox adds nothing per message. See [Meta's pricing](https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing).

Once the 24 hours pass, a text gets `422 outside_window`. Send a template instead. See [Templates and consent](https://airbox.kz/en/docs/templates).

### Choosing the channel

`channel` has no default. Name `whatsapp` or `instagram`, or give `auto` to answer on the channel the customer last wrote on. With `auto`, a customer who has never written gets `422 channel_unresolved`.

`to` is the customer's number in E.164 on WhatsApp, and the `from` of their message on Instagram.

### What the response means

- `201`: the message was accepted and handed to the channel.
- `202` with status `queued`: it waits its turn within Meta's limits and goes on its own.
- `422`: it did not go. `error.code` says why, and `message_id` names the message.

### Following a message

A message moves from `queued` to `sent`, `delivered` and `read`, or ends `failed` or `refused`. Each change comes as a `message.status` event, and `GET /v1/messages/{id}` returns the message at any time. Not every channel reports delivery and reading: `rules.receipts` in `GET /v1/channels` says which do. See [Messages](https://airbox.kz/en/docs/api/messages).

### Sending twice, safely

Give every send an `Idempotency-Key`, for example your order id. When the network fails, send again with the same key and body: for 24 hours you get the first response back, and the customer gets one message. See [Making requests](https://airbox.kz/en/docs/api/requests).

## Templates and consent

A template is a WhatsApp message with set wording that Meta approves before you can send it. You need one in two cases:

1. To message a customer who has never written to you.
2. To message a customer whose last message is more than 24 hours old.

Instagram has no templates.

### Listing templates

`GET /v1/templates` returns the number's approved templates, each with its `name`, `language`, `category`, `parameters` and `body`.

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.templates.list();

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->templates->list();

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.templates.list()

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Templates.List(context.Background())
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Templates.ListAsync();

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client.templates().list().await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X GET https://crm.fintelligence.kz/api/v1/templates \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Sending one

Name the template and its language, and give a value for each placeholder in `parameters`, in their order. A template with named placeholders takes an object by name instead. Values are strings, up to 100 of them, each up to 1,024 characters.

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.templates.send("order_ready", {
  to: "+77011234567",
  language: "ru",
  parameters: [
    "Asel",
    "1042",
  ],
}, { idempotencyKey: "order-1042-reminder" });

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->templates->send('order_ready', [
    'to' => '+77011234567',
    'language' => 'ru',
    'parameters' => [
        'Asel',
        '1042',
    ],
], ['idempotency_key' => 'order-1042-reminder']);

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.templates.send(
    "order_ready",
    to="+77011234567",
    language="ru",
    parameters=[
        "Asel",
        "1042",
    ],
    idempotency_key="order-1042-reminder",
)

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Templates.Send(context.Background(), "order_ready", airbox.SendTemplateParams{
		To:         "+77011234567",
		Language:   "ru",
		Parameters: []string{"Asel", "1042"},
	}, airbox.WithIdempotencyKey("order-1042-reminder"))
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Templates.SendAsync(
    "order_ready",
    new SendTemplateParams
    {
        To = "+77011234567",
        Language = "ru",
        Parameters = new List<string> { "Asel", "1042" },
    },
    new RequestOptions { IdempotencyKey = "order-1042-reminder" });

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;
use airboxhq::models::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .templates()
        .send(
            "order_ready",
            SendTemplate {
                to: "+77011234567".into(),
                language: "ru".into(),
                parameters: Some(vec!["Asel", "1042"].into()),
                ..Default::default()
            },
        )
        .idempotency_key("order-1042-reminder")
        .await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: order-1042-reminder" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "template",
    "template": {
        "name": "order_ready",
        "language": "ru",
        "parameters": [
            "Asel",
            "1042"
        ]
    }
}'
```

A missing or empty value gets `422 template_parameters`, and a name or language Meta has not approved gets `422 template_not_found`.

### Recording consent

Consent is a WhatsApp matter, as only WhatsApp lets you write first. Before a template goes to a number that has never written to the workspace, record that the customer agreed to hear from you. Without it the response is `422 no_consent`.

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.contacts.grantConsent("+77011234567");

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->contacts->grantConsent('+77011234567');

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.contacts.grant_consent("+77011234567")

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Contacts.GrantConsent(context.Background(), "+77011234567")
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Contacts.GrantConsentAsync("+77011234567");

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client.contacts().grant_consent("+77011234567").await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/contacts/%2B77011234567/consent \
  -H "Authorization: Bearer YOUR_API_KEY"
```

When the customer changes their mind, `DELETE /v1/contacts/{phone}/consent` withdraws it. A customer who asked not to be written to gets `422 opted_out` when you write first.

### New customers a day

Meta limits how many new customers a number writes to first in a rolling 24 hours, from 50 to 100,000 by the number's tier. `limits.new_customers_per_day` in `GET /v1/channels` shows the number now, and a send beyond it gets `422 messaging_limit`. Answers to customers who wrote in the last 24 hours do not count.

## Files and media

Photos, videos, voice notes and audio files go by a link, or on WhatsApp as a file uploaded first.

### By link

Give an https link in `url`. It has to open without signing in. Instagram takes files only this way.

```javascript Node.js
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.messages.sendImage({
  to: "+77011234567",
  url: "https://shop.example.kz/orders/1042.jpg",
  caption: "Your order #1042 is packed",
  channel: "whatsapp",
}, { idempotencyKey: "order-1042-photo" });

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->messages->sendImage([
    'to' => '+77011234567',
    'url' => 'https://shop.example.kz/orders/1042.jpg',
    'caption' => 'Your order #1042 is packed',
    'channel' => 'whatsapp',
], ['idempotency_key' => 'order-1042-photo']);

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.messages.send_image(
    to="+77011234567",
    url="https://shop.example.kz/orders/1042.jpg",
    caption="Your order #1042 is packed",
    channel="whatsapp",
    idempotency_key="order-1042-photo",
)

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Messages.SendImage(context.Background(), airbox.SendImageParams{
		To:      "+77011234567",
		URL:     "https://shop.example.kz/orders/1042.jpg",
		Caption: "Your order #1042 is packed",
		Channel: "whatsapp",
	}, airbox.WithIdempotencyKey("order-1042-photo"))
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Messages.SendImageAsync(
    new SendImageParams
    {
        To = "+77011234567",
        Url = "https://shop.example.kz/orders/1042.jpg",
        Caption = "Your order #1042 is packed",
        Channel = "whatsapp",
    },
    new RequestOptions { IdempotencyKey = "order-1042-photo" });

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;
use airboxhq::models::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .messages()
        .send_image(SendImage {
            to: "+77011234567".into(),
            url: Some("https://shop.example.kz/orders/1042.jpg".into()),
            caption: Some("Your order #1042 is packed".into()),
            channel: Some("whatsapp".into()),
            ..Default::default()
        })
        .idempotency_key("order-1042-photo")
        .await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: order-1042-photo" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "image",
    "image": {
        "url": "https://shop.example.kz/orders/1042.jpg",
        "caption": "Your order #1042 is packed"
    }
}'
```

### By upload

On WhatsApp, upload the file with `POST /v1/media`, then send its `id` as `media_id`. An uploaded file can be sent for 30 days.

```javascript Node.js
import { readFile } from "node:fs/promises";
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.media.upload(await readFile("voice.ogg"), {
  filename: "voice.ogg",
  contentType: "audio/ogg",
});

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

console.log(data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->media->upload('voice.ogg');

print_r($data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.media.upload("voice.ogg")

print(data)
```

```go Go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	file, err := os.Open("voice.ogg")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	data, err := client.Media.Upload(context.Background(), file, airbox.UploadParams{
		Filename:    "voice.ogg",
		ContentType: "audio/ogg",
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(data)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

await using var file = File.OpenRead("voice.ogg");

var data = await client.Media.UploadAsync(
    file,
    new UploadParams
    {
        FileName = "voice.ogg",
        ContentType = "audio/ogg",
    });

Console.WriteLine(data);
```

```rust Rust
use airboxhq::Airbox;
use airboxhq::models::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .media()
        .upload(
            std::fs::read("voice.ogg")?,
            Upload {
                filename: Some("voice.ogg".into()),
                content_type: Some("audio/ogg".into()),
                ..Default::default()
            },
        )
        .await?;

    println!("{data:#?}");
    Ok(())
}
```

```bash cURL
curl -X POST https://crm.fintelligence.kz/api/v1/media \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@voice.ogg" \
  -F "channel=whatsapp"
```

### Formats and sizes

| Type | Formats | Up to |
| --- | --- | --- |
| `image` | JPEG, PNG | 5 MB |
| `video` | MP4, 3GP (H.264 and AAC) | 16 MB |
| `audio` | AAC, AMR, MP3, M4A, OGG (Opus, mono) | 16 MB |
| `voice` | OGG with the Opus codec, a link ending in `.ogg` or `.opus` | 16 MB |

A photo or a video takes a `caption` of up to 1,024 characters. On Instagram the caption goes as a message of its own.

### Files customers send

A file in an incoming message comes with its `media_id`, `mime_type` and `expires_at`. Download it with `GET /v1/media/{id}` before then: the channel keeps it 7 days, and we keep no copy.

```javascript Node.js
import { writeFile } from "node:fs/promises";
import { Airbox } from "@airboxhq/api";

const client = new Airbox(process.env.AIRBOX_API_KEY);

const { data, error } = await client.media.download("med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f");

if (error) {
  throw new Error(`${error.code}: ${error.message} (${error.requestId})`);
}

await writeFile("voice.ogg", data);
```

```php PHP
<?php

require __DIR__.'/vendor/autoload.php';

$client = new Airbox\Client(getenv('AIRBOX_API_KEY'));

$data = $client->media->download('med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f');

file_put_contents('voice.ogg', $data);
```

```python Python
import os

from airboxhq import Airbox

client = Airbox(api_key=os.environ["AIRBOX_API_KEY"])

data = client.media.download("med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f")

with open("voice.ogg", "wb") as file:
    file.write(data)
```

```go Go
package main

import (
	"context"
	"os"

	"github.com/airboxhq/airbox-go"
)

func main() {
	client := airbox.NewClient(os.Getenv("AIRBOX_API_KEY"))

	data, err := client.Media.Download(context.Background(), "med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f")
	if err != nil {
		panic(err)
	}

	os.WriteFile("voice.ogg", data, 0o644)
}
```

```csharp .NET
using Airbox;

var client = new AirboxClient(Environment.GetEnvironmentVariable("AIRBOX_API_KEY"));

var data = await client.Media.DownloadAsync("med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f");

await File.WriteAllBytesAsync("voice.ogg", data);
```

```rust Rust
use airboxhq::Airbox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Airbox::new(std::env::var("AIRBOX_API_KEY")?);

    let data = client
        .media()
        .download("med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f")
        .await?;

    std::fs::write("voice.ogg", &data)?;
    Ok(())
}
```

```bash cURL
curl -X GET https://crm.fintelligence.kz/api/v1/media/med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f \
  -H "Authorization: Bearer YOUR_API_KEY" \
  --fail-with-body -o voice.ogg
```

## Errors and retries

Every error has the same shape, and its `code` never changes. Handle errors by `code`, never by the message text.

```json
{
    "error": {
        "code": "outside_window",
        "message": "The customer has not written to you in the last 24 hours, and WhatsApp lets free text through only as a reply. Send an approved template.",
        "message_id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
        "request_id": "req_01k75q3x8f2m9c4v6b7n1d0e5a"
    }
}
```

### What to do

| Codes | Situation | What to do |
| --- | --- | --- |
| `invalid_request`, `invalid_phone`, `template_parameters` | The request is wrong | Fix the request. Sending it again gets the same response. |
| `outside_window` | The 24 hours passed | Send a template. |
| `no_consent` | The customer has not agreed | Record consent, then send. |
| `rate_limited` | Too many requests | Wait as many seconds as `Retry-After` says, then retry. |
| `server_error`, a timeout | Our side or the network failed | Retry with the same `Idempotency-Key`. |
| `channel_unavailable`, `meta_payment`, `payment_required` | The channel cannot send | Ask the client to reconnect or add a card at Meta, or pay the invoice. |

### Retrying safely

Retry only after a network error, `429` or `5xx`, with the same `Idempotency-Key` and body, and wait longer each time. A `4xx` response does not change on its own.

### Errors after the response

A message can also fail once it was accepted: the channel did not deliver it, or Meta refused it. It turns `failed` or `refused`, a `message.status` or `message.refused` event arrives, and `error.code` says why. [Errors](https://airbox.kz/en/docs/api/errors) lists every code.

### Asking us

Every response carries `X-Request-Id`, and an error body repeats it as `request_id`. Log it. The workspace's **Requests** page lists its calls of the last 30 days, each with its id. When something looks wrong, send it to us with your question.

## SDKs

Official SDKs for every stack on the site, each with a runnable example project. They cover the whole API, from messages and templates to files, consent, channels and test mode, and return the API's own error codes.

### Install

```bash Node.js
npm install @airboxhq/api
```

```bash PHP
composer require airboxhq/airbox-php
```

```bash Python
pip install airboxhq
```

```bash Go
go get github.com/airboxhq/airbox-go
```

```bash .NET
dotnet add package AirboxHQ
```

```bash Rust
cargo add airboxhq
```

### Packages and examples

| Language | Package | Example project |
| --- | --- | --- |
| Node.js | [npm](https://www.npmjs.com/package/@airboxhq/api) | [airbox-node-example](https://github.com/airboxhq/airbox-node-example) |
| PHP | [Packagist](https://packagist.org/packages/airboxhq/airbox-php) | [airbox-php-example](https://github.com/airboxhq/airbox-php-example) |
| Python | [PyPI](https://pypi.org/project/airboxhq/) | [airbox-python-example](https://github.com/airboxhq/airbox-python-example) |
| Go | [GitHub](https://github.com/airboxhq/airbox-go) | [airbox-go-example](https://github.com/airboxhq/airbox-go-example) |
| .NET | [NuGet](https://www.nuget.org/packages/AirboxHQ) | [airbox-dotnet-example](https://github.com/airboxhq/airbox-dotnet-example) |
| Rust | [crates.io](https://crates.io/crates/airboxhq) | [airbox-rust-example](https://github.com/airboxhq/airbox-rust-example) |

### Files for agents

- [llms.txt](https://airbox.kz/llms.txt): Index for agents
- [llms-full.txt](https://airbox.kz/llms-full.txt): The whole API in one file
- [docs.md](https://airbox.kz/en/docs.md): The docs in Markdown
- [openapi.json](https://airbox.kz/openapi.json): The OpenAPI spec

## Basics

- Base URL: https://crm.fintelligence.kz/api
- Every request carries the header `Authorization: Bearer <key>`. The examples have `YOUR_API_KEY` where the key goes. Read the key from an environment variable, for example `AIRBOX_API_KEY`, and never write it into code or commit it.
- A live key starts with `abx_live_` and sends real messages. A test key starts with `abx_test_` and works on the simulator: nothing it does reaches customers or Meta.
- A key belongs to one workspace and works only there. If you run several workspaces, create a key in each, under its API keys.
- Request and response bodies are JSON (`Content-Type: application/json`), times are ISO 8601, numbers are E.164, for example `+77011234567`.
- Error codes and messages are always in English, whatever the `Accept-Language` header says. Check the code, not the text: the code never changes.
- No more than 300 requests a minute per key. Every response to a request with a valid key where the API is open carries `X-RateLimit-Limit` and `X-RateLimit-Remaining`: the limit and how many requests are left this minute. Beyond the limit the response is 429 `rate_limited`, which also carries `Retry-After` and `X-RateLimit-Reset`: how many seconds to wait and when the limit renews, in Unix time.
- Every response carries the `X-Request-Id` header with the request’s id, and an error body repeats it as `request_id`. Log it: with it we can find the request if something goes wrong. You may send your own id in the same header: Latin letters, digits and `_ . : -`, up to 128 characters.
- Add an `Idempotency-Key` header to every `POST /v1/messages`, its own for each message, for example from the order id. A retry with the same key and body returns the first response with the header `Idempotent-Replayed: true` and does not send the message again. A key is remembered for 24 hours, and may be up to 255 characters, not blank.
- Retry only after a network error, 429 or 5xx, with the same `Idempotency-Key` and a pause. Retrying after a 4xx response is pointless, so fix the request first.
- `GET /v1/templates` and `GET /v1/channels` return every item at once in `data`. Contacts and a contact's messages come a page at a time, newest first: up to `limit` items in `data`, 20 by default and 100 at most, and while `has_more` is `true`, the next page comes with the last item's `id` in `after`.

## Channels

- Every `POST /v1/messages` names its channel in `channel`, and there is no default. Without it the response is 422 `invalid_request` with `param: channel`.
- `whatsapp` sends from the workspace's WhatsApp number. `auto` sends on the channel the customer last wrote on, among the workspace's connected ones. If they have not written on any, the response is 422 `channel_unresolved`, and then name the channel yourself.
- `instagram` answers from the workspace's Instagram account. A channel the workspace has not connected gets 422 `channel_unavailable`.
- Templates exist only on WhatsApp. A template on another channel gets 422 `template_unsupported`.
- Every message in responses and webhooks says its channel in `channel`: `whatsapp` or `instagram`, and `simulator` in test mode.
- `GET /v1/channels` lists the workspace's channels, each with the same fields, described below. Check it when your system starts, not before every send.

- `whatsapp`, WhatsApp. Customer address: an E.164 number. Writing first: yes, with a template, and a new number needs the customer's consent. Free text: 24 h after the customer writes. Templates: yes, approved by Meta. Delivery and reading: delivery, reading.
- `instagram`, Instagram. Customer address: the `from` of the customer's message. Writing first: no, only replies. Free text: 24 h after the customer writes. Templates: no. Delivery and reading: reading.

A channel in `GET /v1/channels` has the same fields whatever the channel. When a channel lacks something or it is not known yet, the field still comes, as `null`, `[]` or `false`. The values are our own, not Meta's codes.

- `channel`: `whatsapp` or `instagram`. Put the same value in `channel` when sending.
- `status`: `connected` when the channel is connected, `pending` when the number is connected but not ready at Meta yet, `disconnected` when Meta cut it off, and `not_connected` when the workspace does not have the channel.
- `sends_to`: where a send naming this channel goes with this key. With a live key it is the channel itself, with a test key `simulator`, and `null` means the send would be refused.
- `account`: who the workspace writes as on this channel. `null` when nothing is connected.
  - `address`: the WhatsApp number, for example `+7 727 355 00 00`, or the Instagram username, for example `@takhet.kz`.
  - `name`: the name customers see beside the number. `null` when there is none yet.
  - `url`: a link that opens a chat with the workspace, for a button on a site or a QR code. On WhatsApp it is `https://wa.me/` and the number's digits, and on Instagram `https://instagram.com/` and the username.
- `quality`: Meta's rating of the number's messages, `high`, `medium` or `low`. A low rating means customers often block or report the number. `null` when there is no rating yet or the channel is not rated.
- `limits`: the channel's limits, in numbers.
  - `new_customers_per_day`: how many new customers the number may write to first in a moving 24 hours, for example 250 or 2000, by the number's tier at Meta. Answering customers who wrote to you in the last 24 hours does not count against it. `null` when there is no limit or it is not known yet.
  - `messages_per_second`: how many messages a second at most leave the number. Usually 80, or 20 for a number that stays in the WhatsApp Business app too. The rest wait their turn. `null` on Instagram and when the channel is not connected.
- `rules`: the channel's rules and what it can do.
  - `free_text_window_hours`: for how many hours after a customer writes you may send them free text, 24 on WhatsApp. `null` when the channel has no such window.
  - `templates`: whether the channel takes approved templates. `true` on WhatsApp only.
  - `receipts`: what the channel reports after a send: `delivered` for delivery, `read` for reading. WhatsApp reports both, Instagram only `read`. A status missing here never comes for a message on this channel.
- `alerts`: warnings about the channel, as a list of codes. Empty when all is well. The codes never change:
  - `payment`: Meta is not sending the number's messages because the WhatsApp account has no working card. Until a card is added at Meta, sends get the error `meta_payment`.
  - `restricted`: Meta restricted the account for a while, for example from starting conversations. The workspace's Channels page has the details and the date.
  - `policy_violation`: Meta reported a breach of its policies. Repeated breaches lead to restrictions.
  - `disable_scheduled`: Meta is about to disable the account. You can appeal in Meta Business Support Home.
- `whatsapp`: only what WhatsApp has. Each channel has such a key of its own, named after it, and only WhatsApp has one now. `null` when the channel is not connected.
  - `shared_with_phone_app`: `true` when the number stays in the WhatsApp Business app on the phone too. Staff write from the phone as well, and messages leave more slowly.

## WhatsApp

### Connecting

- The number connects on the workspace's Channels page by signing in to Meta, or the client connects it with a connect link.
- The number may stay in the WhatsApp Business app on the phone too. Then people write from the phone as well, such messages come with `sent_by: phone`, and `whatsapp.shared_with_phone_app` in `GET /v1/channels` is `true`.

### Receiving a message

- When a customer writes, the `message.received` event comes to the webhook address.
- `from` is the customer's number in E.164.
- A file in the message downloads with `GET /v1/media/{id}`, the id being `media.id` from the event.

```json
{
    "type": "message.received",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "from": "+77011234567",
        "name": "Asel",
        "channel": "whatsapp",
        "type": "text",
        "text": {
            "body": "Hello! When will my order be ready?"
        },
        "received_at": "2026-10-09T09:30:00+00:00",
        "free_text_until": "2026-10-10T09:30:00+00:00"
    }
}
```

### Replying

- You may reply within 24 h of the customer's last message, later the reply gets `outside_window`.
- Put the customer's number in E.164 in `to`.
- Photos, videos and audio by a `url` link or uploaded with `POST /v1/media`. A voice note is OGG with the Opus codec, its link ending in `.ogg` or `.opus`.

### Writing first

- Free text can be sent only if the customer wrote to you in the last 24 hours. Otherwise the response is 422 `outside_window`, and you need a template.
- A template can be sent at any time, but only one Meta approved. `GET /v1/templates` lists them.
- A template to a number that has not written needs the customer's consent: first `POST /v1/contacts/{phone}/consent`. Without consent the response is 422 `no_consent`.
- You may not write first to a customer who asked not to be written to (`opted_out`).

### Statuses

- Statuses come as the `message.status` event: `sent` → `delivered` → `read`.

### Limits

- Messages leave the number no faster than Meta allows: up to 80 a second, or 20 for a number that stays in the WhatsApp Business app too. The rest wait their turn and go in order. Then the response is 202 with status `queued`, and `message.status` webhooks and `GET /v1/messages/{id}` tell the rest. When Meta asks to send less often, we try again after a pause ourselves.
- A number may write first to as many new customers as its Meta tier allows: from 50 to 100,000 customers in a rolling 24 hours. `limits.new_customers_per_day` in `GET /v1/channels` shows how many now, and a send beyond it gets `messaging_limit`. Replies to those who wrote to you in the last 24 hours may go beyond the limit.

### Meta billing

- Meta charges for messages itself, to the card added to the WhatsApp account at Meta. We take no money for messages.
- Without a working card Meta sends nothing: sends get `meta_payment`, and `payment` appears in `alerts` in `GET /v1/channels`.

## Instagram

### Connecting

- The account connects on the workspace's Channels page by signing in to Meta, or the client connects it with a connect link.

### Receiving a message

- When a customer writes, the `message.received` event comes to the webhook address.
- `from` is the customer's id on Instagram. There is no number, so tie messages together by `contact_id`.
- A file in the message downloads with `GET /v1/media/{id}`, the id being `media.id` from the event.

```json
{
    "type": "message.received",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "from": "1234567890123456",
        "name": "Asel",
        "channel": "instagram",
        "type": "text",
        "text": {
            "body": "Hello! When will my order be ready?"
        },
        "received_at": "2026-10-09T09:30:00+00:00",
        "free_text_until": "2026-10-10T09:30:00+00:00"
    }
}
```

### Replying

- You may reply within 24 h of the customer's last message, later the reply gets `outside_window`.
- Put the `from` of the customer's message in `to`.
- Photos, videos and audio by a `url` link only. A caption goes as its own message.

Send text, `POST /v1/messages`:

```json
{
    "to": "1234567890123456",
    "channel": "instagram",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}
```

Send a photo, `POST /v1/messages`:

```json
{
    "to": "1234567890123456",
    "channel": "instagram",
    "type": "image",
    "image": {
        "url": "https://shop.example.kz/orders/1042.jpg",
        "caption": "Your order #1042 is packed"
    }
}
```

### Writing first

- Not possible: on Instagram you can only reply to someone who wrote.

### Statuses

- Statuses come as the `message.status` event: `sent` → `read`.

## Endpoints

### Send text

`POST https://crm.fintelligence.kz/api/v1/messages`

Free text to a customer who wrote to you in the last 24 hours, on the channel named in `channel`: `whatsapp`, `instagram`, or `auto` for the one the customer last wrote on. `to` is the customer's number on WhatsApp, or the `from` of their message on Instagram. The text is up to 4,096 characters. A 201 response means the message was accepted and handed to the channel, and 202 with status `queued` that it waits its turn within Meta's limits and goes on its own. If it did not go, the response is 422 with the reason in `error.code` and the `message_id`.

Headers: `Idempotency-Key: order-1042`

Request:

```json
{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}
```

Response 201:

```json
{
    "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
    "to": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    },
    "status": "sent",
    "error": null,
    "sent_by": "api",
    "created_at": "2026-10-09T09:30:00+00:00",
    "sent_at": "2026-10-09T09:30:00+00:00",
    "delivered_at": null,
    "read_at": null
}
```

### Send a template

`POST https://crm.fintelligence.kz/api/v1/messages`

A template Meta approved: the way to start a conversation when the customer has not written for 24 hours. The values in `parameters` go in the order of the template's placeholders, and for a template with named placeholders they may be an object. The values are strings, up to 100 of them, each up to 1,024 characters. A number that has not written needs recorded consent. Templates exist only on WhatsApp, so `channel` is `whatsapp`.

Headers: `Idempotency-Key: order-1042-reminder`

Request:

```json
{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "template",
    "template": {
        "name": "order_ready",
        "language": "ru",
        "parameters": [
            "Asel",
            "1042"
        ]
    }
}
```

Response 201:

```json
{
    "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
    "to": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "type": "template",
    "template": {
        "name": "order_ready",
        "language": "ru",
        "parameters": [
            "Asel",
            "1042"
        ]
    },
    "status": "sent",
    "error": null,
    "sent_by": "api",
    "created_at": "2026-10-09T09:30:00+00:00",
    "sent_at": "2026-10-09T09:30:00+00:00",
    "delivered_at": null,
    "read_at": null
}
```

### Upload a file

`POST https://crm.fintelligence.kz/api/v1/media`

A file to send: multipart, the file in `file` and the channel it goes on in `channel`: `whatsapp`. Instagram takes no uploads, only links. The response's `id` is the `media_id` a send names, valid until `expires_at`, 30 days on WhatsApp. The channel keeps the file, and we keep only its id. WhatsApp takes a photo as JPEG or PNG up to 5 MB, a video as MP4 or 3GP (H.264 and AAC) up to 16 MB, and audio as AAC, AMR, MP3, M4A or OGG (Opus, mono) up to 16 MB. With a test key the file is checked and stays on the simulator.

Request (multipart/form-data):

```text
file=@voice.ogg
channel=whatsapp
```

Response 201:

```json
{
    "id": "med_0199c5e2-5c18-7a3f-9d2e-1b0c4a6e8f72",
    "channel": "whatsapp",
    "mime_type": "audio/ogg",
    "size": 14695,
    "expires_at": "2026-11-08T09:30:00+00:00"
}
```

### Send a voice note

`POST https://crm.fintelligence.kz/api/v1/messages`

A voice note to a customer who wrote to you in the last 24 hours, like free text: `type` is `voice`, and `voice` has an uploaded file's `media_id` or a public https `url` to an `.ogg` or `.opus` file the channel fetches itself, one of the two. On Instagram only `url`. A voice note is OGG with the Opus codec, mono: the customer's phone plays it at once and shows it with a microphone. Send any other audio with `type` `audio` and the same fields under `audio`.

Headers: `Idempotency-Key: order-1042-voice`

Request:

```json
{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "voice",
    "voice": {
        "media_id": "med_0199c5e2-5c18-7a3f-9d2e-1b0c4a6e8f72"
    }
}
```

Response 201:

```json
{
    "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
    "to": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "type": "voice",
    "voice": {
        "media_id": "med_0199c5e2-5c18-7a3f-9d2e-1b0c4a6e8f72"
    },
    "status": "sent",
    "error": null,
    "sent_by": "api",
    "created_at": "2026-10-09T09:30:00+00:00",
    "sent_at": "2026-10-09T09:30:00+00:00",
    "delivered_at": null,
    "read_at": null
}
```

### Send a photo

`POST https://crm.fintelligence.kz/api/v1/messages`

A photo or a video to a customer who wrote to you in the last 24 hours: `type` is `image` or `video`, and the field of the same name has an uploaded file's `media_id` or a public https `url`, and an optional `caption` of up to 1,024 characters. On Instagram only `url`, and the caption goes as its own message. A photo is JPEG or PNG up to 5 MB, a video MP4 or 3GP with H.264 and AAC up to 16 MB. On Android a video in H.264 High profile with B-frames may not open, so Main without B-frames or Baseline is safer.

Headers: `Idempotency-Key: order-1042-photo`

Request:

```json
{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "image",
    "image": {
        "url": "https://shop.example.kz/orders/1042.jpg",
        "caption": "Your order #1042 is packed"
    }
}
```

Response 201:

```json
{
    "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
    "to": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "type": "image",
    "image": {
        "url": "https://shop.example.kz/orders/1042.jpg",
        "caption": "Your order #1042 is packed"
    },
    "status": "sent",
    "error": null,
    "sent_by": "api",
    "created_at": "2026-10-09T09:30:00+00:00",
    "sent_at": "2026-10-09T09:30:00+00:00",
    "delivered_at": null,
    "read_at": null
}
```

### Retrieve a message

`GET https://crm.fintelligence.kz/api/v1/messages/{id}`

A message of the workspace by id: its status, and the reason's code if it did not go.

Response 200:

```json
{
    "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
    "to": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    },
    "status": "delivered",
    "error": null,
    "sent_by": "api",
    "created_at": "2026-10-09T09:30:00+00:00",
    "sent_at": "2026-10-09T09:30:00+00:00",
    "delivered_at": "2026-10-09T09:30:02+00:00",
    "read_at": null
}
```

### Download a file

`GET https://crm.fintelligence.kz/api/v1/media/{id}`

A file a customer sent, by the `media_id` from `message.received`. The response is the file itself, its type in `Content-Type`. We read the file from the channel while you download it and keep no copy, so the channel decides how long it lasts: until `expires_at`, 7 days on WhatsApp, and after that the response is 410 `media_expired`. With a test key it is a sample file.

Response 200: the file itself, with these headers:

```text
Content-Type: audio/ogg
Content-Length: 14695
Content-Disposition: attachment; filename="med_0199c5e2-6a2a-7b41-8e0d-2f1c3a4b5d6f.ogg"
Cache-Control: no-store
```

### List templates

`GET https://crm.fintelligence.kz/api/v1/templates`

The number's approved templates: name, language, category and placeholders in order.

Response 200:

```json
{
    "data": [
        {
            "name": "order_ready",
            "language": "ru",
            "category": "utility",
            "parameters": [
                "1",
                "2"
            ],
            "body": "Hello, {{1}}! Your order #{{2}} is ready."
        }
    ]
}
```

### List contacts

`GET https://crm.fintelligence.kz/api/v1/contacts`

The customers you have dealt with, newest first: those who wrote, were written to or gave consent, on the connected channels with a live key and on the simulator with a test key. With `phone`, only the contact with that number, to find their `id` and whether you may write to them. A page has up to `limit` contacts, and while `has_more` is `true`, the next page comes with the last contact's `id` in `after`.

Response 200:

```json
{
    "data": [
        {
            "id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
            "name": "Asel",
            "phone": "+77011234567",
            "instagram_id": null,
            "channel": "whatsapp",
            "free_text_until": "2026-10-10T09:28:00+00:00",
            "consent": true,
            "opted_out": false,
            "last_message_at": "2026-10-09T09:30:00+00:00",
            "created_at": "2026-09-14T11:05:00+00:00"
        }
    ],
    "has_more": false
}
```

### Retrieve a contact

`GET https://crm.fintelligence.kz/api/v1/contacts/{id}`

A contact by `id`: how to reach them, the channel they last wrote on and until when free text may answer them there, whether they agreed to templates and whether they asked not to be written to.

Response 200:

```json
{
    "id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "name": "Asel",
    "phone": "+77011234567",
    "instagram_id": null,
    "channel": "whatsapp",
    "free_text_until": "2026-10-10T09:28:00+00:00",
    "consent": true,
    "opted_out": false,
    "last_message_at": "2026-10-09T09:30:00+00:00",
    "created_at": "2026-09-14T11:05:00+00:00"
}
```

### List messages

`GET https://crm.fintelligence.kz/api/v1/contacts/{id}/messages`

The conversation with a contact, newest first: what they wrote, as `message.received` brings it, and what went to them, as `GET /v1/messages/{id}` shows it, each with its `direction`, `inbound` or `outbound`. A test key sees only the simulator's messages, a live key all the others. A page has up to `limit` messages, and while `has_more` is `true`, the next page comes with the last message's `id` in `after`.

Response 200:

```json
{
    "data": [
        {
            "direction": "outbound",
            "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
            "to": "+77011234567",
            "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
            "channel": "whatsapp",
            "type": "text",
            "text": {
                "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
            },
            "status": "read",
            "error": null,
            "sent_by": "api",
            "created_at": "2026-10-09T09:30:00+00:00",
            "sent_at": "2026-10-09T09:30:00+00:00",
            "delivered_at": "2026-10-09T09:30:02+00:00",
            "read_at": "2026-10-09T09:31:15+00:00"
        },
        {
            "direction": "inbound",
            "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
            "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
            "from": "+77011234567",
            "name": "Asel",
            "channel": "whatsapp",
            "type": "text",
            "text": {
                "body": "Hello! When will my order be ready?"
            },
            "received_at": "2026-10-09T09:28:00+00:00",
            "free_text_until": "2026-10-10T09:28:00+00:00"
        }
    ],
    "has_more": false
}
```

### Record consent

`POST https://crm.fintelligence.kz/api/v1/contacts/{phone}/consent`

The customer agreed to receive WhatsApp messages, and a template to their number passes the check. Record consent only when the customer really gave it.

Response 201:

```json
{
    "phone": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "granted": true,
    "recorded_at": "2026-10-09T09:30:00+00:00"
}
```

### Withdraw consent

`DELETE https://crm.fintelligence.kz/api/v1/contacts/{phone}/consent`

The customer no longer wants messages, and templates to their number fail the check again.

Response 200:

```json
{
    "phone": "+77011234567",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "channel": "whatsapp",
    "granted": false,
    "recorded_at": "2026-10-09T09:30:00+00:00"
}
```

### Write as a customer

`POST https://crm.fintelligence.kz/api/v1/test/inbound`

Test keys only. A made-up customer writes on the simulator: the `message.received` webhook arrives, and until its `free_text_until` you can answer this number with text. With `type` `voice`, `audio`, `image` or `video` instead of `text`, the customer sends a sample file, a photo or a video with the caption from `caption`, which `GET /v1/media/{id}` downloads.

Request:

```json
{
    "from": "+77011234567",
    "text": {
        "body": "Hello! When will my order be ready?"
    },
    "name": "Asel"
}
```

Response 201:

```json
{
    "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
    "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
    "from": "+77011234567",
    "name": "Asel",
    "channel": "simulator",
    "type": "text",
    "text": {
        "body": "Hello! When will my order be ready?"
    },
    "received_at": "2026-10-09T09:30:00+00:00",
    "free_text_until": "2026-10-10T09:30:00+00:00"
}
```

### List channels

`GET https://crm.fintelligence.kz/api/v1/channels`

What the workspace has connected. Every channel has the same fields: its status (`connected`, `pending`, `disconnected` or `not_connected`), where a send naming it goes with this key, the account with its address, name and chat link, quality, limits in numbers, the channel's rules, alerts, and whether the number is shared with the WhatsApp Business app. What a channel lacks or what is not known yet comes as `null`, an empty list or `false`.

Response 200:

```json
{
    "data": [
        {
            "channel": "whatsapp",
            "status": "connected",
            "sends_to": "whatsapp",
            "account": {
                "address": "+7 727 355 00 00",
                "name": "Zerno Coffee",
                "url": "https://wa.me/77273550000"
            },
            "quality": "high",
            "limits": {
                "new_customers_per_day": 2000,
                "messages_per_second": 80
            },
            "rules": {
                "free_text_window_hours": 24,
                "templates": true,
                "receipts": [
                    "delivered",
                    "read"
                ]
            },
            "alerts": [],
            "whatsapp": {
                "shared_with_phone_app": false
            }
        },
        {
            "channel": "instagram",
            "status": "not_connected",
            "sends_to": null,
            "account": null,
            "quality": null,
            "limits": {
                "new_customers_per_day": null,
                "messages_per_second": null
            },
            "rules": {
                "free_text_window_hours": 24,
                "templates": false,
                "receipts": [
                    "read"
                ]
            },
            "alerts": [],
            "instagram": null
        }
    ]
}
```

## Code examples

Sending a text with cURL and HTTPie. In any language it is the same request, and the other endpoints are called the same way. The code reads the key from the `AIRBOX_API_KEY` environment variable.

```bash
curl -X POST https://crm.fintelligence.kz/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: order-1042" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}'
```

```bash
http POST https://crm.fintelligence.kz/api/v1/messages \
  "Authorization:Bearer YOUR_API_KEY" \
  "Idempotency-Key:order-1042" \
  "Content-Type:application/json" \
  <<< '{
    "to": "+77011234567",
    "channel": "whatsapp",
    "type": "text",
    "text": {
        "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
    }
}'
```

## Message statuses

- `queued`: accepted, not handed to the channel yet: for example, it waits its turn within Meta's limits
- `sent`: handed to the channel
- `delivered`: delivered to the customer. Comes only if the channel reports delivery (`rules.receipts`)
- `read`: read by the customer. Comes only if the channel reports reading (`rules.receipts`)
- `failed`: the channel could not send or deliver it, the reason is in error.code
- `refused`: not sent because our rules did not let it through, the reason is in error.code

## Messages

An incoming message: `data` of `message.received` and the response to `POST /v1/test/inbound`. The same fields on every channel.

- `id`: the incoming message's id.
- `contact_id`: the customer's id in the workspace. Use it to tie their messages together in your system.
- `from`: the customer's address on the channel they wrote on: an E.164 number on WhatsApp and in test mode, and on channels without numbers, such as Instagram, the customer's address on the channel itself. Send your answer to it in `to`.
- `name`: the customer's name. `null` when there is none.
- `channel`: the channel the customer wrote on: `whatsapp` or `instagram`, and `simulator` in test mode, where nothing reaches customers or Meta.
- `type`: the message type: `text`, `voice` for a voice note, `audio` for an audio file, `image` for a photo or `video` for a video.
- `text`: the message text in `body`.
- `voice`: for a voice note: the file. `GET /v1/media/{id}` downloads it by `media_id`, `mime_type` is its type, `sha256` its hash to check it by (`null` on Instagram), and `expires_at` says until when the channel keeps it, 7 days on WhatsApp and Instagram. We keep no copy, so download it before then. An audio file, a photo and a video come the same way under `audio`, `image` and `video`, and a photo and a video also have the customer's caption in `caption`, `null` when there is none.
- `received_at`: when the message arrived.
- `free_text_until`: until when you may answer the customer with free text on this channel, by the channel's window (24 hours on WhatsApp). A new message from the customer moves it. `null` when the channel has no such window.

A message of the workspace: the responses to `POST /v1/messages` and `GET /v1/messages/{id}` and `data` of `message.status`. The same fields on every channel.

- `id`: the message's id. `GET /v1/messages/{id}` gives its status by it.
- `to`: the customer's address on the channel: an E.164 number on WhatsApp and in test mode, and on channels without numbers the customer's address on the channel itself.
- `contact_id`: the customer's id in the workspace.
- `channel`: the channel the message went to: `whatsapp` or `instagram`, and `simulator` in test mode, where nothing reaches customers or Meta.
- `type`: `text`, `template`, `voice`, `audio`, `image` or `video`.
- `text`: for a text: the text itself in `body`.
- `template`: for a template: `name`, `language` and the placeholder values in `parameters`.
- `voice`: for a voice note: the file as it was sent, an uploaded file's `media_id` or a `url`. An audio file, a photo and a video come the same way under `audio`, `image` and `video`, a photo and a video with their `caption` when they have one.
- `status`: the message's status, as described under Message statuses.
- `error`: why the message did not go: `code` and `message`. `null` when all is well.
- `sent_by`: who sent it: `api` through the API, `person` someone in the app, `phone` from an app on the phone: WhatsApp Business, where the number stays too, or Instagram.
- `created_at`: when the message was made.
- `sent_at`: when it was handed to the channel. `null` until then.
- `delivered_at`: when it was delivered. `null` until the channel reports delivery, and always on a channel that does not.
- `read_at`: when it was read. `null` until the channel reports reading, and always on a channel that does not.

A customer of the workspace: the responses to `GET /v1/contacts` and `GET /v1/contacts/{id}`. The messages of a conversation, from `GET /v1/contacts/{id}/messages`, are the two objects above, each with its `direction`: `inbound` or `outbound`.

- `id`: the contact's id in the workspace, the `contact_id` of their messages.
- `name`: the customer's name, or their address on the channel when they gave none.
- `phone`: their number in E.164. `null` for a customer known only on a channel without numbers, such as Instagram.
- `instagram_id`: the id they wrote from on Instagram, which `to` names to answer them there. `null` when they never wrote on Instagram.
- `channel`: the channel they last wrote on, where a send on `auto` goes: `whatsapp` or `instagram`, and `simulator` in test mode. `null` when they never wrote.
- `free_text_until`: until when you may answer them with free text on that channel, by its window (24 hours on WhatsApp). `null` when they never wrote or the channel has no such window.
- `consent`: whether they agreed to WhatsApp templates, recorded with `POST /v1/contacts/{phone}/consent` or in the app.
- `opted_out`: whether they asked not to be written to. A template to them is then refused with `opted_out`.
- `last_message_at`: when the last message went either way. `null` when there is none.
- `created_at`: when the contact was made.

## Errors

Every error comes in one format. `code` never changes, so rely on it, while `message` explains the reason to a person. When a message did not go, the error has `message_id`, and when a field of the request is wrong, `param`. Every error has `request_id`.

```json
{
    "error": {
        "code": "outside_window",
        "message": "The customer has not written to you in the last 24 hours, and WhatsApp lets free text through only as a reply. Send an approved template.",
        "message_id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
        "request_id": "req_01k75q3x8f2m9c4v6b7n1d0e5a"
    }
}
```

Codes and what to do about them:

- `unauthenticated` (HTTP 401): The API key is missing, wrong or revoked. Send it in the header Authorization: Bearer <key>.
- `forbidden` (HTTP 403): The workspace's plan does not allow this.
- `payment_required` (HTTP 402): The channel is unpaid, so sending on it is stopped.
- `integrator_required` (HTTP 403): For now the API works only in workspaces an integrator runs. To connect, sign up as an integrator.
- `test_key_required` (HTTP 403): This works with a test key only.
- `not_found` (HTTP 404): Nothing found. A key sees only the messages of its own workspace and its own mode, live or test.
- `method_not_allowed` (HTTP 405): This method is not supported here.
- `invalid_request` (HTTP 422): The request is not filled in correctly.
- `invalid_phone` (HTTP 422): Give the number in international format, for example +77011234567.
- `recipient_unknown` (HTTP 422): This person has not written on Instagram yet. Put the `from` of their message in `to`.
- `template_not_found` (HTTP 422): There is no approved template with this name and language. GET /v1/templates lists the approved ones.
- `template_parameters` (HTTP 422): The values do not fit the template: it needs one value, not empty, for each placeholder.
- `template_unsupported` (HTTP 422): Templates exist only on WhatsApp. On this channel send text, or send the template with channel whatsapp.
- `media_format` (HTTP 422): The file's format does not fit. A photo goes as JPEG or PNG, a video as MP4 or 3GP (H.264 and AAC), audio as AAC, AMR, MP3, M4A or OGG (Opus, mono), and a voice note only as OGG with the Opus codec, mono: an uploaded file of that format, or a link ending in .ogg or .opus.
- `media_too_large` (HTTP 422): The file is larger than the channel takes: up to 5 MB for a photo, 16 MB for audio and video.
- `media_not_found` (HTTP 404): No such file. A key sees only the files of its own workspace and its own mode, live or test. A file uploaded for one channel goes only on that channel, and GET /v1/media/{id} downloads only files customers sent.
- `media_expired` (HTTP 410): The channel no longer keeps this file: WhatsApp keeps a file a customer sent for 7 days and an uploaded one for 30. Download a customer's file sooner, and upload yours again.
- `channel_unresolved` (HTTP 422): The customer has not written to you on any connected channel, so auto cannot choose one. Name the channel, for example whatsapp.
- `idempotency_mismatch` (HTTP 422): This Idempotency-Key came with a different request before. Use a new key for a new message.
- `idempotency_in_progress` (HTTP 409): A request with this Idempotency-Key is still running. Try again in a moment.
- `rate_limited` (HTTP 429): Too many requests with this key. Try again after as many seconds as the Retry-After header says.
- `server_error` (HTTP 500): Something went wrong on our side. Try again a little later with the same Idempotency-Key.
- `channel_unavailable` (HTTP 422): The channel is unavailable: it is not connected to the workspace or was disconnected. Connect it on the workspace's Channels page.
- `outside_window` (HTTP 422): The customer has not written to you in the last 24 hours, and WhatsApp lets free text through only as a reply. Send an approved template.
- `messaging_limit` (HTTP 422): The number has used up its daily WhatsApp limit: in the last 24 hours it has already written first to as many customers as Meta allows, from 50 to 100,000 depending on the number's tier. You can write to new customers again once the first of those messages are 24 hours old, and you can answer anyone who wrote to you in the last 24 hours right now. Meta raises the limit on its own while message quality stays high.
- `no_consent` (HTTP 422): The customer has not agreed to hear from you. Once they agree, record it with POST /v1/contacts/{phone}/consent.
- `opted_out` (HTTP 422): The customer asked not to be written to, so you may not write to them first.
- `made_up_number` (HTTP 422): This is a made-up number of a demo workspace, and nothing goes to it on a real channel.
- `meta_payment` (HTTP 422): Meta is not sending messages: the WhatsApp account has no working card. Add a card at Meta and try again.
- `undeliverable` (HTTP 422): The channel could not deliver the message. For example, the number may not have WhatsApp.
- `media_rejected` (HTTP 422): The channel did not take the file: its format did not fit or its link did not open. Check the format and size, and that the link opens without signing in.
- `channel_error` (HTTP 422): The channel did not take the message. Try again later, and if it still fails, write to us.

## Webhooks

- The webhook address is set on your account's Webhook page. There is one for all your workspaces, https only.
- Each event comes as a POST request with JSON of four fields: `type`, `timestamp`, `workspace` and `data`. `workspace` is its workspace: `id`, the Workspace ID from the workspace's Settings page, which never changes, and `name`, its current name. Tell the events of your workspaces apart by `workspace.id` when you have several.
- The signature follows Standard Webhooks, in the headers `webhook-id`, `webhook-timestamp` and `webhook-signature`. The secret starts with `whsec_`, so keep it in an environment variable, for example `WEBHOOK_SECRET`.
- Answer 2xx within 5 seconds and do long work in the background. After any other response or a timeout the event comes again with the same `webhook-id`, so use it to drop repeats. Any other response, 3xx and 4xx included, counts as a failure.
- If the address does not answer 2xx, we try again: 8 tries in all over about 21 h. If the address fails for longer than 24 h while events keep coming, sending pauses, and new events wait until it is resumed on the workspace's Webhook deliveries page or a new address is saved. That page shows every try, and sends the test event `webhook.test`: answer it 2xx, its `data` holds only `message`.

`message.received`: A customer wrote to you on any connected channel, or, in test mode, through `POST /v1/test/inbound`. `data` holds the channel, the customer's address on it (`from`), the contact, the name, the text or a file, and the time. You may reply with free text until `free_text_until`, and `null` there means the channel has no such window.

```json
{
    "type": "message.received",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-6a29-7b40-8e0d-2f1c3a4b5d6e",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "from": "+77011234567",
        "name": "Asel",
        "channel": "whatsapp",
        "type": "text",
        "text": {
            "body": "Hello! When will my order be ready?"
        },
        "received_at": "2026-10-09T09:30:00+00:00",
        "free_text_until": "2026-10-10T09:30:00+00:00"
    }
}
```

`message.status`: A message of the workspace changed status: it was handed to the channel (`sent`), delivered (`delivered`), read (`read`) or not sent (`failed`, the reason in `error.code`). Not every channel reports delivery and reading, and `rules.receipts` in `GET /v1/channels` says which do. `data` holds the whole message, as `GET /v1/messages/{id}` returns it. It comes for every message of the workspace, not only those sent through the API: `sent_by` tells who sent it.

```json
{
    "type": "message.status",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
        "to": "+77011234567",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "channel": "whatsapp",
        "type": "text",
        "text": {
            "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
        },
        "status": "delivered",
        "error": null,
        "sent_by": "api",
        "created_at": "2026-10-09T09:30:00+00:00",
        "sent_at": "2026-10-09T09:30:00+00:00",
        "delivered_at": "2026-10-09T09:30:02+00:00",
        "read_at": null
    }
}
```

`message.refused`: A message of the workspace will not go: the checks did not let it through, for example with no consent from the customer or the window closed, or a person dismissed the draft or a newer one replaced it. `data` is the whole message as `GET /v1/messages/{id}` returns it, the reason in `error`. For a send through the API the same reason also comes in the response to the request.

```json
{
    "type": "message.refused",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "id": "0199c5e2-7b3a-7c51-9f0e-3a1d2b4c5e6f",
        "to": "+77011234567",
        "contact_id": "0199c5e2-1f0a-7a42-8d1e-5b7c9a2e4f10",
        "channel": "whatsapp",
        "type": "text",
        "text": {
            "body": "Hello! Your order #1042 is ready, and you can pick it up today until 8 pm."
        },
        "status": "refused",
        "error": {
            "code": "no_consent",
            "message": "The customer has not agreed to hear from you. Once they agree, record it with POST /v1/contacts/{phone}/consent."
        },
        "sent_by": "api",
        "created_at": "2026-10-09T09:30:00+00:00",
        "sent_at": null,
        "delivered_at": null,
        "read_at": null
    }
}
```

`channel.updated`: A channel of the workspace was connected or disconnected, Meta disconnected or restored it, or an alert on it came or went, for example when Meta cannot charge for messages. `data` is the whole channel as `GET /v1/channels` returns it for a live key: its state in `status`, alerts in `alerts`.

```json
{
    "type": "channel.updated",
    "timestamp": "2026-10-09T09:30:00+00:00",
    "workspace": {
        "id": "0199c5e2-0d4b-7e21-a3f6-8c2b1e7d9a40",
        "name": "Smile Clinic"
    },
    "data": {
        "channel": "whatsapp",
        "status": "connected",
        "sends_to": "whatsapp",
        "account": {
            "address": "+7 727 355 00 00",
            "name": "Zerno Coffee",
            "url": "https://wa.me/77273550000"
        },
        "quality": "high",
        "limits": {
            "new_customers_per_day": 2000,
            "messages_per_second": 80
        },
        "rules": {
            "free_text_window_hours": 24,
            "templates": true,
            "receipts": [
                "delivered",
                "read"
            ]
        },
        "alerts": [],
        "whatsapp": {
            "shared_with_phone_app": false
        }
    }
}
```

Check the signature with a ready-made Standard Webhooks library, one for every language the SDKs cover: `standardwebhooks` for Node.js, Python and Rust, `standard-webhooks/standard-webhooks` for PHP, `github.com/standard-webhooks/standard-webhooks/libraries/go` for Go and `StandardWebhooks.StandardWebhooks` for .NET. By hand it goes like this: base64-decode the part of the secret after `whsec_`, compute with that key the HMAC-SHA256 of the string `webhook-id.webhook-timestamp.body`, base64-encode the result and compare it with each signature after `v1,` in `webhook-signature` (there may be several, separated by spaces), using a constant-time comparison. Take the body as it arrived, before parsing the JSON. Reject events whose time is more than 5 minutes off yours.

```js
import { Webhook } from "standardwebhooks";

const webhook = new Webhook(process.env.WEBHOOK_SECRET);

const event = webhook.verify(rawBody, {
  "webhook-id": request.headers["webhook-id"],
  "webhook-timestamp": request.headers["webhook-timestamp"],
  "webhook-signature": request.headers["webhook-signature"],
});
```

## Test mode

- A test key sends on the simulator: messages are recorded and pass the same checks, but go nowhere.
- `POST /v1/test/inbound` writes as a customer. The `message.received` webhook arrives, and until its `free_text_until` you can answer this number with text.
- The simulator reports no delivery or reading, so test messages stay `sent`.
- In test mode `channel` is `simulator` in responses and webhooks, and that alone marks a test: there is no separate mode field. A test key sees only test messages, and the consent it records counts only on the simulator.
- In test mode too, templates come from the ones Meta approved for the number.
- A test key sends on the simulator with `whatsapp` and `auto` alike, and `auto` chooses from what the customer wrote through `POST /v1/test/inbound`.
- `POST /v1/test/inbound` with `type` `voice`, `audio`, `image` or `video` sends a sample file: `message.received` carries its `media_id`, and `GET /v1/media/{id}` downloads it with the test key. A file uploaded with a test key is checked and goes nowhere.
