# Flutterwave Payment Integration

## Overview
The Flutterwave integration is fully implemented and operational. It supports multi-currency deposits (NGN, USD, EUR, GBP, etc.) with automatic conversion to NGN for wallet crediting.

## Current Implementation Status ✅

### 1. **Database Schema** (config.php)
- `flutterwave_enabled` - Toggle gateway on/off
- `flutterwave_public_key` - Public API key
- `flutterwave_secret_key` - Secret API key  
- `flutterwave_minimum` - Minimum deposit amount (NGN)
- `flutterwave_default_currency` - Default currency selection

### 2. **Admin Settings** (admin/settings.php)
Located in the Payment Gateways section:
- Enable/disable toggle switch
- Public key input field
- Secret key input field (with show/hide toggle)
- Minimum deposit configuration (₦)
- Default currency dropdown (NGN, USD, EUR, GBP)

### 3. **User Deposit Form** (user/fund-wallet.php)
**Features:**
- Payment method selector with Flutterwave option
- Currency dropdown supporting:
  - NGN (Nigerian Naira)
  - USD (US Dollar)
  - EUR (Euro)
  - GBP (British Pound)
  - KES, GHS, ZAR, CAD, AUD, JPY, CNY, AED, INR (via rate map)
- Real-time minimum validation based on NGN equivalent
- Automatic FX conversion using configurable exchange rates
- Transaction metadata tracking (original amount, currency, converted NGN)

**Payment Flow:**
1. User selects Flutterwave and chooses currency
2. Enters amount in selected currency
3. System converts to NGN equivalent using exchange rates
4. Creates transaction record with metadata
5. Initiates Flutterwave payment via API
6. Redirects user to Flutterwave hosted payment page
7. Supports card, bank transfer, and USSD payment options

**API Integration:**
```php
Endpoint: https://api.flutterwave.com/v3/payments
Method: POST
Headers: Authorization: Bearer {secret_key}
Payload:
- tx_ref (unique transaction reference)
- amount (in selected currency)
- currency (NGN, USD, EUR, GBP, etc.)
- redirect_url (verification endpoint)
- payment_options (card, banktransfer, ussd)
- customer data (email, name, phone)
- metadata (user_id, converted_ngn, source_currency)
```

### 4. **Payment Verification** (user/verify-payment.php)
**Verification Flow:**
1. User redirected back from Flutterwave with transaction reference
2. System queries Flutterwave API to verify payment status
3. Checks transaction is not already processed (prevents double-crediting)
4. Verifies payment status is 'successful' or 'completed'
5. Credits NGN amount to user's wallet (from stored transaction)
6. Awards referral commission on first deposit
7. Updates transaction status and gateway response

**API Integration:**
```php
Endpoint: https://api.flutterwave.com/v3/transactions/verify_by_reference
Method: GET
Headers: Authorization: Bearer {secret_key}
Query: tx_ref={transaction_reference}
Success Statuses: ['successful', 'completed']
```

**Security Features:**
- Transaction locking (FOR UPDATE) prevents race conditions
- Double-processing prevention
- Gateway response logging for audit trail
- Amount stored in NGN regardless of payment currency

## Exchange Rate Configuration

**Default Rates** (in `fund-wallet.php`):
```php
'USD' => 1600.00 NGN  (configurable via usd_to_ngn setting)
'EUR' => 1700.00 NGN
'GBP' => 2000.00 NGN
'KES' => 12.00 NGN
'GHS' => 100.00 NGN
'ZAR' => 85.00 NGN
'CAD' => 1200.00 NGN
'AUD' => 1000.00 NGN
'JPY' => 11.00 NGN
'CNY' => 220.00 NGN
'AED' => 430.00 NGN
'INR' => 20.00 NGN
```

## Configuration Steps

### Admin Setup
1. Navigate to **Admin Panel → Settings → Payment Gateways**
2. Scroll to **Flutterwave** section
3. Toggle **Enable Flutterwave** to ON
4. Enter **Public Key** from Flutterwave dashboard
5. Enter **Secret Key** from Flutterwave dashboard
6. Set **Minimum Deposit** amount in NGN (default: ₦100)
7. Select **Default Currency** (NGN recommended)
8. Click **Save Settings**

### Testing
**Test Mode:**
- Use Flutterwave test keys (FLWPUBK-TEST-... / FLWSECK-TEST-...)
- Test cards: https://developer.flutterwave.com/docs/test-cards

