# Webhook Implementation Guide for XChange Registration System

This guide explains how to set up and use the webhook system to receive real-time notifications about registration events.

## Overview

The webhook system automatically sends HTTP POST requests to configured endpoints whenever specific events occur in the registration system. This enables real-time integration with external systems, CRMs, analytics platforms, or custom applications.

## Features

- **Real-time notifications** for registration events
- **HMAC signature verification** for security
- **Configurable retry logic** with exponential backoff
- **Comprehensive logging** for monitoring and debugging
- **Admin interface** for easy configuration and testing
- **Multiple event types** support

## Supported Events

### 1. `registration_created`
Triggered when a new registration is submitted.

**Payload:**
```json
{
  "event": "registration_created",
  "timestamp": "2025-01-27T10:30:00+00:00",
  "data": {
    "registration_number": "XCHANGE2025-001",
    "contact_name": "John Doe",
    "contact_email": "john@university.edu",
    "university": "University of Example",
    "delegate_count": 3,
    "total_amount": 1650.00,
    "payment_method": "gateway",
    "created_at": "2025-01-27T10:30:00+00:00"
  },
  "webhook_id": "wh_65b8f8c8e4b0a"
}
```

### 2. `payment_status_changed`
Triggered when payment status is updated (paid, failed, cancelled, etc.).

**Payload:**
```json
{
  "event": "payment_status_changed",
  "timestamp": "2025-01-27T10:35:00+00:00",
  "data": {
    "registration_number": "XCHANGE2025-001",
    "payment_status": "paid",
    "payment_method": "gateway",
    "gateway_transaction_id": "pi_1234567890",
    "amount_paid": 1650.00,
    "currency": "usd",
    "updated_at": "2025-01-27T10:35:00+00:00"
  },
  "webhook_id": "wh_65b8f8c8e4b0b"
}
```

### 3. `registration_updated`
Triggered when registration details are modified by admin users.

### 4. `delegate_added`
Triggered when new delegates are added to existing registrations.

### 5. `registration_cancelled`
Triggered when registrations are cancelled.

## Setup Instructions

### Step 1: Database Setup

Run the SQL script to create the webhook tables and default settings:

```sql
-- Run this file: sql/create_webhook_tables.sql
```

### Step 2: Configure Webhook Settings

1. **Access Admin Panel**: Navigate to `Settings > Webhook Settings`
2. **Enable Webhooks**: Set "Enable Webhooks" to "Enabled"
3. **Configure Endpoint**: Enter your webhook URL (e.g., `https://your-domain.com/webhook`)
4. **Set Secret Key**: Create a secure secret key for HMAC signature verification
5. **Select Events**: Choose which events should trigger webhooks
6. **Configure Retry Settings**: Set retry count and timeout values
7. **Save Settings**: Click "Update Webhook Settings"

### Step 3: Test Configuration

1. **Send Test Webhook**: Use the "Send Test Webhook" button to verify your endpoint
2. **Check Logs**: View webhook delivery status in `Settings > Webhook Logs`
3. **Verify Response**: Ensure your endpoint returns HTTP 200-299 for successful processing

## Webhook Endpoint Implementation

### Basic Endpoint Example (PHP)

```php
<?php
// webhook_endpoint.php

// Get the webhook payload
$payload = file_get_contents('php://input');
$headers = getallheaders();

// Verify HMAC signature
$webhookSecret = 'your_webhook_secret_here';
$signature = $headers['X-Webhook-Signature'] ?? '';
$expectedSignature = hash_hmac('sha256', $payload, $webhookSecret);

if (!hash_equals($expectedSignature, $signature)) {
    http_response_code(401);
    exit('Unauthorized');
}

// Parse the payload
$data = json_decode($payload, true);

// Process the webhook based on event type
switch ($data['event']) {
    case 'registration_created':
        handleRegistrationCreated($data['data']);
        break;
        
    case 'payment_status_changed':
        handlePaymentStatusChanged($data['data']);
        break;
        
    default:
        // Handle unknown events
        break;
}

// Return success response
http_response_code(200);
echo json_encode(['status' => 'success']);

function handleRegistrationCreated($data) {
    // Process new registration
    // e.g., create customer in CRM, send to analytics, etc.
    error_log("New registration: " . $data['registration_number']);
}

function handlePaymentStatusChanged($data) {
    // Process payment status change
    // e.g., update CRM, trigger workflows, etc.
    error_log("Payment status changed: " . $data['registration_number'] . " -> " . $data['payment_status']);
}
?>
```

### Node.js/Express Example

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

app.use(express.json());

app.post('/webhook', (req, res) => {
    const payload = JSON.stringify(req.body);
    const signature = req.headers['x-webhook-signature'];
    const webhookSecret = 'your_webhook_secret_here';
    
    // Verify HMAC signature
    const expectedSignature = crypto
        .createHmac('sha256', webhookSecret)
        .update(payload)
        .digest('hex');
    
    if (signature !== expectedSignature) {
        return res.status(401).json({ error: 'Unauthorized' });
    }
    
    // Process webhook
    const { event, data } = req.body;
    
    switch (event) {
        case 'registration_created':
            console.log('New registration:', data.registration_number);
            break;
            
        case 'payment_status_changed':
            console.log('Payment status changed:', data.registration_number, data.payment_status);
            break;
    }
    
    res.json({ status: 'success' });
});

