# iPay Payment Gateway Package v1.0

Complete payment processing system for Website Reviewer Script with iPay Africa integration.

## 🚀 Features

- ✅ **Upgrade-Safe Design** - Completely standalone, won't be affected by script updates
- ✅ **iPay Africa Integration** - M-Pesa, Airtel Money, Card payments
- ✅ **Membership Management** - Multiple pricing plans with different features
- ✅ **Automatic Activation** - Memberships activated instantly via IPN
- ✅ **Access Control** - Restrict PDF downloads, comparisons, report limits
- ✅ **Admin Dashboard** - Manage plans, view transactions, revenue reports
- ✅ **Security Features** - Hash verification, CSRF protection, duplicate prevention
- ✅ **Edge Case Handling** - 20+ failure scenarios covered
- ✅ **Cron Automation** - Auto-expire memberships, retry failed IPNs

## 📦 Installation

### Step 1: Upload Package
Upload the entire `ipay_payment_gateway` folder to:
```
/core/plugins/ipay_payment_gateway/
```

### Step 2: Run Installer
Visit in your browser:
```
https://yoursite.com/core/plugins/ipay_payment_gateway/install.php
```

Click "Install Now" and wait for completion.

### Step 3: Configure iPay Credentials
1. Go to **Admin Panel → Payment Settings**
2. Enter your iPay Merchant ID
3. Enter your iPay Secret Key
4. Set Live/Demo mode
5. Save settings

### Step 4: Configure Plans (Optional)
1. Go to **Admin Panel → Membership Plans**
2. Edit existing plans or create new ones
3. Set pricing, duration, features
4. Activate plans

### Step 5: Add Custom Routes (Auto-configured)
The installer automatically adds these routes to `core/routes/custom_router.php`:
```php
$custom_route['pricing'] = 'ipay-pricing';
$custom_route['checkout'] = 'ipay-checkout';
$custom_route['payment/callback'] = 'ipay-callback';
```

### Step 6: Setup Cron Job (Optional but Recommended)
Add to your crontab to run every 5 minutes:
```bash
*/5 * * * * php /path/to/core/plugins/ipay_payment_gateway/cron/payment_processor.php
```

This handles:
- Expiring old memberships
- Retrying failed IPNs
- Marking abandoned payments
- Sending expiry notifications

## 🔧 Configuration

### iPay Settings (Admin Panel → Payment Settings)

| Setting | Description |
|---------|-------------|
| **iPay Merchant ID** | Your iPay vendor/merchant ID |
| **iPay Secret Key** | Your iPay hash key (keep secret!) |
| **Live Mode** | Enable for production, disable for testing |
| **Currency** | KES, USD, etc. |
| **Callback URL** | Auto-configured during installation |
| **Allowed Methods** | mpesa, airtel, card (comma-separated) |
| **Free Reports Limit** | Number of free reports for guests |

### Default Pricing Plans

Three plans are created during installation:

1. **Basic Monthly** - KES 499/month
   - 50 reports per month
   - PDF downloads
   - Email support

2. **Professional Monthly** - KES 1,499/month
   - Unlimited reports
   - PDF downloads
   - Site comparison
   - Priority support

3. **Professional Yearly** - KES 14,990/year
   - All Professional features
   - Save 20%
   - API access (coming soon)

## 📱 How It Works

### For Users

1. User runs website scan (free basic report)
2. To download PDF or access premium features → redirected to Pricing
3. Select plan → Checkout
4. Enter M-Pesa number → Pay via iPay
5. Payment confirmed → Membership activated instantly
6. Full access to reports, PDF downloads, comparisons

### For Admins

1. View all transactions in **Payment Transactions**
2. Monitor revenue in **Payment Reports**
3. Manage pricing in **Membership Plans**
4. Configure iPay in **Payment Settings**
5. Manually verify stuck payments if needed

## 🔐 Security Features

### Hash Verification
All iPay communications verified with HMAC SHA256 signatures

### CSRF Protection
Checkout forms protected against cross-site request forgery

### SQL Injection Prevention
Uses prepared statements and escapeTrim() throughout

### Duplicate Prevention
- Unique order IDs
- Transaction ID uniqueness check
- Idempotent IPN processing

### Amount Validation
Callback amounts verified against database records

## 🛡️ Edge Case Handling

### Covered Scenarios

1. ✅ User closes browser during payment
2. ✅ M-Pesa successful but IPN never fires
3. ✅ IPN fires multiple times (network retry)
4. ✅ Payment success but database insert fails
5. ✅ Partial payment (network timeout)
6. ✅ Double payment by same user
7. ✅ Invalid phone number format
8. ✅ Insufficient M-Pesa balance
9. ✅ Membership expires mid-report view
10. ✅ Admin changes price after payment initiated
11. ✅ Database deadlock during high traffic
12. ✅ iPay API unreachable
13. ✅ SSL certificate error
14. ✅ Free trial abuse (multiple accounts)
15. ✅ Refund requests
16. ✅ Plan deleted but users still active
17. ✅ Time zone issues
18. ✅ IPN replay attack
19. ✅ Hash verification failure
20. ✅ Concurrent payment processing