**Live Mode:**
- Use Flutterwave live keys
- Ensure business is verified on Flutterwave dashboard

## Transaction Flow Diagram

```
User Initiates Deposit
         ↓
Selects Flutterwave + Currency
         ↓
Enters Amount (e.g., $10 USD)
         ↓
System Converts to NGN (₦16,000)
         ↓
Creates Transaction Record
         ↓
Calls Flutterwave Payments API
         ↓
User Redirected to Flutterwave
         ↓
User Completes Payment
         ↓
Flutterwave Redirects Back
         ↓
System Verifies with Flutterwave API
         ↓
Credits Wallet in NGN (₦16,000)
         ↓
Processes Referral Commission (if first deposit)
         ↓
Shows Success Message
```

## Key Features

✅ **Multi-Currency Support** - Accept payments in 13+ currencies  
✅ **Automatic Conversion** - FX conversion to NGN handled seamlessly  
✅ **Payment Options** - Card, bank transfer, USSD support  
✅ **Transaction Metadata** - Original amount/currency preserved  
✅ **Double-Credit Prevention** - Transaction locking & status checks  
✅ **Referral Integration** - First deposit commissions work correctly  
✅ **Error Handling** - User-friendly error messages  
✅ **Admin Controls** - Easy enable/disable and configuration  
✅ **Audit Trail** - Full gateway response logging  

## Recommended Updates

### 1. **Dynamic Exchange Rates** (Optional Enhancement)
Currently using hardcoded rates. Consider integrating a rates API:
```php
// Example: Use exchangerate-api.com or similar
function fetch_live_rates($base_currency = 'NGN') {
    $api_url = "https://api.exchangerate-api.com/v4/latest/{$base_currency}";
    $response = file_get_contents($api_url);
    return json_decode($response, true)['rates'];
}
```

### 2. **Add More Currencies to Admin Settings**
Allow admins to configure which currencies to display:
```php
// In settings table
flutterwave_supported_currencies TEXT // JSON: ["NGN","USD","EUR","GBP"]
```

### 3. **Webhook Handler** (Recommended)
Add webhook endpoint for asynchronous payment notifications:
```php
// user/flutterwave-webhook.php
$secret_hash = $site_data['flutterwave_webhook_secret'];
$signature = $_SERVER['HTTP_VERIF-HASH'];
if ($signature === $secret_hash) {
    // Process webhook payload
}
```

### 4. **Transaction Metadata Display**
Show original currency/amount in transaction history:
```php
// In transaction list
if ($metadata = json_decode($txn['metadata'], true)) {
    echo "{$metadata['original_currency']} {$metadata['original_amount']}";
    echo " → NGN {$txn['amount']}";
}
```

### 5. **Rate Markup Configuration**
Allow admins to add FX markup percentage:
```php
// In settings
flutterwave_fx_markup DECIMAL(5,2) DEFAULT 2.00 // 2% markup
```

## Error Messages Reference

| Error | Cause | Solution |
|-------|-------|----------|
| "Flutterwave payments are currently unavailable" | Gateway disabled | Enable in admin settings |
| "Flutterwave is not configured yet" | Missing API keys | Add keys in admin settings |
| "Unable to start Flutterwave payment" | API connection error | Check keys, internet connection |
| "Flutterwave payment could not be confirmed" | Verification failed | User should retry or contact support |
| "Minimum deposit amount is ₦XXX" | Amount below minimum | Increase deposit amount |

## API Documentation

**Flutterwave Docs:** https://developer.flutterwave.com/docs  
**Test Environment:** https://developer.flutterwave.com/docs/test-cards  
**Dashboard:** https://dashboard.flutterwave.com  

## Support

For Flutterwave API issues:
- Email: developers@flutterwavego.com
- Slack: https://bit.ly/34Vkzcg

For platform integration issues:
- Developer: Core Tech Web Design Technology
- WhatsApp: +2349162671360
- Telegram: @jeditech

---

## Summary

The Flutterwave integration is **fully functional** with:
- ✅ Multi-currency deposit support
- ✅ Automatic NGN conversion
- ✅ Payment verification
- ✅ Wallet crediting
- ✅ Referral commission processing
- ✅ Admin configuration interface

No urgent updates required. Optional enhancements listed above can improve functionality further.
