> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zappway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# WhatsApp API

> Internal reference for the WhatsApp Business API integration — session management, QR code pairing, webhook event processing, conversation routing, and message sending.

> **Internal documentation for developers.** This page covers the WhatsApp Business API integration: session lifecycle, webhook architecture, and routing patterns. Not intended for end users.

***

## Route Map

| Method     | Endpoint                       | Handler File                           | Type                    |
| ---------- | ------------------------------ | -------------------------------------- | ----------------------- |
| `POST`     | `/api/whatsapp/create-session` | `whatsapp/create-session/route.ts`     | Setup                   |
| `GET`      | `/api/whatsapp/qr-code`        | `whatsapp/qr-code/route.ts`            | Setup                   |
| `GET/POST` | `/api/whatsapp/sessions`       | `whatsapp/sessions/route.ts`           | Session CRUD            |
| `POST`     | `/api/whatsapp/assign`         | `whatsapp/assign/route.ts`             | Agent assignment        |
| `POST`     | `/api/whatsapp/disconnect`     | `whatsapp/disconnect/route.ts`         | Session teardown        |
| `POST`     | `/api/whatsapp/resolve`        | `whatsapp/resolve/route.ts`            | Conversation resolution |
| `GET/POST` | `/api/whatsapp/status`         | `whatsapp/status/route.ts`             | Connection health       |
| `POST`     | `/api/whatsapp/start-pairing`  | `whatsapp/start-pairing/route.ts`      | Phone number pairing    |
| `POST`     | `/api/whatsapp/webhook`        | (handled via WhatsApp webhook routing) | Webhook                 |
| `GET`      | `/api/whatsapp/callback`       | `whatsapp/callback/route.ts`           | OAuth callback (Meta)   |

***

## Architecture Overview

```
WhatsApp Business API (Meta)
        ↓ (webhook POST)
/api/whatsapp/webhook
        ↓
Message routing middleware
        ↓
┌─────────────────────────────┐
│ AI Employee handles message │
│   (via @zappway/lib/...    │
│    conversation engine)     │
└─────────────────────────────┘
        ↓ (if AI replies)
Send message via WABA API
```

***

## Session Lifecycle

### 1. Pairing (QR Code or Phone Number)

Two pairing methods:

**QR Code flow:**

```
POST /api/whatsapp/create-session
  → Initializes WhatsApp session
  → Returns session token

GET /api/whatsapp/qr-code?sessionId=...
  → Returns QR code as image/JSON
  → Frontend polls until scanned or expired
```

**Phone number pairing:**

```
POST /api/whatsapp/start-pairing { phoneNumber }
  → Initiates WhatsApp phone number pairing
  → Returns pairing code
```

### 2. Session States

| State          | Description                            |
| -------------- | -------------------------------------- |
| `initializing` | Session created, not yet connected     |
| `qr_pending`   | QR code generated, awaiting scan       |
| `connected`    | WhatsApp active and receiving messages |
| `disconnected` | Session ended or timed out             |
| `error`        | Session failed — needs re-creation     |

### 3. Disconnect

```ts theme={null}
// POST /api/whatsapp/disconnect { sessionId }
// Gracefully terminates WhatsApp session
// Marks session as disconnected in DB
```

***

## Webhook Event Processing

WhatsApp sends all events (messages, status updates, read receipts) to the webhook endpoint.

**Required for webhook:**

* Public HTTPS URL
* Verified with Meta's challenge-response handshake

**Event types handled:**

| Event Type | Action                                   |
| ---------- | ---------------------------------------- |
| `messages` | Route to conversation engine, trigger AI |
| `statuses` | Update message delivery/read status      |
| `contacts` | Create/update contact record             |

**Signature verification:**

```ts theme={null}
const signature = req.headers.get('x-hub-signature-256');
// Verify using HMAC-SHA256 with WHATSAPP_APP_SECRET
```

***

## Agent Assignment

```ts theme={null}
// POST /api/whatsapp/assign { sessionId, agentId }
// Associates a WhatsApp session with a specific AI Employee
// From that point, all incoming messages go to that agent
```

***

## Conversation Resolution

```ts theme={null}
// POST /api/whatsapp/resolve { conversationId }
// Marks conversation as resolved in ZappWay
// Does NOT send any message to WhatsApp
```

***

## Meta OAuth Callback

When connecting a WhatsApp Business Account via Meta's OAuth:

```
User clicks "Connect WhatsApp" in settings
→ Redirect to Meta OAuth
→ Meta redirects to GET /api/whatsapp/callback?code=...&state=...
→ Server exchanges code for access token
→ Token stored encrypted in DB
→ Redirect to dashboard
```

***

## Environment Variables Required

| Variable                   | Description                                     |
| -------------------------- | ----------------------------------------------- |
| `WHATSAPP_APP_ID`          | Meta App ID                                     |
| `WHATSAPP_APP_SECRET`      | Meta App Secret (webhook signature + OAuth)     |
| `WHATSAPP_VERIFY_TOKEN`    | Static token for webhook verification handshake |
| `WHATSAPP_PHONE_NUMBER_ID` | Default phone number ID (if single-tenant)      |
| `WHATSAPP_ACCESS_TOKEN`    | System user or user access token                |

***

## Known Issues / Gotchas

* **Webhook re-delivery:** Meta retries webhook delivery if your server returns non-2xx. Ensure idempotent message processing using `whatsapp_message_id` as dedup key.
* **Session expiry:** WhatsApp sessions (for personal numbers via unofficial API) expire after 20 days of inactivity. Business API sessions don't expire but phone numbers can be disconnected.
* **QR code polling:** The QR code is short-lived (\~60 seconds). Frontend must regenerate if expired before scanning.
* **Rate limits:** The WhatsApp Business API enforces per-phone-number rate limits for outbound messages. Monitor for `131056` (spam rate limit) errors.
* **24-hour messaging window:** Businesses can only proactively message users who messaged within the last 24 hours (without pre-approved templates).
