# WhatsApp Webhook - Quick Start Guide

## 📋 What You Have

1. **whatsapp_webhook.php** - Main webhook handler
2. **whatsapp_config.php** - Configuration file
3. **whatsapp_database.sql** - Database schema (optional)
4. **WHATSAPP_SETUP_GUIDE.md** - Detailed setup instructions
5. **QUICK_START.md** - This file

---

## 🚀 5-Minute Setup

### Step 1: Update Configuration
Edit `whatsapp_config.php`:
```php
'verify_token' => 'your_webhook_verify_token_here',
'phone_number_id' => 'your_phone_number_id_here',
'access_token' => 'your_access_token_here',
'business_account_id' => 'your_waba_id_here',
```

Get these values from:
- [Meta App Dashboard](https://developers.facebook.com/apps)
- WhatsApp > Configuration > Phone Number ID & Access Token

### Step 2: Upload Files
Upload to your server:
```
your-domain.com/webhooks/whatsapp_webhook.php
your-domain.com/webhooks/whatsapp_config.php
```

**Must be HTTPS** (required by Meta)

### Step 3: Configure in Meta Dashboard
1. Go to App Dashboard > WhatsApp > Configuration
2. Set **Callback URL**: `https://your-domain.com/webhooks/whatsapp_webhook.php`
3. Set **Verify Token**: Same as in config file
4. Click **Verify and Save**

### Step 4: Subscribe to Webhooks
In same Configuration section:
- ✅ Check **messages**
- ✅ Check **message_template_status_update**

### Step 5: Done! 🎉
Start receiving webhooks. Check the log file:
```bash
tail -f /path/to/whatsapp_webhooks.log
```

---

## 📞 Send Your First Message

```php
<?php
require 'whatsapp_webhook.php';

$config = require 'whatsapp_config.php';

sendMessage(
    '16505551234',              // User's WhatsApp number (with country code)
    'Hello! This is a test',    // Message
    $config['phone_number_id'], // Your phone number ID
    $config['access_token']     // Your access token
);
?>
```

Run:
```bash
php send_message.php
```

---

## 🧪 Test Webhook Locally with ngrok

### Install ngrok
```bash
# macOS
brew install ngrok

# Ubuntu/Debian
apt-get install ngrok

# Or download from https://ngrok.com/download
```

### Start webhook on localhost
```bash
# Local PHP server (port 8000)
php -S localhost:8000 whatsapp_webhook.php
```

### Expose with ngrok
```bash
ngrok http 8000
# Output: https://abc123.ngrok.io
```

### Update Meta Dashboard
- Callback URL: `https://abc123.ngrok.io/whatsapp_webhook.php`
- Verify Token: Your chosen token
- Click **Verify and Save**

### Watch Webhooks in Real-Time
```bash
# Terminal 1: Run webhook
php -S localhost:8000

# Terminal 2: Watch logs
tail -f whatsapp_webhooks.log

# Terminal 3: Test with curl
curl -X POST https://abc123.ngrok.io/whatsapp_webhook.php \
  -H "Content-Type: application/json" \
  -d '{
    "object": "whatsapp_business_account",
    "entry": [{
      "changes": [{
        "value": {
          "messaging_product": "whatsapp",
          "messages": [{
            "from": "16505551234",
            "id": "test123",
            "timestamp": "1749416383",
            "type": "text",
            "text": {"body": "Hello webhook!"}
          }]
        },
        "field": "messages"
      }]
    }]
  }'
```

---

## 📊 Webhook Payload Reference

### Incoming Text Message
```json
{
  "object": "whatsapp_business_account",
  "entry": [{
    "changes": [{
      "value": {
        "messaging_product": "whatsapp",
        "messages": [{
          "from": "16505551234",
          "id": "wamid.xxx",
          "timestamp": "1749416383",
          "type": "text",
          "text": {"body": "Your message here"}
        }]
      },
      "field": "messages"
    }]
  }]
}
```

### Message Status (Delivered/Read)
```json
{
  "object": "whatsapp_business_account",
  "entry": [{
    "changes": [{
      "value": {
        "messaging_product": "whatsapp",
        "statuses": [{
          "id": "wamid.xxx",
          "status": "delivered",
          "timestamp": "1749416384",
          "recipient_id": "16505551234"
        }]
      },
      "field": "messages"
    }]
  }]
}
```

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

---

## 🛠️ Common Tasks

### Receive a Message and Reply
```php
function handleTextMessage($from, $text, $messageId) {
    // Echo back the message
    sendMessage(
        $from,
        "You said: " . $text,
        PHONE_NUMBER_ID,
        ACCESS_TOKEN
    );
}
```

### Save Messages to Database
```php
function handleTextMessage($from, $text, $messageId) {
    $pdo = new PDO('mysql:host=localhost;dbname=whatsapp', 'user', 'pass');
    $stmt = $pdo->prepare(
        'INSERT INTO whatsapp_messages (phone_number, message_body, message_id) 
         VALUES (?, ?, ?)'
    );
    $stmt->execute([$from, $text, $messageId]);
}
```

### Send Template Messages
```php
function sendTemplate($phoneNumber, $templateName, $parameters = []) {
    $url = "https://graph.instagram.com/v18.0/" . PHONE_NUMBER_ID . "/messages";
    
    $payload = [
        'messaging_product' => 'whatsapp',
        'to' => $phoneNumber,
        'type' => 'template',
        'template' => [
            'name' => $templateName,
            'language' => ['code' => 'en_US']
        ]
    ];
    
    if (!empty($parameters)) {
        $payload['template']['components'][0]['parameters'] = $parameters;
    }
    
    // Send via curl (same as sendMessage function)
    // ...
}
```

### Send Media Messages
```php
function sendImage($phoneNumber, $imageUrl, $caption = null) {
    $url = "https://graph.instagram.com/v18.0/" . PHONE_NUMBER_ID . "/messages";
    
    $payload = [
        'messaging_product' => 'whatsapp',
        'recipient_type' => 'individual',
        'to' => $phoneNumber,
        'type' => 'image',
        'image' => [
            'link' => $imageUrl
        ]
    ];
    
    if ($caption) {
        $payload['image']['caption'] = $caption;
    }
    
    // Send via curl...
}
```

---

## 🔍 Debugging Checklist

| Issue | Solution |
|-------|----------|
| ❌ Webhook not verified | Check verify token matches, ensure HTTPS |
| ❌ No messages received | Check "messages" is subscribed in Config, app is Live mode |
| ❌ 403 Forbidden error | Check server logs, verify HTTPS is working |
| ❌ 500 Server error | Check PHP syntax in webhook.php |
| ✅ Still stuck? | Check `whatsapp_webhooks.log` for error details |

### View Logs
```bash
# Last 20 lines
tail -20 whatsapp_webhooks.log

# Real-time
tail -f whatsapp_webhooks.log

# Search for errors
grep "error" whatsapp_webhooks.log

# Count messages
grep -c "New message" whatsapp_webhooks.log
```

---

## 📝 Next Steps

1. ✅ Set up webhook.php on your server
2. ✅ Configure in Meta dashboard  
3. ✅ Test webhook verification
4. ✅ Send test message from WhatsApp
5. ✅ Verify message appears in logs
6. ✅ Implement your business logic
7. ✅ Set up database (optional)
8. ✅ Add auto-reply functionality
9. ✅ Deploy to production

---

## 📚 Resources

- [Full Setup Guide](./WHATSAPP_SETUP_GUIDE.md)
- [Database Schema](./whatsapp_database.sql)
- [Configuration File](./whatsapp_config.php)
- [WhatsApp 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)

---

## 💡 Pro Tips

1. **Use ngrok during development** - Easy testing without deploying
2. **Check logs first** - Always look at `whatsapp_webhooks.log` when debugging
3. **Test webhook in dashboard** - Meta provides a test tool in Configuration
4. **Keep access tokens secure** - Use environment variables in production
5. **Monitor rate limits** - Meta has messaging limits; check account alerts
6. **Use templates** - Template messages are cheaper and more reliable

---

**Need help?** Check the logs: `tail -f whatsapp_webhooks.log`
