# 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://api.airbox.kz/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/docs/templates.md).

## 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/docs/api/messages.md).

## 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. A refused send keeps its key too, so send the corrected message with a new one. See [Making requests](https://airbox.kz/docs/api/requests.md).