# Install and configure WhatsApp-Meta-Business-API-Handler

Follow the source instructions for **WhatsApp-Meta-Business-API-Handler**. Read the prerequisites and configuration steps before running an example.

## Installation

```bash
npm install @your-package/whatsapp-handler
# or
yarn add @your-package/whatsapp-handler
```

### Requirements

- Node.js 16+
- WhatsApp Business API credentials
- Meta Business Account

---

## Quick Start

### Basic Setup

```typescript
import { createWhatsAppHandler } from './whatsapp-handler';

const whatsapp = createWhatsAppHandler({
  token: 'YOUR_ACCESS_TOKEN',
  phoneNumberId: 'YOUR_PHONE_NUMBER_ID',
  webhookVerifyToken: 'YOUR_VERIFY_TOKEN'
});

// Send a message
await whatsapp.sendMessage('1234567890', 'Hello from WhatsApp!');
```

### Using Environment Variables

```typescript
import { createWhatsAppHandlerFromEnv } from './whatsapp-handler';

// Reads from process.env automatically
const whatsapp = createWhatsAppHandlerFromEnv();
```

Required environment variables:
```env
WHATSAPP_TOKEN=your_access_token
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id
WHATSAPP_WEBHOOK_VERIFY_TOKEN=your_verify_token
WHATSAPP_APP_SECRET=your_app_secret
```

---

## Webhook Setup

### Express.js

```typescript
import express from 'express';

const app = express();
app.use(express.json());

// Use as middleware
app.post('/webhook', whatsapp.expressMiddleware());
app.get('/webhook', whatsapp.expressMiddleware());

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});
```

### Next.js (App Router)

```typescript
// app/api/webhook/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function POST(req: NextRequest) {
  const body = await req.json();
  
  const result = await whatsapp.processWebhook({
    method: 'POST',
    headers: Object.fromEntries(req.headers),
    body,
    query: Object.fromEntries(req.nextUrl.searchParams)
  });

  return NextResponse.json(result.data, { status: result.status });
}

export async function GET(req: NextRequest) {
  const result = await whatsapp.processWebhook({
    method: 'GET',
    headers: Object.fromEntries(req.headers),
    query: Object.fromEntries(req.nextUrl.searchParams)
  });

  if (result.challenge) {
    return new NextResponse(result.challenge, { status: 200 });
  }

  return NextResponse.json(result.data, { status: result.status });
}
```

### Next.js (Pages Router)

```typescript
// pages/api/webhook.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await whatsapp.nextjsHandler(req, res);
}
```

### Standalone HTTP Server

```typescript
// Start built-in server
const server = whatsapp.startWebhookServer(3000, '/webhook', () => {
  console.log('Webhook server started on port 3000');
});

// Stop server
await whatsapp.stopWebhookServer();
```

### Generic/Universal Handler

```typescript
// Works with any framework
const result = await whatsapp.processWebhook({
  method: 'POST',
  headers: req.headers,
  body: req.body,
  query: req.query,
  rawBody: req.rawBody
});
```

---

## Configuration

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `token` | `string` | **Required** | WhatsApp API access token |
| `phoneNumberId` | `string` | **Required** | Your WhatsApp phone number ID |
| `businessAccountId` | `string` | Optional | Business account ID |
| `version` | `string` | `'v21.0'` | API version |
| `appSecret` | `string` | Optional | App secret for signature verification |
| `webhookVerifyToken` | `string` | Optional | Token for webhook verification |
| `apiTimeout` | `number` | `30000` | API request timeout (ms) |
| `maxRetries` | `number` | `3` | Max retry attempts for failed requests |
| `autoMarkRead` | `boolean` | `true` | Auto-mark messages as read |
| `autoProcessMessages` | `boolean` | `true` | Auto-process incoming messages |
| `queueEnabled` | `boolean` | `true` | Enable message queue |
| `maxQueueSize` | `number` | `1000` | Maximum queue size |

### Full Configuration Example

```typescript
const whatsapp = createWhatsAppHandler({
  token: 'YOUR_TOKEN',
  phoneNumberId: 'YOUR_PHONE_ID',
  businessAccountId: 'YOUR_BUSINESS_ID',
  version: 'v21.0',
  appSecret: 'YOUR_APP_SECRET',
  webhookVerifyToken: 'YOUR_VERIFY_TOKEN',
  apiTimeout: 30000,
  maxRetries: 3,
  autoMarkRead: true,
  autoProcessMessages: true,
  queueEnabled: true,
  maxQueueSize: 1000,
  storage: {
    type: 'memory',
    autoCleanup: true,
    maxMessagesPerConversation: 1000
  },
  webhook: {
    verifyToken: 'YOUR_VERIFY_TOKEN',
    appSecret: 'YOUR_APP_SECRET',
    autoProcess: true,
    autoMarkRead: true,
    verifySignature: true,
    maxBodySize: 10485760, // 10MB
    timeout: 30000
  }
});
```

---

## Check the installation

After setup, continue with the [first example](/docs/up-to-code-whatsapp-meta-business-api-handler/quick-start-guide). If a command fails, compare the runtime version, working directory, and required configuration with the original README before changing dependencies.

## Source and help

- [GitHub repository](https://github.com/qentrah/WhatsApp-Meta-Business-API-Handler)
- [Original README](https://github.com/qentrah/WhatsApp-Meta-Business-API-Handler/blob/main/README.md)
- [Issues and existing reports](https://github.com/qentrah/WhatsApp-Meta-Business-API-Handler/issues)

The catalog identifies the license as **MIT**. Read the repository license before redistributing source or assets.