# Flutterwave Integration - Quick Start Guide

## ✅ Installation Complete!

Flutterwave has been successfully integrated into your tourism booking system. Here's what was added:

### 📦 Components Added

#### 1. **PaymentController** (`app/Http/Controllers/PaymentController.php`)
- Handles all Flutterwave payment operations
- Manages payment initialization, callbacks, and webhooks
- Verifies payments and updates booking status
- Returns available payment methods

#### 2. **Configuration** (`config/flutterwave.php`)
- Centralized configuration for Flutterwave
- Environment variable handling
- Payment method options
- Webhook settings

#### 3. **Updated Models**
- **Payment Model**: Added `payment_details` JSON casts and new attributes
- **Booking Model**: `payment_method` field support

#### 4. **Routes** (`routes/web.php`)
```php
POST   /payment/{reference}/initialize    - Initialize payment
GET    /payment/callback                   - Handle payment callback
POST   /api/webhooks/flutterwave          - Webhook endpoint
GET    /payment/methods                    - List payment methods
```

#### 5. **Booking Form** (`resources/views/packages/book.blade.php`)
- Payment method selection (Flutterwave vs WhatsApp)
- Real-time price calculation
- Traveler information collection
- User-friendly interface

#### 6. **CSRF Middleware** (`app/Http/Middleware/VerifyCsrfToken.php`)
- Webhook endpoint exempted from CSRF protection
- Secure webhook processing

#### 7. **Database Migration**
- Schema updates for Flutterwave fields
- `payment_details` JSON column
- `payment_method` field

### 🚀 Quick Start (5 minutes)

#### Step 1: Get Flutterwave Credentials
```
1. Visit https://dashboard.flutterwave.com
2. Go to Settings > API Keys
3. Copy your Public Key (pk_...)
4. Copy your Secret Key (sk_...)
```

#### Step 2: Update Environment Variables
```bash
# Edit your .env file:
FLUTTERWAVE_ENABLED=true
FLUTTERWAVE_PUBLIC_KEY=pk_your_key_here
FLUTTERWAVE_SECRET_KEY=sk_your_key_here
FLUTTERWAVE_LOGO_URL=https://your-logo-url.png
FLUTTERWAVE_WEBHOOK_URL=https://your-domain.com/api/webhooks/flutterwave
```

#### Step 3: Run Database Migrations
```bash
php artisan migrate
```

#### Step 4: Configure Webhooks (Flutterwave Dashboard)
```
1. Go to Settings > Webhooks
2. Add new webhook
3. URL: https://your-domain.com/api/webhooks/flutterwave
4. Select "Payment Complete" event
5. Copy webhook secret to .env
```

#### Step 5: Test
```
1. Clear cache: php artisan config:clear
2. Visit a package booking page
3. Select "Flutterwave" payment method
4. Complete a test transaction
```

### 📋 Payment Flow

**User Flow:**
```
Package Page → Select "Book Now" → Booking Form 
  → Select Payment Method (Flutterwave or WhatsApp)
  → Enter Traveler Details
  → Click "Complete Booking"
  → [If Flutterwave] Redirected to Flutterwave payment page
  → Complete payment
  → Redirected back to booking success page
  → Confirmation email sent
```

### 🔒 Security Checklist

- [ ] API keys are in `.env` (not in version control)
- [ ] Using HTTPS for all payment URLs
- [ ] Webhook secret verified in `verifyWebhookSignature()`
- [ ] CSRF protection disabled only for webhook endpoint
- [ ] API responses don't log sensitive data
- [ ] Error messages don't expose sensitive information

### 🧪 Testing

#### Test Cards (Flutterwave)
```
Visa:           4242 4242 4242 4242
Mastercard:     5531 8866 5869 2454
Any Expiry:     09/32
Any CVV:        123
```

#### Test Webhooks
Use a tool like Postman or webhook.site to test webhook delivery:
```bash
curl -X POST https://your-domain.com/api/webhooks/flutterwave \
  -H "Content-Type: application/json" \
  -H "verif-hash: your_webhook_signature" \
  -d '{
    "data": {
      "id": 123456,
      "tx_ref": "PAYXXXXXXXX2026",
      "status": "successful"
    }
  }'
```

### 📊 Database Fields

The `payments` table now includes:
```sql
- payment_details (JSON)      -- Flutterwave transaction details
- payment_method (string)     -- 'flutterwave' or 'whatsapp'
- transaction_id (string)     -- Flutterwave transaction ID
- confirmed_at (timestamp)    -- Payment confirmation time
```

### 🔄 API Endpoints

#### Initialize Payment
```
POST /payment/{payment_reference}/initialize
Response: Redirects to Flutterwave payment page
```

#### Payment Callback
```
GET /payment/callback?status=successful&transaction_id=123&tx_ref=PAYXXXXXXXX2026
Response: Verifies and confirms payment, redirects to success page
```

#### Webhook Handler
```
POST /api/webhooks/flutterwave
Headers: verif-hash (webhook signature)
Body: {
  "data": {
    "id": transaction_id,
    "tx_ref": payment_reference,
    "status": "successful|failed",
    ...
  }
}
```

### 🛠️ Available Methods in PaymentController

```php
// Initialize payment
initializePayment($reference)

// Handle callback from Flutterwave
handleCallback()

// Process webhook from Flutterwave
handleWebhook()

// Get available payment methods
paymentMethods()

// Private helper methods
flutterWaveInitialize($payment)
flutterWaveVerify($transactionId)
verifyWebhookSignature($payload, $signature, $secretKey)
```

### 📞 Support Resources

- **Flutterwave Docs**: https://developer.flutterwave.com
- **API Reference**: https://developer.flutterwave.com/reference
- **Support**: https://support.flutterwave.com
- **Dashboard**: https://dashboard.flutterwave.com

### 🐛 Troubleshooting

#### Webhook Not Received?
- Check webhook URL is publicly accessible
- Verify webhook secret matches
- Check server firewall allows Flutterwave IPs
- Review logs: `storage/logs/laravel.log`

#### Payment Verification Failed?
- Verify API keys are correct
- Check transaction ID format
- Ensure API key has sufficient permissions
- Check network connectivity

#### Redirect Loop?
- Clear cache: `php artisan config:clear`
- Verify callback URL in routes
- Check payment reference format
- Review browser console for errors

### 📚 Documentation

Full documentation available in: `FLUTTERWAVE_SETUP.md`

---

**Status**: ✅ Ready for production after configuring credentials and webhooks
**Version**: 1.0
**Last Updated**: May 2026
