# 🌧️ Rainforest Pay Integration for EasyStream

## 📋 **Complete Integration Package**

This is a comprehensive Rainforest Pay integration for EasyStream that provides:

- ✅ **Full Payment Processing** - Donations, tips, and creator monetization
- ✅ **Multiple Payment Methods** - Cards, bank transfers, mobile money, wallets
- ✅ **Secure Webhooks** - Real-time payment notifications
- ✅ **Payout System** - Automated creator payments
- ✅ **Admin Dashboard** - Transaction monitoring and management
- ✅ **User-Friendly Interface** - Modern donation forms and flows

## 🚀 **Quick Setup Guide**

### 1. **Database Setup**
```sql
-- Run the installation SQL
mysql -u your_user -p your_database < install_rainforest.sql
```

### 2. **Configuration**
Edit `config.rainforest.php` with your Rainforest Pay credentials:

```php
'api_key' => 'your_rainforest_api_key',
'secret_key' => 'your_rainforest_secret_key',
'merchant_id' => 'your_merchant_id',
'environment' => 'sandbox', // or 'production'
```

### 3. **Environment Variables** (Recommended)
```bash
# Add to your .env file
RAINFOREST_API_KEY=your_api_key_here
RAINFOREST_SECRET_KEY=your_secret_key_here
RAINFOREST_MERCHANT_ID=your_merchant_id_here
RAINFOREST_ENVIRONMENT=sandbox
RAINFOREST_WEBHOOK_URL=https://yourdomain.com/donations/webhook
RAINFOREST_WEBHOOK_SECRET=your_webhook_secret_here
```

### 4. **Webhook Setup**
Configure your Rainforest Pay webhook URL to:
```
https://yourdomain.com/f_modules/m_frontend/m_donations/rainforest_webhook.php
```

## 📁 **File Structure**

```
f_modules/m_frontend/m_donations/
├── config.rainforest.php          # Configuration settings
├── rainforest_pay.php             # Main payment handler class
├── rainforest_donation_form.php   # User donation interface
├── rainforest_webhook.php         # Webhook processor
├── install_rainforest.sql         # Database setup
└── README_RAINFOREST.md          # This documentation
```

## 🎯 **Integration Points**

### **Donation Form URL**
```
/f_modules/m_frontend/m_donations/rainforest_donation_form.php?streamer=USER_ID
```

### **API Endpoints**
```php
// Create donation
POST /f_modules/m_frontend/m_donations/rainforest_pay.php?action=create_donation

// Process webhook
POST /f_modules/m_frontend/m_donations/rainforest_webhook.php

// Request payout
POST /f_modules/m_frontend/m_donations/rainforest_pay.php?action=request_payout

// Get payment methods
GET /f_modules/m_frontend/m_donations/rainforest_pay.php?action=get_payment_methods
```

## 💳 **Supported Payment Methods**

- **💳 Credit/Debit Cards** - Visa, Mastercard, American Express
- **🏦 Bank Transfers** - Direct bank account transfers
- **📱 Mobile Money** - MTN, Airtel, Vodafone, and other providers
- **👛 Digital Wallets** - PayPal, Apple Pay, Google Pay

## 🔧 **Usage Examples**

### **Basic Donation Processing**
```php
$rainforest = new RainforestPayHandler($class_database);

$result = $rainforest->createDonation(
    $streamer_id = 123,
    $amount = 25.00,
    $donor_name = 'John Doe',
    $message = 'Great content!',
    $payment_method = 'card'
);

if ($result['success']) {
    // Redirect to payment URL
    header('Location: ' . $result['payment_url']);
} else {
    // Handle error
    echo $result['message'];
}
```

### **Payout Request**
```php
$result = $rainforest->requestPayout($streamer_id = 123);

if ($result['success']) {
    echo "Payout of $" . $result['amount'] . " requested successfully";
} else {
    echo "Payout failed: " . $result['message'];
}
```

### **Get Donation History**
```php
$donations = $rainforest->getDonationHistory($streamer_id = 123, $limit = 20);

foreach ($donations as $donation) {
    echo "Donation: $" . $donation['amount'] . " from " . $donation['donor_name'];
}
```

## 🎨 **Frontend Integration**

### **Add Donation Button to Channel Pages**
```html
<a href="/f_modules/m_frontend/m_donations/rainforest_donation_form.php?streamer=<?php echo $streamer_id; ?>" 
   class="donate-btn">
   💖 Donate
</a>
```

### **Add to Video Player**
```html
<button onclick="openDonationForm(<?php echo $streamer_id; ?>)" class="player-donate-btn">
    💰 Support Creator
</button>
```

