# Flutterwave Configuration Guide

## Overview
This guide explains how to configure the Flutterwave payment gateway for card payment processing in the Miss Interschools Donation system.

## Prerequisites
- Active Flutterwave business account (https://dashboard.flutterwave.com)
- API keys (Public Key and Secret Key) from your Flutterwave dashboard

## Setup Steps

### 1. Get Your API Keys
1. Log in to your Flutterwave dashboard: https://dashboard.flutterwave.com
2. Navigate to **Settings** → **API**
3. Copy your **Public Key** (used in frontend)
4. Copy your **Secret Key** (used in backend verification)

### 2. Store API Keys in WordPress
Add the following to your `wp-config.php` file OR use WordPress Settings:

#### Option A: wp-config.php (Recommended for production)
```php
define( 'FLUTTERWAVE_PUBLIC_KEY', 'your_public_key_here' );
define( 'FLUTTERWAVE_SECRET_KEY', 'your_secret_key_here' );
```

#### Option B: WordPress Options Table
Use the WordPress admin panel or wp-cli:

```bash
wp option add flutterwave_public_key "your_public_key_here"
wp option add flutterwave_secret_key "your_secret_key_here"
```

### 3. Configure in PHP
The plugin reads keys using this priority order:
1. `FLUTTERWAVE_PUBLIC_KEY` constant (if defined)
2. `flutterwave_public_key` from wp_options table
3. Falls back to empty if not configured

## Payment Flow

### Card Payments
```
User selects Card
    ↓
Form submitted with donor details
    ↓
Record saved in database (status: 'completed')
    ↓
Flutterwave Public Key retrieved via AJAX
    ↓
Flutterwave modal opens with transaction details
    ↓
User enters card details in secure Flutterwave iframe
    ↓
Payment processed by Flutterwave
    ↓
Flutterwave callback verifies payment (status: 'successful')
    ↓
Backend AJAX confirms with Flutterwave API (/v3/transactions/{id}/verify)
    ↓
Database record status confirmed
    ↓
Campaign donation totals updated
    ↓
Success message shown to user
```

## API Integration Details

### Getting Public Key
- **AJAX Action:** `get_flutterwave_key`
- **Method:** POST (or GET)
- **Response:** `{ "public_key": "PK_...", "error": null }`
- **Handler:** `class-missinterschools-donation.php::get_flutterwave_key()`

### Verifying Payment
- **AJAX Action:** `verify_flutterwave_payment`
- **Method:** POST
- **Parameters:**
  - `record_id`: Donation record ID from database
  - `transaction_id`: Flutterwave transaction ID
  - `tx_ref`: Transaction reference (DONATION_{record_id}_{timestamp})
- **Response:** `{ "success": true, "message": "Payment verified" }` OR error
- **Handler:** `class-missinterschools-donation.php::verify_flutterwave_payment()`

### Flutterwave Verification API
- **Endpoint:** `https://api.flutterwave.com/v3/transactions/{transaction_id}/verify`
- **Method:** GET
- **Authorization:** Bearer {FLUTTERWAVE_SECRET_KEY}
- **Expected Response:**
  ```json
  {
    "status": "success",
    "data": {
      "id": 12345678,
      "tx_ref": "DONATION_42_1699987654",
      "status": "successful",
      "amount": 50000,
      "currency": "UGX"
    }
  }
  ```

## Webhook Configuration (Optional)

For production, consider setting up Flutterwave webhooks for real-time payment notifications:

1. Go to **Settings** → **Webhooks** in Flutterwave dashboard
2. Set webhook URL: `https://yourdomain.com/wp-admin/admin-ajax.php?action=flutterwave_webhook`
3. Subscribe to: `charge.complete` event
4. Implement webhook handler in plugin (optional enhancement)

## Testing

### Test Cards (Sandbox)
Use these test credentials in Flutterwave's sandbox mode:

**Successful Payment:**
- Card: 4242 4242 4242 4242
- Expiry: 12/25
- CVV: 123

**Declined Payment:**
- Card: 5555 5555 5555 4444
- Expiry: 12/25
- CVV: 123

### Test Mode
To use test keys instead of live:
1. Get test keys from Flutterwave dashboard (toggle "Live Mode" off)
2. Update configuration with test keys
3. Payments will not be charged

## Troubleshooting

### "Failed to get Flutterwave public key"
- Check that `flutterwave_public_key` is set in wp_options
- Verify AJAX endpoint is accessible: `POST /wp-admin/admin-ajax.php?action=get_flutterwave_key`
- Check browser console for AJAX errors

### "Payment verification failed"
- Verify `flutterwave_secret_key` is set in wp_options
- Check that transaction ID is correct
- Verify Flutterwave API is accessible (check firewall/SSL)
- Enable debugging: Check WordPress debug logs

### "Transaction reference mismatch"
- Ensure tx_ref format is: `DONATION_{record_id}_{timestamp}`
- Check that record_id matches database record
- Verify client-side timestamp is in milliseconds

### SSL Certificate Errors
The plugin has SSL verification disabled for development:
```php
'sslverify' => false  // In wp_remote_get() for API calls
```
For production, enable SSL verification and use valid certificates.

## Currency

All transactions are processed in **UGX (Uganda Shilling)**.
- Amounts sent to Flutterwave should be in UGX cents (smallest currency unit)
- Example: 50,000 UGX = amount should be 5000000 (in cents)

## Database Fields

Donation records include Flutterwave payment data:
- `transaction_id`: Flutterwave transaction ID
- `status`: 'pending', 'completed', or 'failed'
- `payment_method`: 'card' for Flutterwave payments
- `donor_name`: Full name of donor
- `donor_phone`: Mobile number of donor
- `donation_amount`: Amount in UGX

## Security Considerations

1. **Never expose Secret Key**: Only use on server side
2. **Public Key is safe**: Can be included in frontend code
3. **SSL Verification**: Enabled in production (set `'sslverify' => true`)
4. **NONCE Verification**: Add WordPress nonces to AJAX calls for production
5. **Rate Limiting**: Consider adding rate limiting to payment endpoints
6. **Input Validation**: All user inputs are validated before processing

## Support

For Flutterwave API support: https://support.flutterwave.com
For plugin support: Contact development team

## References

- [Flutterwave API Docs](https://developer.flutterwave.com/docs/)
- [Flutterwave v3 Checkout](https://developer.flutterwave.com/docs/flutterwave-checkout/v3/)
- [Payment Verification](https://developer.flutterwave.com/docs/apis/payments-query-transactions/)