## 📊 Database Tables

### ipay_membership_plans
Stores pricing plans configured by admin

### ipay_user_memberships
Tracks active subscriptions and usage

### ipay_payment_transactions
Complete payment history with iPay responses

### ipay_settings
System configuration (API keys, settings)

## 🎨 Frontend Pages

- **/pricing** - Display available plans
- **/checkout** - Payment initiation form
- **/payment/callback** - iPay IPN handler
- **/payment/success** - Success page
- **/payment/failed** - Failed payment page

## 👨‍💼 Admin Pages

- **Membership Plans** - CRUD for pricing plans
- **Payment Settings** - iPay configuration
- **Payment Transactions** - View all payments
- **Payment Reports** - Revenue analytics

## 🔄 Access Control

### Free Users
- Limited reports (configurable)
- Basic scan results only
- No PDF downloads
- No comparison feature

### Paid Users
- Unlimited or plan-based reports
- Full detailed reports
- PDF downloads
- Site comparison
- Priority support badge

### Enforcement
Access control hooks intercept:
- PDF generation (`genpdf`, `pdf-domain`)
- Comparison feature (`compare`, `compare-domain`)
- Report viewing (`domain`)

## 🚨 Troubleshooting

### Payment Not Activating

1. Check **Admin → Payment Transactions**
2. Look for transaction status
3. If "success" but no membership → Click "Manual Activate"
4. Check error logs at `/core/logs/error.tdata`

### IPN Not Firing

1. Verify Callback URL in iPay dashboard matches:
   ```
   https://yoursite.com/payment/callback
   ```
2. Check firewall isn't blocking iPay IPs
3. Enable logging and check `/core/logs/`

### Hash Verification Failure

1. Verify Secret Key in **Payment Settings** matches iPay dashboard
2. Check for trailing spaces in settings
3. Ensure Live Mode setting matches iPay environment

## 🔄 Uninstallation

To completely remove the package:

1. Visit: `https://yoursite.com/core/plugins/ipay_payment_gateway/uninstall.php`
2. Confirm uninstallation
3. All tables and plugin entries will be removed
4. **Warning**: Payment history will be permanently deleted!

## 📝 Customization

### Adding Custom Payment Methods

Edit `helpers/ipay_helper.php` and add method support in `ipay_initiate_payment()`

### Changing Plan Features

Admin Panel → Membership Plans → Edit Plan → Modify features

### Custom Email Notifications

Add email sending in `helpers/membership_helper.php` → `ipay_create_membership()`

## 🆘 Support

### Common Issues

**Q: Can I test without real payments?**
A: Yes! Set "Live Mode" to Off in Payment Settings. Use iPay demo credentials.

**Q: How do I refund a payment?**
A: Refunds must be processed through iPay dashboard. Then mark transaction as "refunded" in admin.

**Q: Can I offer free trials?**
A: Yes! Create a plan with KES 0 price and limited duration.

**Q: How do I change the currency?**
A: Edit plans in Admin → Membership Plans → Set currency per plan.

## 📄 File Structure

```
ipay_payment_gateway/
├── install.php                 # Installer
├── uninstall.php              # Uninstaller
├── plugin_main.php            # Plugin entry point
├── README.md                  # This file
├── config/
│   └── package_config.php
├── controllers/               # Frontend controllers
│   ├── pricing.php
│   ├── checkout.php
│   ├── payment_callback.php
│   └── payment_verify.php
├── admin/                     # Admin controllers & views
│   ├── controllers/
│   └── views/
├── views/                     # Frontend views
├── helpers/                   # Helper functions
│   ├── payment_helper.php
│   ├── membership_helper.php
│   └── ipay_helper.php
├── models/                    # Data models
├── database/                  # SQL files
│   ├── install.sql
│   └── uninstall.sql
├── hooks/                     # Integration hooks
│   ├── report_access_hook.php
│   └── profile_hook.php
├── cron/                      # Background jobs
└── assets/                    # CSS & JS
```

## 📅 Version History

### v1.0.0 - Initial Release
- iPay Africa integration
- Membership management
- Access control system
- Admin dashboard
- Full edge case handling

## 📧 Credits

Developed for Website Reviewer Script
iPay Africa Payment Gateway Integration
Copyright © 2025

## ⚖️ License

This package is proprietary software for use with Website Reviewer Script only.
