# Flutterwave Webhook Setup Guide

## Overview
Webhooks provide a more reliable way to receive payment notifications. Instead of relying only on user redirects, Flutterwave sends a server-to-server notification when a payment is completed.

## Why Use Webhooks?

✅ **More Reliable** - Works even if user closes browser  
✅ **Faster** - Instant notification without waiting for redirect  
✅ **Secure** - Server-to-server communication with signature verification  
✅ **Automatic** - Processes payments even if user doesn't complete redirect  

## Setup Instructions

### 1. Configure Webhook URL in Flutterwave Dashboard

1. Login to [Flutterwave Dashboard](https://dashboard.flutterwave.com)
2. Navigate to **Settings → Webhooks**
3. Add your webhook URL:
   ```
   https://yourdomain.com/user/flutterwave-webhook.php
   ```
4. Copy the **Secret Hash** provided by Flutterwave
5. Select events to receive:
   - ✅ `charge.completed` (required for deposits)
   - ⬜ `transfer.completed` (optional, for payouts)
6. Save settings

### 2. Add Webhook Secret to Database

Run this SQL query (replace `YOUR_SECRET_HASH` with your actual hash):

```sql
UPDATE settings 
SET flutterwave_webhook_secret = 'YOUR_SECRET_HASH_FROM_FLUTTERWAVE'
WHERE id = 1;
```

Or add it via the admin panel (if you add the field to settings page).

### 3. Create Logs Directory

The webhook handler creates logs automatically, but you can pre-create the directory:

```bash
mkdir -p user/logs
chmod 755 user/logs
```

### 4. Test the Webhook

**Using Flutterwave Test Mode:**

1. Make a test deposit using test keys
2. Use test card: `4187427415564246` (any future date, CVV: 123)
3. Check webhook logs:
   ```bash
   tail -f user/logs/flutterwave_webhook.log
   ```

**Manual Test (from command line):**

```bash
curl -X POST https://yourdomain.com/user/flutterwave-webhook.php \
  -H "Content-Type: application/json" \
  -H "verif-hash: YOUR_SECRET_HASH" \
  -d '{
    "event": "charge.completed",
    "data": {
      "id": 12345,
      "tx_ref": "TXN_TEST123",
      "flw_ref": "FLW_REF_123",
      "status": "successful",
      "currency": "NGN",
      "charged_amount": 1000,
      "payment_type": "card",
      "customer": {"email": "test@example.com"}
    }
  }'
```

### 5. Verify Webhook is Working

**Check logs:**
```bash
cat user/logs/flutterwave_webhook.log
```

**Check database:**
```sql
-- View recent webhook-processed transactions
SELECT 
    transaction_ref,
    status,
    amount,
    payment_method,
    gateway_reference,
    updated_at
FROM transactions
WHERE payment_gateway = 'flutterwave'
AND status = 'successful'
ORDER BY updated_at DESC
LIMIT 10;
```

## Webhook Event Flow

```
1. User completes payment on Flutterwave
         ↓
2. Flutterwave sends webhook to your server
         ↓
3. Webhook handler verifies signature
         ↓
4. Calls Flutterwave API to double-check payment
         ↓
5. Credits user wallet in NGN
         ↓
6. Awards referral commission (first deposit)
         ↓
7. Logs all actions
         ↓
8. Returns success response to Flutterwave
```

## Webhook vs Redirect

| Feature | Redirect Only | With Webhook |
|---------|--------------|--------------|
| Reliability | Medium | High |
| Works if user closes browser | ❌ No | ✅ Yes |
| Processing speed | Slower | Faster |
| Duplicate prevention | Manual | Automatic |
| Logging | Basic | Detailed |
| Recommended | For testing | For production |

## Security Features

✅ **Signature Verification** - Validates webhook is from Flutterwave  
✅ **API Double-Check** - Verifies payment status with Flutterwave API  
✅ **Transaction Locking** - Prevents duplicate processing  
✅ **Status Validation** - Only processes successful payments  
✅ **Detailed Logging** - Tracks all webhook activity  

## Troubleshooting

### Webhook Not Receiving Events

**Check 1:** Verify webhook URL is publicly accessible
```bash
curl https://yourdomain.com/user/flutterwave-webhook.php
```

**Check 2:** Verify SSL certificate is valid
```bash
curl -v https://yourdomain.com 2>&1 | grep SSL
```

**Check 3:** Check server logs
```bash
tail -f /var/log/apache2/error.log  # or nginx error log
```

**Check 4:** Verify Flutterwave dashboard shows webhook as active

### Webhook Returns Error

**Check logs:**
```bash
cat user/logs/flutterwave_webhook.log | grep ERROR
```

**Common Errors:**

| Error | Cause | Solution |
|-------|-------|----------|
| "Invalid signature" | Wrong secret hash | Update secret in database |
| "Transaction not found" | tx_ref mismatch | Check transaction_ref in DB |
| "Already processed" | Duplicate webhook | Ignore, this is normal |
| "Database error" | DB connection issue | Check config.php settings |

### Signature Verification Failing

1. Check secret hash in database:
   ```sql
   SELECT flutterwave_webhook_secret FROM settings WHERE id = 1;
   ```

2. Compare with Flutterwave dashboard secret

3. Update if different:
   ```sql
   UPDATE settings 
   SET flutterwave_webhook_secret = 'CORRECT_SECRET_HASH'
   WHERE id = 1;
   ```

### Payments Not Being Credited

**Check webhook logs:**
```bash
grep "Crediting user wallet" user/logs/flutterwave_webhook.log
```

**Check transaction status:**
```sql
SELECT 
    transaction_ref,
    status,
    amount,
    gateway_response,
    updated_at
FROM transactions
WHERE transaction_ref = 'YOUR_TXN_REF';
```

**Check user balance:**
```sql
SELECT id, username, main_balance 
FROM users 
WHERE id = YOUR_USER_ID;
```

## Webhook Payload Example

```json
{
  "event": "charge.completed",
  "data": {
    "id": 285959875,
    "tx_ref": "TXN_ABC123_1234567890",
    "flw_ref": "FLW-MOCK-d80f07c58e62a4dccf69a6dc5d57e4f8",
    "device_fingerprint": "N/A",
    "amount": 1000,
    "currency": "NGN",
    "charged_amount": 1000,
    "app_fee": 14,
    "merchant_fee": 0,
    "processor_response": "Approved",
    "auth_model": "PIN",
    "ip": "102.88.45.123",
    "narration": "CARD Transaction",
    "status": "successful",
    "payment_type": "card",
    "created_at": "2024-01-15T10:30:00.000Z",
    "account_id": 123456,
    "customer": {
      "id": 789012,
      "name": "John Doe",
      "phone_number": "+2348012345678",
      "email": "john@example.com",
      "created_at": "2024-01-01T08:00:00.000Z"
    },
    "card": {
      "first_6digits": "418742",
      "last_4digits": "4246",
      "issuer": "MASTERCARD",
      "country": "NG",
      "type": "DEBIT",
      "expiry": "09/26"
    }
  }
}
```

## Adding Webhook Secret to Admin Panel (Optional)

If you want to manage webhook secret from admin panel:

**1. Add to settings page (`admin/settings.php`):**
```php
<div class="form-group">
  <label for="flutterwave_webhook_secret"><strong>Webhook Secret Hash</strong></label>
  <div class="input-group">
    <input type="password" class="form-control" id="flutterwave_webhook_secret" 
           name="flutterwave_webhook_secret"
           value="<?php echo htmlspecialchars($site_data['flutterwave_webhook_secret'] ?? ''); ?>" 
           placeholder="Webhook secret from Flutterwave dashboard">
    <div class="input-group-append">
      <button class="btn btn-outline-secondary" type="button" 
              onclick="toggleVis('flutterwave_webhook_secret',this)">
        <i class="fas fa-eye"></i>
      </button>
    </div>
  </div>
  <small class="form-text text-muted">
    Copy from Flutterwave Dashboard → Settings → Webhooks
  </small>
</div>
```

**2. Add to update handler (`admin/ajax/update_settings.php`):**
```php
'flutterwave_webhook_secret' => trim($_POST['flutterwave_webhook_secret'] ?? ''),
```

## Monitoring Webhook Activity

**Recent webhook calls:**
```bash
tail -n 100 user/logs/flutterwave_webhook.log
```

**Count successful webhooks today:**
```bash
grep "Transaction processed successfully" user/logs/flutterwave_webhook.log | \
grep "$(date +%Y-%m-%d)" | wc -l
```

**Failed webhooks today:**
```bash
grep "ERROR:" user/logs/flutterwave_webhook.log | grep "$(date +%Y-%m-%d)"
```

## Log Rotation (Recommended)

Create logrotate config to prevent logs from growing too large:

```bash
sudo nano /etc/logrotate.d/flutterwave-webhook
```

```
/path/to/your/user/logs/flutterwave_webhook.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0644 www-data www-data
}
```

## Testing Checklist

- [ ] Webhook URL is publicly accessible
- [ ] SSL certificate is valid
- [ ] Webhook secret is configured in database
- [ ] Logs directory exists and is writable
- [ ] Test deposit with Flutterwave test card
- [ ] Webhook log shows "Transaction processed successfully"
- [ ] User wallet is credited correctly
- [ ] Referral commission awarded (first deposit)
- [ ] Duplicate webhook is handled gracefully

## Production Checklist

- [ ] Use live Flutterwave API keys
- [ ] Use production webhook secret
- [ ] Enable webhook in Flutterwave dashboard
- [ ] Test with small real payment
- [ ] Monitor webhook logs for 24 hours
- [ ] Set up log rotation
- [ ] Document webhook URL for team
- [ ] Add webhook monitoring/alerting

## Support

**Flutterwave Webhook Docs:**  
https://developer.flutterwave.com/docs/integration-guides/webhooks

**Platform Support:**  
- WhatsApp: +2349162671360
- Telegram: @jeditech

---

**Note:** The webhook works alongside the redirect verification. Both methods credit the wallet, but duplicate processing is prevented through transaction locking and status checks.
