# WhatsApp CRM API - Webhook System Summary

## What You Asked For

✅ **QR Code Authentication** - User logs in via QR code (like WhatsApp Web linked devices)
✅ **Session Management** - Automatic session creation with unique API keys
✅ **Webhook System** - External platforms can receive real-time events
✅ **Similar to WhatsML** - Professional third-party tool architecture

## System Architecture

```
┌──────────────────────────────────────────────────────┐
│  Your WhatsApp Account (via QR Code)                 │
│  Connected to Your CRM API Server                    │
└───────────────┬────────────────────────────────────────┘
                │
┌───────────────▼────────────────────────────────────────┐
│     WhatsApp CRM API Server                           │
│  ┌─────────────────────────────────────────────────┐ │
│  │  Session Management (QR Auth)                   │ │
│  │  Message Send/Receive                           │ │
│  │  Contact Management                             │ │
│  │  ⭐ Webhook Event Triggers                      │ │
│  └─────────────────────────────────────────────────┘ │
└───────────────┬────────────────────────────────────────┘
                │
    ┌───────────┼───────────┬──────────────┐
    │           │           │              │
    ▼           ▼           ▼              ▼
┌─────────┐ ┌────────┐ ┌────────┐ ┌──────────┐
│  Your   │ │  CRM   │ │Chatbot │ │Analytics│
│ Website │ │System  │ │Engine  │ │Platform │
└─────────┘ └────────┘ └────────┘ └──────────┘
```

## How It Works

### Step 1: Initialize Session with QR Code
```bash
POST /api/auth/init
→ Returns: sessionId + apiKey
→ Show QR code to user
→ User scans with WhatsApp phone
```

### Step 2: Setup Webhooks
```bash
POST /api/webhooks/:sessionId
Body: {
  "eventType": "message.received",
  "webhookUrl": "https://yourplatform.com/webhook"
}
```

### Step 3: Receive Real-time Events
```
Message received in WhatsApp
→ API detects event
→ Sends webhook to your URL with message data
→ Your platform processes the message
```

## Event Types

Your webhooks can listen to:

| Event | Triggered | Payload |
|-------|-----------|---------|
| `message.received` | When someone messages you | Phone, message text, timestamp |
| `message.sent` | When you send a message | Phone, message text, timestamp |
| `contact.added` | When a new contact is added | Phone, name |
| `contact.updated` | When a contact is updated | Phone, name |
| `contact.deleted` | When a contact is deleted | Phone, name |
| `session.authenticated` | When QR is scanned | Phone number |
| `session.disconnected` | When session ends | Reason |

## Quick Start for External Platforms

### 1. Get Session & API Key
You or your user initializes a session and shares:
- `sessionId` - The unique session identifier
- `apiKey` - The authentication key

### 2. Register Your Webhook
```bash
curl -X POST http://yourserver:3000/api/webhooks/SESSION_ID \
  -H "X-API-Key: API_KEY" \
  -d '{
    "eventType": "message.received",
    "webhookUrl": "https://yourplatform.com/whatsapp-webhook"
  }'
```

### 3. Create Webhook Receiver
```javascript
app.post('/whatsapp-webhook', (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'message.received') {
    // Process incoming message
    console.log('New message from', data.from, ':', data.text);
    // Forward to your CRM, chatbot, etc.
  }
  
  res.json({ success: true });
});
```

### 4. Process Events
- Store in database
- Send to CRM system
- Trigger chatbot responses
- Update analytics
- Send notifications

## API Endpoints for Webhooks

```
POST   /api/webhooks/:sessionId              - Register webhook
GET    /api/webhooks/:sessionId              - List webhooks
GET    /api/webhooks/:sessionId/:webhookId   - Get webhook details
PUT    /api/webhooks/:sessionId/:webhookId   - Update webhook
DELETE /api/webhooks/:sessionId/:webhookId   - Delete webhook
POST   /api/webhooks/:sessionId/:webhookId/test - Test webhook
GET    /api/webhooks/:sessionId/:webhookId/logs - View delivery logs
```

## Real-World Example

### Scenario: WhatsApp to CRM Integration

1. **User logs in via QR**
   ```bash
   POST /api/auth/init
   ```

2. **Get QR Code**
   ```bash
   GET /api/auth/SESSION_ID/qr
   ```
   Show QR in web UI, user scans

3. **Register webhook for CRM**
   ```bash
   POST /api/webhooks/SESSION_ID
   {
     "eventType": "message.received",
     "webhookUrl": "https://crm.company.com/api/whatsapp-webhook"
   }
   ```

4. **Customer sends message**
   - Message arrives in WhatsApp
   - System detects event
   - Sends webhook to CRM:
   ```json
   {
     "event": "message.received",
     "data": {
       "from": "919876543210",
       "text": "I want to place an order",
       "timestamp": "2024-01-30T10:05:00Z"
     }
   }
   ```