app.listen(3000, () => {
    console.log('Webhook endpoint listening on port 3000');
});
```

## Security Considerations

### HMAC Signature Verification

All webhooks include an `X-Webhook-Signature` header containing an HMAC-SHA256 signature. Always verify this signature to ensure webhook authenticity:

```php
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$expectedSignature = hash_hmac('sha256', $payload, $webhookSecret);

if (!hash_equals($expectedSignature, $signature)) {
    http_response_code(401);
    exit('Unauthorized');
}
```

### Best Practices

1. **Use HTTPS**: Always use HTTPS endpoints for production
2. **Validate Payload**: Verify payload structure and data types
3. **Idempotency**: Handle duplicate webhooks gracefully
4. **Rate Limiting**: Implement rate limiting if needed
5. **Logging**: Log all webhook attempts for debugging

## Monitoring and Troubleshooting

### Webhook Logs

Access webhook delivery status in the admin panel:
- **Settings > Webhook Logs**: View all webhook attempts
- **Filter by Event**: Filter logs by event type, status, or date
- **Response Details**: View full response and error messages

### Common Issues

1. **Webhook Not Received**
   - Check if webhooks are enabled
   - Verify webhook URL is accessible
   - Check firewall/network settings

2. **Signature Verification Failed**
   - Ensure webhook secret matches
   - Check for URL encoding issues
   - Verify HMAC implementation

3. **Timeout Errors**
   - Increase timeout setting if needed
   - Optimize endpoint response time
   - Check server performance

4. **Retry Failures**
   - Review retry count setting
   - Check endpoint availability
   - Monitor server logs

### Testing

1. **Local Testing**: Use tools like ngrok for local development
2. **Test Endpoint**: Use the built-in test webhook feature
3. **Log Analysis**: Review webhook logs for delivery status
4. **Endpoint Monitoring**: Monitor your endpoint for incoming requests

## Configuration Options

### Webhook Settings

| Setting | Description | Default | Range |
|---------|-------------|---------|-------|
| `webhook_enabled` | Enable/disable webhooks | false | true/false |
| `webhook_url` | Endpoint URL | - | Valid URL |
| `webhook_secret` | HMAC secret key | - | 32+ characters |
| `webhook_events` | Enabled events | All events | Array of event names |
| `webhook_retry_count` | Retry attempts | 3 | 0-10 |
| `webhook_timeout` | Request timeout | 30 | 5-120 seconds |

### Event Configuration

Events can be individually enabled/disabled:
- `registration_created`: New registrations
- `payment_status_changed`: Payment updates
- `registration_updated`: Registration modifications
- `delegate_added`: Delegate additions
- `registration_cancelled`: Registration cancellations

## Integration Examples

### CRM Integration

```php
function handleRegistrationCreated($data) {
    // Create customer in CRM
    $crmData = [
        'name' => $data['contact_name'],
        'email' => $data['contact_email'],
        'company' => $data['university'],
        'custom_fields' => [
            'registration_number' => $data['registration_number'],
            'delegate_count' => $data['delegate_count'],
            'total_amount' => $data['total_amount']
        ]
    ];
    
    // Send to CRM API
    createCustomerInCRM($crmData);
}
```

### Analytics Integration

```php
function handlePaymentStatusChanged($data) {
    // Track payment conversion
    $analyticsData = [
        'event' => 'payment_completed',
        'properties' => [
            'registration_number' => $data['registration_number'],
            'amount' => $data['amount_paid'],
            'currency' => $data['currency']
        ]
    ];
    
    // Send to analytics service
    trackEvent($analyticsData);
}
```

### Workflow Automation

```php
function handleRegistrationCreated($data) {
    // Trigger automated workflows
    if ($data['delegate_count'] > 5) {
        // Large group registration
        triggerLargeGroupWorkflow($data);
    }
    
    if ($data['payment_method'] === 'tt') {
        // Bank transfer - send payment instructions
        triggerPaymentInstructionsWorkflow($data);
    }
}
```

## Support and Maintenance

### Regular Tasks

1. **Monitor Logs**: Check webhook logs regularly for failures
2. **Update Secrets**: Rotate webhook secrets periodically
3. **Test Endpoints**: Verify endpoint functionality after changes
4. **Review Events**: Adjust enabled events based on needs

### Troubleshooting Checklist

- [ ] Webhooks enabled in admin panel
- [ ] Valid webhook URL configured
- [ ] Webhook secret set and matches endpoint
- [ ] Endpoint accessible and responding
- [ ] Endpoint returning HTTP 200-299
- [ ] No firewall/network blocking
- [ ] HMAC signature verification working
- [ ] Endpoint handling all event types

For additional support, check the webhook logs in the admin panel or contact your system administrator.
