# WhatsApp Setup Guide

**Last Updated**: 2026-01-18

This guide walks you through setting up WhatsApp Business API access for the MKT WhatsApp Service.

## Prerequisites

- Meta Business Account
- Facebook Business Manager access
- Verified business (for higher tier limits)
- Domain with HTTPS (for webhook)

## Step 1: Create Meta Business Account

1. Go to [Meta Business Suite](https://business.facebook.com/)
2. Click "Create Account"
3. Enter your business name and details
4. Verify your business email

## Step 2: Access WhatsApp API

### Option A: Cloud API (Recommended)

1. Go to [Meta for Developers](https://developers.facebook.com/)
2. Click "My Apps" → "Create App"
3. Select "Business" as app type
4. Fill in app details (name, contact email, business account)
5. After creation, click "Add Product"
6. Select "WhatsApp" → "Set Up"

### Option B: On-Premise API

Not recommended for most use cases. Requires dedicated server infrastructure and BSP partnership.

## Step 3: Get Phone Number

### Test Phone Number (Development)

Meta provides a test number for development:

1. In WhatsApp product settings, you'll see a test phone number
2. Copy the `Phone Number ID`
3. Add test recipients (max 5) in the Configuration tab

### Production Phone Number

1. Click "Add Phone Number"
2. Choose one of:
   - **Use existing**: Migrate existing WhatsApp Business number
   - **Register new**: Get new number from Meta
3. Verify phone number via SMS/call
4. Complete business verification

**Important**: Once connected to API, you cannot use WhatsApp Business App on this number.

## Step 4: Generate Access Token

### Temporary Token (24 hours)

1. Go to WhatsApp → API Setup
2. Copy the temporary access token
3. Use for testing only

### Permanent Token

1. Go to Meta Business Suite → Settings → System Users
2. Click "Add" → Create system user (name: "WhatsApp API")
3. Assign "Admin" role
4. Click "Generate Token"
5. Select your app
6. Choose permissions:
   - `whatsapp_business_management`
   - `whatsapp_business_messaging`
7. Copy token (store securely, shown once)

## Step 5: Configure Webhook

### Get Webhook URL

From your deployed service:
```
https://yourdomain.com/api/v1/whatsapp/webhooks
```

### Generate Verify Token

Create a random string for webhook verification:

```bash
# Generate random token
openssl rand -hex 32
```

Save this as `WHATSAPP_WEBHOOK_VERIFY_TOKEN` in your `.env`

### Setup in Meta

1. Go to WhatsApp → Configuration → Webhook
2. Click "Edit"
3. Enter:
   - **Callback URL**: `https://yourdomain.com/api/v1/whatsapp/webhooks`
   - **Verify Token**: Your generated token
4. Click "Verify and Save"

### Subscribe to Events

After verification, subscribe to:
- ✅ `messages` - Incoming customer messages
- ✅ `message_status` (optional) - Delivery/read status updates
- ✅ `messaging_postbacks` (optional) - Button interactions

## Step 6: Get App Secret

For webhook signature verification:

1. Go to App Dashboard → Settings → Basic
2. Click "Show" next to "App Secret"
3. Copy and save as `WHATSAPP_APP_SECRET`

## Step 7: Configure Service

Update your `.env` file:

```bash
# WhatsApp Configuration
WHATSAPP_PHONE_NUMBER_ID=123456789012345
WHATSAPP_ACCESS_TOKEN=your_permanent_token_here
WHATSAPP_WEBHOOK_VERIFY_TOKEN=your_verify_token_here
WHATSAPP_APP_SECRET=your_app_secret_here
WHATSAPP_API_VERSION=v21.0
```

## Step 8: Test Integration

### Verify Webhook

The service will automatically handle webhook verification. Check logs:

```bash
docker-compose logs -f mkt-whatsapp-service-net
```

You should see:
```
[INFO] Webhook verification successful
```

### Send Test Message

1. Get a test customer's WhatsApp number
2. Use API to send message:

```bash
curl -X POST http://localhost/api/v1/whatsapp/conversations/{conversationId}/messages \
  -H "Content-Type: application/json" \
  -d '{
    "content": {
      "type": "text",
      "text": "Hello from MKT WhatsApp Service!"
    }
  }'
```

### Receive Test Message

1. Send a message from test customer's WhatsApp to your business number
2. Check service logs for incoming webhook
3. Verify message is stored in database

## Step 9: Message Templates

For messages outside 24-hour window, you need approved templates.

### Create Template

1. Go to WhatsApp → Message Templates
2. Click "Create Template"
3. Fill in:
   - **Name**: `order_confirmation` (lowercase, underscores only)
   - **Category**: Utility/Marketing/Authentication
   - **Language**: Vietnamese, English, etc.
   - **Content**: Use placeholders like `{{1}}`, `{{2}}`

Example template:
```
Xin chào {{1}}!

Đơn hàng #{{2}} của bạn đã được xác nhận.
Tổng tiền: {{3}} VNĐ

Cảm ơn bạn đã mua hàng!
```

4. Submit for review (approval takes 1-3 days)

### Use Template in Service

Once approved update `.env`:
```bash
WHATSAPP_TEMPLATE_ORDER_CONFIRMATION=order_confirmation
```

## Step 10: Upgrade Tier Limits

### Initial Tier

New phone numbers start at **Tier 1** (1,000 conversations/day).

### Upgrade Process

Tiers upgrade automatically based on:
1. **Phone number quality** (low block rate)
2. **Sending volume**
3. **Time** (minimum 7 days at current tier)

### Tier Levels

| Tier | Daily Limit | Upgrade Criteria |
|------|-------------|------------------|
| Tier 1 | 1,000 | Start tier |
| Tier 2 | 10,000 | 7 days + good quality |
| Tier 3 | 100,000 | 7 days + high volume |
| Unlimited | No limit | Request from Meta |

## Troubleshooting

### Webhook Verification Fails

**Problem**: "Verification token mismatch"

**Solution**:
1. Check `WHATSAPP_WEBHOOK_VERIFY_TOKEN` matches exactly
2. Ensure service is running and accessible
3. Check HTTPS is working (WhatsApp requires HTTPS)

### Messages Not Sending

**Problem**: API returns error `(#131030) Recipient phone number not valid`

**Solution**:
1. Ensure number includes country code without + or 0
2. Format: `84901234567` (Vietnam), not `+84901234567`

**Problem**: `(#368) Template not found`

**Solution**:
1. Verify template is approved in Meta dashboard
2. Check template name matches exactly
3. Ensure correct language code

### Rate Limit Exceeded

**Problem**: `(#130429) Rate limit exceeded`

**Solution**:
1. Check current tier in Meta dashboard
2. Implement exponential backoff
3. Request tier upgrade if needed

### Invalid Access Token

**Problem**: `(#190) Invalid OAuth access token`

**Solution**:
1. Token may have expired - generate new permanent token
2. Check token has correct permissions
3. Verify token belongs to correct app

## Security Best Practices

1. **Never commit tokens** - Use environment variables
2. **Rotate tokens regularly** - Generate new tokens every 6 months
3. **Verify webhook signatures** - Always validate `X-Hub-Signature-256`
4. **Use HTTPS only** - WhatsApp will reject HTTP webhooks
5. **Restrict IP access** - Whitelist Meta IP ranges if possible

## Cost Optimization

1. **Use utility templates** - Cheaper than marketing
2. **Leverage 24-hour window** - Free messages within window
3. **Avoid spam** - High block rate can limit your account
4. **Monitor conversations** - Track which types open/close windows

## Next Steps

- [API Documentation](API.md) - Learn available endpoints
- [Automation Guide](AUTOMATION_GUIDE.md) - Setup automation flows
- [AI Chatbot Guide](AI_CHATBOT_GUIDE.md) - Configure AI agent

## Resources

- [WhatsApp Cloud API Docs](https://developers.facebook.com/docs/whatsapp/cloud-api)
- [Business Verification](https://www.facebook.com/business/help/2058515294227817)
- [Message Templates Guide](https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates)
- [Webhook Reference](https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks)