### **JavaScript Integration**
```javascript
function openDonationForm(streamerId) {
    const url = `/f_modules/m_frontend/m_donations/rainforest_donation_form.php?streamer=${streamerId}`;
    window.open(url, 'donation', 'width=600,height=800,scrollbars=yes');
}
```

## 🔒 **Security Features**

- ✅ **Webhook Signature Verification** - Ensures authentic notifications
- ✅ **Data Encryption** - Sensitive data is encrypted
- ✅ **Rate Limiting** - Prevents abuse and spam
- ✅ **Fraud Detection** - Built-in fraud prevention
- ✅ **Audit Logging** - Complete transaction audit trail

## 📊 **Admin Features**

### **Transaction Monitoring**
```php
// Get platform earnings
$sql = "SELECT SUM(platform_fee) as total_fees FROM donations WHERE status = 'completed'";

// Get top earners
$sql = "SELECT streamer_id, SUM(streamer_amount) as earnings 
        FROM donations 
        WHERE status = 'completed' 
        GROUP BY streamer_id 
        ORDER BY earnings DESC 
        LIMIT 10";
```

### **Payout Management**
```php
// Get pending payouts
$sql = "SELECT * FROM payouts WHERE status = 'pending' ORDER BY created_at ASC";

// Process automatic payouts
$rainforest->processAutomaticPayouts();
```

## 🎯 **Customization Options**

### **Fee Configuration**
```php
// In config.rainforest.php
'platform_fee_percentage' => 2.5,  // 2.5% platform fee
'platform_fee_fixed' => 0.30,      // $0.30 fixed fee
'payout_fee_percentage' => 1.0,     // 1% payout fee
'payout_fee_fixed' => 0.25,         // $0.25 payout fee
```

### **Donation Limits**
```php
'min_donation' => 1.00,     // Minimum $1
'max_donation' => 10000.00, // Maximum $10,000
'min_payout' => 10.00,      // Minimum payout $10
```

### **Payment Methods**
```php
'payment_methods' => [
    'card' => true,           // Enable/disable cards
    'bank_transfer' => true,  // Enable/disable bank transfers
    'mobile_money' => true,   // Enable/disable mobile money
    'wallet' => false         // Enable/disable wallets
]
```

## 🚨 **Error Handling**

The integration includes comprehensive error handling:

- **Invalid amounts** - Validates min/max donation limits
- **Payment failures** - Graceful handling of failed payments
- **Network issues** - Retry logic for API calls
- **Webhook validation** - Signature verification for security
- **Database errors** - Transaction rollback on failures

## 📈 **Analytics & Reporting**

### **Built-in Views**
- `donation_summary` - Overall donation statistics per streamer
- `monthly_donation_stats` - Monthly earnings breakdown

### **Custom Reports**
```sql
-- Top donors
SELECT donor_name, SUM(amount) as total_donated 
FROM donations 
WHERE status = 'completed' 
GROUP BY donor_name 
ORDER BY total_donated DESC;

-- Daily earnings
SELECT DATE(completed_at) as date, SUM(streamer_amount) as earnings 
FROM donations 
WHERE status = 'completed' 
GROUP BY DATE(completed_at) 
ORDER BY date DESC;
```

## 🔧 **Troubleshooting**

### **Common Issues**

1. **Webhook not receiving notifications**
   - Check webhook URL configuration
   - Verify SSL certificate
   - Check firewall settings

2. **Payment failures**
   - Verify API credentials
   - Check environment setting (sandbox/production)
   - Review error logs

3. **Database connection issues**
   - Verify database credentials
   - Check table permissions
   - Run installation SQL

### **Debug Mode**
Enable debug logging in `config.rainforest.php`:
```php
'debug' => true,
'log_level' => 'debug'
```

## 📞 **Support**

For Rainforest Pay specific issues:
- 📧 **Email**: support@rainforestpay.com
- 📚 **Documentation**: https://docs.rainforestpay.com
- 🔧 **API Reference**: https://api.rainforestpay.com/docs

For EasyStream integration issues:
- Check the error logs in `logs/rainforest_pay.log`
- Review webhook logs in `logs/rainforest_webhooks.log`
- Verify database table structure matches installation SQL

## 🎉 **Ready to Go!**

Your Rainforest Pay integration is now complete and ready for production use. The system provides:

- **Seamless donation processing** for creators
- **Multiple payment options** for donors
- **Automated payout system** for creators
- **Complete admin oversight** for platform owners
- **Secure, scalable architecture** for growth

**Happy monetizing!** 💰🚀