# 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/docs/sdks.md) has a runnable example for each.

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

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

```bash Laravel
composer require airboxhq/airbox-laravel
```

```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://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."
    }
}'
```

## 4. Receive replies

Set your webhook address on your account's **Webhook** page and tick the events it should hear, at least `message.received`. 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/docs/webhooks.md).

## 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. Templates are the exception: they need a connected WhatsApp number, even in test mode. See [Test mode](https://airbox.kz/docs/test-mode.md).