# WhatsApp

> Set up an Aerostack bot on WhatsApp using the WhatsApp Cloud API via Meta Developer Portal.

Connect your Aerostack bot to WhatsApp using the WhatsApp Cloud API. Messages sent to your WhatsApp Business number are forwarded to Aerostack, processed through the bot engine, and responses are sent back automatically.

---

## Prerequisites

- An Aerostack account with an existing bot (or create one during setup)
- A [Meta Developer](https://developers.facebook.com/) account
- A Meta Business account (required for WhatsApp Cloud API)

---

## Step 1: Create a Meta App

1. Go to the [Meta Developer Portal](https://developers.facebook.com/apps/)
2. Click **Create App** and select **Business** type
3. Fill in the app name and select your Business account
4. On the app dashboard, find **WhatsApp** and click **Set Up**
5. Follow the prompts to add a test phone number

From the WhatsApp section of your app, collect:

- **Phone Number ID** — found under WhatsApp > API Setup
- **Permanent Access Token** — generate a System User token with `whatsapp_business_messaging` permission (temporary tokens expire in 24 hours)
- **App Secret** — found under App Settings > Basic

The test access token from Meta expires after 24 hours. For production, create a **System User** in your Business Manager and generate a permanent token. See [Meta's documentation](https://developers.facebook.com/docs/whatsapp/business-management-api/get-started#system-user-access-tokens) for details.

---

## Step 2: Configure in Aerostack

### Via Dashboard

1. Navigate to **Bots** in the sidebar
2. Click on your bot (or create a new one with platform set to **WhatsApp**)
3. In the **Platform Configuration** section, enter:
   - **Phone Number ID** — your WhatsApp phone number ID
   - **Access Token** — your permanent access token
   - **Verify Token** — any random string you choose (used for webhook verification)
   - **App Secret** — your Meta app secret (for signature verification)

### Via API

```bash
curl -X POST https://api.aerostack.dev/api/bots \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "WhatsApp Support Bot",
    "platform": "whatsapp",
    "workspace_id": "YOUR_WORKSPACE_ID",
    "system_prompt": "You are a helpful WhatsApp assistant for Acme Corp.",
    "platform_config": {
      "phone_number_id": "123456789012345",
      "access_token": "EAABsbCS...",
      "verify_token": "my-verify-token-xyz",
      "app_secret": "abc123def456..."
    }
  }'
```

---

## Step 3: Activate

```bash
curl -X POST https://api.aerostack.dev/api/bots/YOUR_BOT_ID/activate \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Response:

```json
{
  "status": "active",
  "webhook_url": "https://api.aerostack.dev/api/bots/webhook/whatsapp/bt_a1b2c3d4e5f6g7h8i9j0",
  "manual_setup_required": true,
  "warnings": []
}
```

**Manual step required:** The WhatsApp Cloud API does not allow setting the webhook URL programmatically. You must configure the webhook URL in the Meta Developer Portal manually (see Step 4).

---

## Step 4: Set the Webhook URL in Meta Portal

1. Go to your app in the [Meta Developer Portal](https://developers.facebook.com/apps/)
2. Navigate to **WhatsApp** > **Configuration**
3. Under **Webhook**, click **Edit**
4. Enter the webhook URL from the activate response:
   ```
   https://api.aerostack.dev/api/bots/webhook/whatsapp/bt_YOUR_BOT_ID
   ```
5. Enter the **Verify Token** you configured in Step 2
6. Click **Verify and Save**
7. Under **Webhook fields**, subscribe to the `messages` field

The verification works via a GET request to your webhook URL with `hub.mode=subscribe`, `hub.verify_token`, and `hub.challenge` parameters. Aerostack handles this automatically.

---

## Step 5: Test

Send a WhatsApp message to your business phone number. The bot should respond within a few seconds.

---

## Platform Config Fields

| Field | Required | Description |
|-------|----------|-------------|
| `phone_number_id` | Yes | WhatsApp phone number ID |
| `access_token` | Yes | System User access token with `whatsapp_business_messaging` permission |
| `verify_token` | Yes | Your chosen verify token (must match what you enter in Meta portal) |
| `app_secret` | Recommended | Meta app secret for HMAC-SHA256 webhook signature verification |
| `business_account_id` | No | WhatsApp Business Account ID |

---

## Webhook Verification

When `app_secret` is set, Aerostack verifies the authenticity of every incoming WhatsApp webhook automatically.

If `app_secret` is not set, Aerostack skips signature verification. This is acceptable for development with test numbers but is a security risk in production.

---

## Supported Message Types

| Incoming Type | How It's Processed |
|---------------|-------------------|
| Text | Full text passed to bot engine |
| Image | Caption text (if any) + `[Image]` placeholder. Attachment metadata included. |
| Document | Caption text (if any) + `[Document: filename]` placeholder |
| Audio | `[Voice message]` placeholder |
| Video | Caption text (if any) + `[Video]` placeholder |
| Location | `[Location: lat, lng]` placeholder |
| Interactive (button/list reply) | Button title or list row title used as text |

---

## 24-Hour Messaging Window

WhatsApp enforces a **24-hour messaging window**. Your bot can send free-form messages only within 24 hours of the user's last message. Outside this window, you must use pre-approved message templates.

Aerostack does not currently enforce or handle the 24-hour window. If a user messages your bot after the window expires, WhatsApp will accept the incoming message but may reject the bot's response. This results in a silent send failure from the bot's perspective.

---

## Read Receipts

Aerostack automatically sends **read receipts** (blue ticks) when processing WhatsApp messages. This is non-blocking and happens in the background.

---

## Message Limits

WhatsApp enforces a **4096 character limit** per message. Longer responses are automatically split at whitespace boundaries.

---

## Troubleshooting

| Issue | Solution |
|-------|---------|
| Webhook verification fails in Meta Portal | Check that your `verify_token` matches exactly. The verify token is case-sensitive. |
| Bot not responding to messages | Verify you subscribed to the `messages` webhook field in Meta Portal. Check that the access token is valid (not expired). |
| "Message failed to send" | Your access token may have expired (24h for test tokens). Generate a permanent System User token. |
| Bot responds once then stops | This may be the 24-hour window. The user must send another message to re-open the window. |
