# Flutterwave Payment Integration Guide

This documentation covers the Flutterwave payment gateway integration for the Tourism Booking System.

## Overview

Flutterwave is now integrated as a payment method for package bookings, alongside the existing WhatsApp payment option. Users can choose their preferred payment method during checkout.

## Features

- ✅ Real-time payment processing
- ✅ Multiple payment options (Card, Bank Transfer, USSD, Mobile Money)
- ✅ Secure payment gateway
- ✅ Webhook support for real-time payment updates
- ✅ Refund functionality
- ✅ Payment verification
- ✅ Backward compatible with WhatsApp payments

## Setup Instructions

### 1. Get Flutterwave Credentials

1. Visit [Flutterwave Dashboard](https://dashboard.flutterwave.com)
2. Sign up or log in to your account
3. Navigate to **Settings > API Keys**
4. Copy your:
   - **Public Key** (starts with `pk_`)
   - **Secret Key** (starts with `sk_`)

### 2. Configure Environment Variables

Add the following to your `.env` file:

```env
# Flutterwave Configuration
FLUTTERWAVE_ENABLED=true
FLUTTERWAVE_PUBLIC_KEY=pk_your_public_key_here
FLUTTERWAVE_SECRET_KEY=sk_your_secret_key_here
FLUTTERWAVE_LOGO_URL=https://your-logo-url.png
FLUTTERWAVE_WEBHOOK_URL=https://your-domain.com/api/webhooks/flutterwave
FLUTTERWAVE_WEBHOOK_SECRET=your_webhook_secret_here
```

### 3. Set Up Webhooks

1. Go to **Settings > Webhooks** in Flutterwave Dashboard
2. Add a new webhook with URL: `https://your-domain.com/api/webhooks/flutterwave`
3. Select events: **Payment Complete**
4. Copy the webhook secret and add to `.env`

### 4. Run Database Migrations

```bash
php artisan migrate
```

This creates/updates the necessary database columns for Flutterwave integration.

### 5. Update Booking Form

Update your booking form to include payment method selection:

```blade
<div class="payment-method-selection">
    <label>Select Payment Method:</label>
    <input type="radio" name="payment_method" value="flutterwave" required>
    <label>Flutterwave (Card, Bank Transfer, USSD, Mobile Money)</label>
    
    <input type="radio" name="payment_method" value="whatsapp">
    <label>WhatsApp (Manual Confirmation)</label>
</div>
```

## API Endpoints

### Initialize Payment
- **Route**: `POST /payment/{reference}/initialize`
- **Description**: Initializes a payment with Flutterwave
- **Parameters**: Payment reference
- **Response**: Redirects to Flutterwave payment page

### Payment Callback
- **Route**: `GET /payment/callback`
- **Description**: Handles payment completion callback from Flutterwave
- **Parameters**: `status`, `transaction_id`, `tx_ref`

### Webhook Handler
- **Route**: `POST /api/webhooks/flutterwave`
- **Description**: Receives real-time payment updates from Flutterwave
- **Header Required**: `verif-hash` (webhook signature)

### Get Payment Methods
- **Route**: `GET /payment/methods`
- **Description**: Returns available payment methods
- **Response**: JSON with payment methods list

## Payment Flow

### Flutterwave Payment Flow

1. User fills out booking form and selects **Flutterwave** as payment method
2. Booking is created with status `pending` and payment status `pending`
3. User is redirected to `/payment/{reference}/initialize`
4. Payment controller initializes Flutterwave transaction
5. User is redirected to Flutterwave payment page
6. User completes payment on Flutterwave
7. Flutterwave redirects back to `/payment/callback`
8. System verifies payment with Flutterwave
9. Payment status is updated to `completed`
10. Booking status is updated to `confirmed`
11. User is redirected to booking success page
12. Confirmation email is sent

### Webhook Flow

1. Flutterwave sends payment update via webhook
2. System verifies webhook signature
3. Payment status is updated
4. Booking is confirmed if payment is successful

## Database Schema

### payments table additions

```sql
- payment_details (JSON) - Stores Flutterwave transaction details
- payment_method (string) - 'flutterwave' or 'whatsapp'
- transaction_id (string) - Flutterwave transaction ID
```

## Payment Methods Supported

Flutterwave supports multiple payment methods:

- 💳 **Card** (Visa, Mastercard, American Express)
- 🏦 **Bank Transfer**
- 📱 **USSD** (Unstructured Supplementary Service Data)
- 💰 **Mobile Money**
  - Ghana Mobile Money
  - Rwanda Mobile Money
  - Kenya Mobile Money
  - Uganda Mobile Money

## Testing

### Test Credentials

For testing, you can use Flutterwave's test keys:

1. Get test keys from Flutterwave Dashboard (switch to test mode)
2. Use test payment cards provided by Flutterwave
3. Process payments in test environment

### Test Cards

```
Card Number: 4242 4242 4242 4242
Expiry: Any future date (e.g., 09/32)
CVV: Any 3 digits (e.g., 123)
```

## Security Considerations

1. **API Keys**: Never commit API keys to version control. Use `.env` files only.
2. **HTTPS**: Always use HTTPS in production for payment endpoints.
3. **Webhook Verification**: Verify webhook signatures using HMAC-SHA256.
4. **CSRF**: Webhook endpoint is excluded from CSRF protection (configured in middleware).
5. **Rate Limiting**: Implement rate limiting on webhook endpoint in production.
6. **Logging**: Sensitive payment data is not logged. Only transaction IDs and status are logged.

## Error Handling

### Common Errors

| Error | Cause | Solution |
|-------|-------|----------|
| Invalid API Key | Missing or incorrect credentials | Check .env file, regenerate keys |
| Payment Failed | User declined or card declined | Inform user to try again or use different method |
| Webhook Verification Failed | Invalid signature | Check webhook secret matches |
| Transaction Not Found | Invalid transaction ID | Verify transaction ID format |

### Debugging

Enable debug logging in `.env`:

```env
APP_DEBUG=true
LOG_LEVEL=debug
```

Check logs in `storage/logs/laravel.log`

## Refund Process

Refunds can be initiated via the Payment model:

```php
$payment = Payment::find($paymentId);
$payment->refund(); // Full refund

// Or through Flutterwave service
$flutterWaveService = new FlutterWaveService();
$result = $flutterWaveService->refundTransaction($transactionId);
```

## Customer Communication

### Email Templates

Update your email templates to include payment method information:

```blade
@if($payment->payment_method === 'flutterwave')
    <p>You can track your payment status in your account dashboard.</p>
@else
    <p>Please complete payment via WhatsApp using the link provided.</p>
@endif
```

### Payment Status Messages

- **Pending**: Payment is awaiting completion
- **Processing**: Payment is being processed
- **Completed**: Payment successful
- **Failed**: Payment failed, please try again
- **Refunded**: Payment has been refunded

## Support and Troubleshooting

### Common Issues

**Q: Webhook not being received**
- A: Check webhook URL is accessible and HTTPS
- A: Verify webhook secret in Flutterwave dashboard
- A: Check server firewall allows Flutterwave IPs

**Q: Payment not updating after completion**
- A: Check webhook configuration
- A: Verify API key is correct
- A: Check server logs for errors

**Q: Users seeing redirect loop**
- A: Clear browser cache
- A: Check callback URL is correct
- A: Verify payment reference format

### Contact Support

- **Flutterwave Support**: [https://support.flutterwave.com](https://support.flutterwave.com)
- **Documentation**: [https://developer.flutterwave.com](https://developer.flutterwave.com)

## Useful Resources

- [Flutterwave API Documentation](https://developer.flutterwave.com/reference)
- [Flutterwave Dashboard](https://dashboard.flutterwave.com)
- [Payment Processing Best Practices](https://developer.flutterwave.com/docs/integration-guide/)

## Version Information

- **Integration Version**: 1.0
- **Laravel Version**: 12.0+
- **Flutterwave API**: v3
- **Last Updated**: May 2026

## Changelog

### v1.0 (Initial Release)
- Flutterwave payment gateway integration
- Support for multiple payment methods
- Webhook handling for real-time updates
- Refund functionality
- Backward compatibility with WhatsApp payments