5. **CRM processes webhook**
   - Creates lead in system
   - Assigns to sales team
   - Sends auto-reply via API:
   ```bash
   POST /api/messages/SESSION_ID/send
   {
     "phone": "919876543210",
     "message": "Thanks for contacting us! We'll respond shortly."
   }
   ```

## Complete API Endpoints

Your platform can use all these endpoints:

### Authentication
- `POST /api/auth/init` - Create new session with QR
- `GET /api/auth/:sessionId/qr` - Get QR code
- `GET /api/auth/:sessionId/status` - Check if authenticated

### Messages
- `POST /api/messages/:sessionId/send` - Send message
- `GET /api/messages/:sessionId/list` - Get all messages
- `GET /api/messages/:sessionId/conversation/:phone` - Get chat history

### Contacts
- `POST /api/contacts/:sessionId` - Add contact
- `GET /api/contacts/:sessionId` - List contacts
- `PUT /api/contacts/:sessionId/:id` - Update contact
- `DELETE /api/contacts/:sessionId/:id` - Delete contact

### Webhooks ⭐
- `POST /api/webhooks/:sessionId` - Register webhook
- `GET /api/webhooks/:sessionId` - List webhooks
- `PUT /api/webhooks/:sessionId/:webhookId` - Update webhook
- `DELETE /api/webhooks/:sessionId/:webhookId` - Delete webhook
- `POST /api/webhooks/:sessionId/:webhookId/test` - Test webhook

## Why This Is Better Than Manual API Calls

### Without Webhooks (Polling)
```
Your app every 5 seconds:
  GET /api/messages/SESSION_ID
  → Wastes bandwidth
  → Delays in processing
  → Scalability issues
```

### With Webhooks (Real-time) ⭐
```
Message received:
  → Instant webhook to your app
  → No polling needed
  → Real-time response
  → Scalable solution
```

## Database Schema Addition

New tables for webhooks:
```sql
CREATE TABLE webhooks (
  id TEXT PRIMARY KEY,
  session_id TEXT,
  event_type TEXT,
  webhook_url TEXT,
  is_active INTEGER,
  created_at DATETIME,
  updated_at DATETIME
);

CREATE TABLE webhook_logs (
  id INTEGER PRIMARY KEY,
  webhook_id TEXT,
  status_code INTEGER,
  message TEXT,
  timestamp DATETIME
);
```

## Files Updated

✅ `src/webhooks.js` - Webhook logic
✅ `src/routes/webhooks.js` - Webhook API endpoints
✅ `src/database.js` - Added webhook tables
✅ `src/index.js` - Added webhook routes
✅ `src/whatsapp.js` - Trigger webhooks on events
✅ `src/routes/contacts.js` - Trigger webhooks on contact events
✅ `WEBHOOKS.md` - Complete webhook documentation

## Testing Your Webhooks

### 1. Create a test endpoint
```javascript
app.post('/test-webhook', (req, res) => {
  console.log('Webhook received:', req.body);
  res.json({ success: true });
});
```

### 2. Register webhook
```bash
curl -X POST http://localhost:3000/api/webhooks/SESSION_ID \
  -H "X-API-Key: API_KEY" \
  -d '{
    "eventType": "message.received",
    "webhookUrl": "http://localhost:3001/test-webhook"
  }'
```

### 3. Send test payload
```bash
curl -X POST http://localhost:3000/api/webhooks/SESSION_ID/WEBHOOK_ID/test \
  -H "X-API-Key: API_KEY"
```

### 4. Check logs
```bash
curl http://localhost:3000/api/webhooks/SESSION_ID/WEBHOOK_ID/logs \
  -H "X-API-Key: API_KEY"
```

## Next Steps

1. **Start the server**
   ```bash
   npm install
   npm start
   ```

2. **Read webhook documentation**
   - See `WEBHOOKS.md` for complete details

3. **Initialize a session**
   - `POST /api/auth/init`
   - Scan QR code

4. **Register a webhook**
   - `POST /api/webhooks/:sessionId`

5. **Build your integration**
   - Receive events from your platform
   - Process and respond

## Summary

You now have a complete **WhatsApp CRM API** with:

✅ QR code authentication (like linked devices)
✅ Session management per user
✅ Webhook system for real-time events
✅ API endpoints for messages, contacts, templates
✅ Professional-grade architecture
✅ Ready for production deployment

This is exactly like WhatsML, Twilio, and other professional services - but under your control!

---

For more details, see:
- `README.md` - Quick start
- `GUIDE.md` - Complete implementation guide
- `WEBHOOKS.md` - Webhook system guide
- `TESTING.md` - API testing examples
