# WhatsApp Business Webhook Setup Guide

## Step 1: Get Your Credentials from Meta

1. Go to [Meta Developers](https://developers.facebook.com)
2. Create or select your app
3. Go to **Settings** > **Basic** and get your:
   - **App ID**
   - **App Secret**

4. Go to **WhatsApp** > **Getting Started** or **Configuration**
5. Get your:
   - **Phone Number ID** (for your WhatsApp Business phone number)
   - **Business Account ID** (WABA)
   - **Access Token** (from System User)

## Step 2: Deploy Your Webhook Endpoint

### Option A: Using Your Own Server
1. Upload `whatsapp_webhook.php` to your server
2. Make sure it's accessible via HTTPS (required by Meta)
3. Note the full URL: `https://yourdomain.com/whatsapp_webhook.php`

### Option B: Using Local Testing (ngrok)
For local development, use ngrok to expose your local server:

```bash
ngrok http 80
# or for HTTPS
ngrok http 443
```

This gives you a public URL like `https://xxx.ngrok.io/whatsapp_webhook.php`

## Step 3: Configure Webhook in Meta Dashboard

1. Go to **[Meta App Dashboard](https://developers.facebook.com/apps)**
2. Select your app → **WhatsApp** → **Configuration**
3. In the **Webhook URL** section:
   - **Callback URL**: `https://yourdomain.com/whatsapp_webhook.php`
   - **Verify Token**: Set any secure string (e.g., `abc123secure456`)
4. Click **Verify and Save**

Meta will send a GET request to verify your endpoint. The webhook handler checks the verify token automatically.

## Step 4: Subscribe to Webhook Fields

In the same **Configuration** section, subscribe to these fields:

**Essential:**
- ✅ **messages** - Receive incoming messages
- ✅ **message_template_status_update** - Template status changes

**Optional (based on your needs):**
- account_alerts - Messaging limits, account status
- message_template_quality_update - Template quality scores
- business_capability_update - Account capability changes

## Step 5: Update Configuration in PHP Code

Edit `whatsapp_webhook.php` and update:

```php
define('VERIFY_TOKEN', 'abc123secure456'); // Must match Meta dashboard

// Also set these constants for sending messages:
define('PHONE_NUMBER_ID', 'your_phone_number_id_here');
define('ACCESS_TOKEN', 'your_access_token_here');
define('WABA_ID', 'your_business_account_id_here');
```

## Step 6: Test Your Webhook

### Using Meta Dashboard Test Tool
1. In **Configuration** section, find **Send test message**
2. Click to send a test payload
3. Check your `whatsapp_webhooks.log` file to verify it was received

### Using curl (command line)
```bash
curl -X POST https://yourdomain.com/whatsapp_webhook.php \
  -H "Content-Type: application/json" \
  -d '{
    "object": "whatsapp_business_account",
    "entry": [{
      "id": "102290129340398",
      "changes": [{
        "value": {
          "messaging_product": "whatsapp",
          "messages": [{
            "from": "16505551234",
            "id": "wamid.test",
            "timestamp": "1749416383",
            "type": "text",
            "text": {"body": "Test message"}
          }]
        },
        "field": "messages"
      }]
    }]
  }'
```

## Step 7: Send Messages Back to Users

To reply to messages, use the included `sendMessage()` function:

```php
sendMessage(
    '16505551234',  // User's phone number (with country code)
    'Hello! Thanks for messaging us!',
    $phoneNumberId,
    $accessToken
);
```

Or implement full message sending in your message handlers.

## Webhook Payload Examples

### Incoming Text Message
```json
{
  "object": "whatsapp_business_account",
  "entry": [{
    "id": "102290129340398",
    "changes": [{
      "value": {
        "messaging_product": "whatsapp",
        "metadata": {
          "display_phone_number": "15550783881",
          "phone_number_id": "106540352242922"
        },
        "contacts": [{
          "profile": {"name": "John Doe"},
          "wa_id": "16505551234"
        }],
        "messages": [{
          "from": "16505551234",
          "id": "wamid.HBgL...",
          "timestamp": "1749416383",
          "type": "text",
          "text": {"body": "Hi, I need help!"}
        }]
      },
      "field": "messages"
    }]
  }]
}
```

### Message Status Update
```json
{
  "object": "whatsapp_business_account",
  "entry": [{
    "id": "102290129340398",
    "changes": [{
      "value": {
        "messaging_product": "whatsapp",
        "metadata": {
          "phone_number_id": "106540352242922"
        },
        "statuses": [{
          "id": "wamid.HBgL...",
          "status": "delivered",
          "timestamp": "1749416384",
          "recipient_id": "16505551234"
        }]
      },
      "field": "messages"
    }]
  }]
}
```

Status values: `sent`, `delivered`, `read`, `failed`

## Common Issues & Solutions

### ❌ "Webhook verification failed"
- Make sure verify token in code matches Meta dashboard
- Ensure endpoint is HTTPS
- Check your server is accessible from the internet

### ❌ "Not receiving messages"
- Verify webhook URL is correct in Meta dashboard
- Check PHP error logs
- Make sure "messages" field is subscribed in Configuration
- Ensure app is in **Live** mode (not Dev)

### ❌ "Getting 403 Forbidden"
- Check server logs
- Verify HTTPS is working
- Ensure correct file permissions

### ✅ "Webhooks working!"
- Check `whatsapp_webhooks.log` for incoming payloads
- All messages should appear in the log
- Database integration working as expected

## File Structure

```
your-project/
├── whatsapp_webhook.php          # Main webhook handler
├── whatsapp_webhooks.log         # Webhook log file (auto-created)
├── WHATSAPP_SETUP_GUIDE.md      # This file
└── database/
    └── whatsapp_messages.sql     # (Optional) Database schema
```

## Database Integration (Optional)

To store messages in a database, modify the message handlers. Example:

```php
function handleTextMessage($from, $text, $messageId) {
    // Save to database
    $pdo = new PDO('mysql:host=localhost;dbname=whatsapp', 'user', 'pass');
    $stmt = $pdo->prepare('INSERT INTO messages (from_number, body, message_id) VALUES (?, ?, ?)');
    $stmt->execute([$from, $text, $messageId]);
}
```

## Next Steps

1. ✅ Deploy webhook.php to HTTPS server
2. ✅ Configure in Meta dashboard
3. ✅ Test with sample messages
4. ✅ Implement your business logic in message handlers
5. ✅ Add database storage (optional)
6. ✅ Set up message templating for auto-replies
7. ✅ Monitor logs and adjust as needed

## Resources

- [WhatsApp Business API Docs](https://developers.facebook.com/docs/whatsapp)
- [Webhooks Reference](https://developers.facebook.com/docs/whatsapp/webhooks)
- [Message Types](https://developers.facebook.com/docs/whatsapp/message-types)
- [Sending Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages)

---

**Questions?** Check the logs in `whatsapp_webhooks.log` for detailed debugging information.
