# Webhook System Guide

## Overview

The WhatsApp CRM API includes a **webhook system** that allows external platforms to receive real-time notifications about events happening in your WhatsApp sessions.

This is similar to WhatsML, Twilio, and other third-party WhatsApp tools - allowing you to build integrations and automations on top of the API.

## How It Works

```
┌─────────────────────────────────────────────────────┐
│         Your WhatsApp CRM API Server               │
│  ┌──────────────────────────────────────────────┐ │
│  │  User logs in via QR → Session created       │ │
│  │  Message received from WhatsApp              │ │
│  │  Event: message.received                     │ │
│  └──────────────────────────────────────────────┘ │
└───────────────────┬─────────────────────────────────┘
                    │
                    │ POST webhook payload
                    ▼
        ┌───────────────────────────┐
        │ Your External Platform    │
        │ (CRM/Chatbot/Integration) │
        │                           │
        │ Webhook endpoint:         │
        │ https://yoursite.com/     │
        │ whatsapp-webhook          │
        └───────────────────────────┘
```

## Webhook Events

The system triggers webhooks for these events:

### 1. **message.received**
When a message is received from a contact

**Payload:**
```json
{
  "event": "message.received",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "messageId": "true_919876543210@c.us_E1234567890",
    "from": "919876543210",
    "to": "919876543211@c.us",
    "text": "Hello! How are you?",
    "type": "text",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 2. **message.sent**
When a message is sent to a contact

**Payload:**
```json
{
  "event": "message.sent",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "messageId": "true_919876543211@c.us_E1234567890",
    "to": "919876543210",
    "text": "Hello! I'm doing great!",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 3. **contact.added**
When a new contact is added

**Payload:**
```json
{
  "event": "contact.added",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "contactId": "uuid-here",
    "phone": "919876543210",
    "name": "John Doe",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 4. **contact.updated**
When a contact is updated

**Payload:**
```json
{
  "event": "contact.updated",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "contactId": "uuid-here",
    "phone": "919876543210",
    "name": "John Smith",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 5. **contact.deleted**
When a contact is deleted

**Payload:**
```json
{
  "event": "contact.deleted",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "contactId": "uuid-here",
    "phone": "919876543210",
    "name": "John Doe",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 6. **session.authenticated**
When a session is authenticated (QR code scanned)

**Payload:**
```json
{
  "event": "session.authenticated",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "phone_number": "919876543210",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

### 7. **session.disconnected**
When a session is disconnected

**Payload:**
```json
{
  "event": "session.disconnected",
  "timestamp": "2024-01-30T10:05:00.000Z",
  "sessionId": "uuid-here",
  "data": {
    "reason": "logout",
    "timestamp": "2024-01-30T10:05:00.000Z"
  }
}
```

## API Endpoints

### Register a Webhook

**Endpoint:** `POST /api/webhooks/:sessionId`

**Header:** `X-API-Key: your_api_key`

**Body:**
```json
{
  "eventType": "message.received",
  "webhookUrl": "https://yourplatform.com/webhooks/whatsapp",
  "isActive": true
}
```

**Response:**
```json
{
  "success": true,
  "webhook": {
    "webhookId": "uuid-here",
    "eventType": "message.received",
    "webhookUrl": "https://yourplatform.com/webhooks/whatsapp",
    "isActive": true,
    "status": "registered"
  }
}
```

### Get All Webhooks

**Endpoint:** `GET /api/webhooks/:sessionId`

**Header:** `X-API-Key: your_api_key`

**Response:**
```json
{
  "success": true,
  "total": 2,
  "webhooks": [
    {
      "id": "uuid-1",
      "session_id": "uuid-session",
      "event_type": "message.received",
      "webhook_url": "https://yourplatform.com/webhooks/messages",
      "is_active": 1,
      "created_at": "2024-01-30T10:00:00Z",
      "updated_at": "2024-01-30T10:00:00Z",
      "isActive": true
    }
  ]
}
```

### Get Specific Webhook

**Endpoint:** `GET /api/webhooks/:sessionId/:webhookId`

**Header:** `X-API-Key: your_api_key`

### Update Webhook

**Endpoint:** `PUT /api/webhooks/:sessionId/:webhookId`

**Header:** `X-API-Key: your_api_key`

**Body:**
```json
{
  "eventType": "message.sent",
  "webhookUrl": "https://yourplatform.com/webhooks/whatsapp",
  "isActive": true
}
```

### Delete Webhook

**Endpoint:** `DELETE /api/webhooks/:sessionId/:webhookId`

**Header:** `X-API-Key: your_api_key`

### Test Webhook

**Endpoint:** `POST /api/webhooks/:sessionId/:webhookId/test`

**Header:** `X-API-Key: your_api_key`

Sends a test payload to your webhook URL to verify it's working.

**Response:**
```json
{
  "success": true,
  "result": {
    "webhookId": "uuid-here",
    "status": "success",
    "statusCode": 200,
    "message": "Webhook test successful"
  }
}
```

### Get Webhook Logs

**Endpoint:** `GET /api/webhooks/:sessionId/:webhookId/logs?limit=50`

**Header:** `X-API-Key: your_api_key`

View delivery logs for your webhook (successful and failed deliveries).

**Response:**
```json
{
  "success": true,
  "total": 5,
  "logs": [
    {
      "id": 1,
      "webhook_id": "uuid-here",
      "status_code": 200,
      "message": "Success",
      "timestamp": "2024-01-30T10:05:00Z"
    },
    {
      "id": 2,
      "webhook_id": "uuid-here",
      "status_code": 500,
      "message": "Internal Server Error",
      "timestamp": "2024-01-30T10:04:00Z"
    }
  ]
}
```

## cURL Examples

### Register Webhook for All Messages Received

```bash
curl -X POST http://localhost:3000/api/webhooks/YOUR_SESSION_ID \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "eventType": "message.received",
    "webhookUrl": "https://yourplatform.com/webhooks/messages",
    "isActive": true
  }'
```

### Register Webhook for All Messages Sent

```bash
curl -X POST http://localhost:3000/api/webhooks/YOUR_SESSION_ID \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "eventType": "message.sent",
    "webhookUrl": "https://yourplatform.com/webhooks/sent",
    "isActive": true
  }'
```

### Test a Webhook

```bash
curl -X POST http://localhost:3000/api/webhooks/YOUR_SESSION_ID/WEBHOOK_ID/test \
  -H "X-API-Key: YOUR_API_KEY"
```

### Get Webhook Logs

```bash
curl http://localhost:3000/api/webhooks/YOUR_SESSION_ID/WEBHOOK_ID/logs?limit=20 \
  -H "X-API-Key: YOUR_API_KEY"
```

### Update Webhook

```bash
curl -X PUT http://localhost:3000/api/webhooks/YOUR_SESSION_ID/WEBHOOK_ID \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "eventType": "message.received",
    "webhookUrl": "https://newplatform.com/webhooks/whatsapp",
    "isActive": true
  }'
```

### Delete Webhook

```bash
curl -X DELETE http://localhost:3000/api/webhooks/YOUR_SESSION_ID/WEBHOOK_ID \
  -H "X-API-Key: YOUR_API_KEY"
```

## Implementation Examples

### Node.js - Express Webhook Receiver

```javascript
const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhooks/whatsapp', (req, res) => {
  const { event, sessionId, data } = req.body;

  console.log(`Event: ${event}`);
  console.log(`Data:`, data);

  // Handle different events
  switch(event) {
    case 'message.received':
      console.log(`New message from ${data.from}: ${data.text}`);
      // Send to your CRM
      // Send auto-reply
      break;
    
    case 'message.sent':
      console.log(`Message sent to ${data.to}`);
      // Log in your system
      break;
    
    case 'contact.added':
      console.log(`New contact: ${data.name} (${data.phone})`);
      // Add to your database
      break;
    
    case 'session.authenticated':
      console.log(`Session authenticated: ${data.phone_number}`);
      // Update your system
      break;
  }

  // Always respond with 200 to acknowledge receipt
  res.json({ success: true, message: 'Webhook received' });
});

app.listen(3001, () => console.log('Webhook server listening on port 3001'));
```

### Python - Flask Webhook Receiver

```python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/whatsapp', methods=['POST'])
def whatsapp_webhook():
    data = request.get_json()
    
    event = data.get('event')
    session_id = data.get('sessionId')
    payload = data.get('data')
    
    print(f"Event: {event}")
    print(f"Data: {payload}")
    
    if event == 'message.received':
        print(f"New message from {payload['from']}: {payload['text']}")
        # Handle incoming message
        
    elif event == 'message.sent':
        print(f"Message sent to {payload['to']}")
        
    elif event == 'contact.added':
        print(f"New contact: {payload['name']}")
        
    return jsonify({'success': True, 'message': 'Webhook received'})

if __name__ == '__main__':
    app.run(port=3001)
```

### PHP - Webhook Receiver

```php
<?php
$input = json_decode(file_get_contents('php://input'), true);

$event = $input['event'];
$sessionId = $input['sessionId'];
$data = $input['data'];

error_log("Event: " . $event);
error_log("Data: " . json_encode($data));

switch($event) {
    case 'message.received':
        error_log("New message from " . $data['from']);
        // Handle incoming message
        break;
        
    case 'message.sent':
        error_log("Message sent to " . $data['to']);
        break;
        
    case 'contact.added':
        error_log("New contact: " . $data['name']);
        break;
}

header('Content-Type: application/json');
echo json_encode(['success' => true, 'message' => 'Webhook received']);
?>
```

## Use Cases

### 1. Real-time CRM Updates
```
Message received → Webhook → Create lead in Salesforce/HubSpot
Contact added → Webhook → Add to CRM database
```

### 2. Chatbot Integration
```
Message received → Webhook → Send to chatbot
Bot response → API call → Send via WhatsApp API
```

### 3. Notification System
```
Message received → Webhook → Send email/SMS notification
Message sent → Webhook → Log in system
```

### 4. Analytics & Reporting
```
All events → Webhook → Log to analytics platform
Track message metrics, response times, engagement
```

### 5. Auto-responder
```
Message received → Webhook → Check if auto-reply enabled
Send auto-response via API
```

### 6. Queue System
```
Message received → Webhook → Add to message queue
Process messages asynchronously
```

## Best Practices

1. **Always respond with 200** - Acknowledge webhook receipt immediately
2. **Process asynchronously** - Don't do heavy processing in webhook handler
3. **Use message queues** - Queue incoming webhooks for processing
4. **Log everything** - Keep logs of all webhook deliveries
5. **Monitor delivery** - Check webhook logs regularly
6. **Set timeouts** - Your endpoint should respond within 5-10 seconds
7. **Validate webhooks** - Verify the sessionId in your system
8. **Handle retries** - Be prepared for duplicate webhook deliveries
9. **Use HTTPS** - Always use HTTPS for webhook URLs
10. **Scale properly** - Ensure your webhook endpoint can handle volume

## Webhook Delivery Guarantees

- **At-least-once delivery**: Webhooks may be delivered multiple times
- **No guaranteed order**: Events may be received out of order
- **Timeout**: Webhooks fail if endpoint doesn't respond in 10 seconds
- **Retry logic**: Failed webhooks are logged but not automatically retried

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Webhook not triggered | Check webhook is active, verify event type |
| Webhook failing | Check webhook URL is correct, verify endpoint responding |
| Timeouts | Ensure endpoint responds within 10 seconds |
| Missing events | Check webhook logs for delivery status |
| Duplicate events | Implement idempotency key handling |

## Webhook URL Requirements

Your webhook endpoint must:
- ✅ Accept POST requests
- ✅ Accept JSON payloads
- ✅ Return HTTP 200 status
- ✅ Respond within 10 seconds
- ✅ Use HTTPS in production
- ✅ Be publicly accessible

## Security

- Webhooks are only sent to authenticated sessions
- Your API key is required to register webhooks
- Store webhook credentials securely
- Validate sessionId in webhook payload
- Use HTTPS to encrypt webhook payloads
- Implement rate limiting on your webhook endpoint

---

This webhook system makes it easy to integrate your WhatsApp session with any external platform - just like WhatsML, Twilio, and other professional services!
