# NuxSaaS Payment Gateway System

## Overview

The NuxSaaS Payment Gateway System is a comprehensive, extensible payment processing framework that allows ISP administrators to accept payments from customers through multiple payment providers. The system supports addons, making it easy for developers to create custom payment gateway integrations.

## Features

### Core Features
- 🚀 **Multi-Gateway Support** - Support for multiple payment gateways simultaneously
- 🔌 **Plugin Architecture** - Easy addon installation and management
- 💳 **Multiple Payment Methods** - Credit cards, digital wallets, bank transfers, etc.
- 🔄 **Subscription Management** - Automatic renewal processing
- 📊 **Real-time Monitoring** - Payment tracking and analytics
- 🔐 **Secure Processing** - Industry-standard security practices
- 📱 **Responsive Design** - Works on all devices
- 🌐 **Multi-Currency** - Support for different currencies
- 📧 **Email Notifications** - Automatic payment confirmations
- 🔔 **Webhook Support** - Real-time payment status updates

### Supported Payment Gateways
- **PayPal** - PayPal Standard and Express Checkout
- **Stripe** - Credit cards, digital wallets, and more
- **Manual Payments** - For offline payment processing
- **Extensible** - Add any payment gateway through addons

### Developer Features
- 📚 **Comprehensive API** - Well-documented development framework
- 🛠️ **Developer Tools** - Testing utilities and debugging tools
- 📖 **Developer Documentation** - Step-by-step integration guides
- 🎯 **Standardized Interface** - Consistent API across all gateways
- 🧪 **Sandbox Support** - Test mode for development
- 🔍 **Error Handling** - Robust error management and logging

## Installation

### Prerequisites
- PHP 7.4 or higher
- MySQL 5.7 or higher
- HTTPS enabled (required for production)
- cURL extension
- JSON extension

### Database Setup

1. Run the payment gateway database migration:
```sql
mysql -u your_username -p your_database < database/payment_gateways.sql
```

2. Verify tables were created:
- `payment_gateways`
- `payments`
- `subscriptions`
- `subscription_renewals`
- `payment_logs`
- `gateway_transactions`

### System Configuration

1. Ensure the addons directory exists:
```bash
mkdir -p addons/payment_gateways
chmod 755 addons/payment_gateways
```

2. Copy gateway addons to the directory:
```bash
cp -r addons/payment_gateways/paypal /path/to/nuxsaas/addons/payment_gateways/
cp -r addons/payment_gateways/stripe /path/to/nuxsaas/addons/payment_gateways/
```

3. Access the admin panel and navigate to Payment Gateways

## Gateway Management

### Installing a Gateway

1. **Admin Panel Method:**
   - Go to Admin → Payment Gateways
   - Click on an available gateway
   - Click "Install Gateway"
   - Configure the required settings
   - Enable the gateway

2. **Manual Method:**
   - Upload gateway files to `addons/payment_gateways/gateway_name/`
   - Access admin panel to complete installation

### Configuring a Gateway

Each gateway has specific configuration requirements:

#### PayPal Configuration
- **Mode**: Sandbox or Live
- **Client ID**: Your PayPal application client ID
- **Client Secret**: Your PayPal application client secret
- **Currency**: Default payment currency

#### Stripe Configuration
- **Mode**: Test or Live
- **Publishable Key**: Your Stripe publishable key
- **Secret Key**: Your Stripe secret key
- **Webhook Secret**: For webhook verification
- **Currency**: Default payment currency

### Testing Gateways

Use the built-in test function to verify gateway connectivity:

1. Go to Payment Gateways
2. Click "Test" on any configured gateway
3. Verify the connection is successful

## Customer Payment Flow

### Subscription Renewal Process

1. **Customer Initiates Payment:**
   - Customer goes to Payment Center
   - Selects subscription to renew
   - Chooses payment method

2. **Payment Processing:**
   - System creates payment record
   - Redirects to gateway checkout
   - Customer completes payment

3. **Payment Completion:**
   - Gateway sends webhook notification
   - System verifies payment
   - Subscription is renewed
   - Customer receives confirmation email

### Payment Status Flow

```
Pending → Processing → Completed
                   ↘ Failed
                   ↘ Cancelled
```

## API Reference

### Core Classes

#### PaymentGateways Controller
Main controller for gateway management and payment processing.

**Key Methods:**
- `index()` - Display gateway management page
- `install()` - Install a new gateway
- `configure()` - Update gateway configuration
- `processPayment()` - Initiate payment processing
- `webhook()` - Handle webhook notifications

#### BaseGateway Class
Abstract base class that all payment gateways must extend.

**Required Methods:**
- `processPayment($data)` - Process payment request
- `handleWebhook()` - Handle webhook notifications
- `verifyPayment($paymentId)` - Verify payment status
- `getConfigFields()` - Return configuration fields
- `testConnection()` - Test gateway connectivity

### Database Schema

#### payments table
```sql
id              INT(11) PRIMARY KEY
user_id         INT(11) NOT NULL
subscription_id INT(11) NULL
gateway_id      VARCHAR(50) NOT NULL
amount          DECIMAL(10,2) NOT NULL
status          ENUM('pending','processing','completed','failed','cancelled')
gateway_response LONGTEXT
created_at      DATETIME NOT NULL
updated_at      DATETIME NULL
```

#### payment_gateways table
```sql
id          INT(11) PRIMARY KEY
gateway_id  VARCHAR(50) UNIQUE NOT NULL
name        VARCHAR(100) NOT NULL
status      ENUM('active','inactive')
config      LONGTEXT
created_at  DATETIME NOT NULL
updated_at  DATETIME NULL
```

## Developer Guide

### Creating a Custom Gateway

1. **Create Gateway Directory:**
```bash
mkdir addons/payment_gateways/your_gateway
```

2. **Create Required Files:**
- `manifest.json` - Gateway metadata
- `Gateway.php` - Gateway implementation
- `README.md` - Documentation

3. **Implement Gateway Class:**
```php
<?php
namespace PaymentGateway\YourGateway;

use PaymentGateway\BaseGateway;

class Gateway extends BaseGateway
{
    public function processPayment($data) { /* Implementation */ }
    public function handleWebhook() { /* Implementation */ }
    public function verifyPayment($paymentId) { /* Implementation */ }
    public function getConfigFields() { /* Implementation */ }
    public function testConnection() { /* Implementation */ }
}
```

4. **Define Manifest:**
```json
{
    "name": "Your Gateway",
    "description": "Gateway description",
    "version": "1.0.0",
    "config_fields": [...],
    "supported_features": [...]
}
```

### Testing Your Gateway

1. **Use Sandbox Mode:**
   Always implement and test in sandbox/test mode first

2. **Test Connection:**
   Implement robust connection testing

3. **Test Webhooks:**
   Use tools like ngrok for local webhook testing

4. **Error Handling:**
   Implement comprehensive error handling and logging

## Security Considerations

### Best Practices

1. **HTTPS Required:**
   - All payment processing must use HTTPS
   - Redirect HTTP to HTTPS automatically

2. **Webhook Verification:**
   - Always verify webhook signatures
   - Use secret keys for signature validation

3. **Data Protection:**
   - Never store sensitive payment data
   - Use gateway tokens for recurring payments
   - Encrypt configuration data

4. **Input Validation:**
   - Validate all input data
   - Sanitize user inputs
   - Use prepared statements

5. **Error Handling:**
   - Don't expose sensitive information in errors
   - Log errors securely
   - Provide user-friendly error messages

## Troubleshooting

### Common Issues

#### Gateway Installation Failed
- Check file permissions
- Verify manifest.json syntax
- Ensure PHP extensions are installed

#### Payment Processing Errors
- Verify gateway configuration
- Check API credentials
- Review error logs

#### Webhook Not Working
- Verify webhook URL is accessible
- Check webhook signature validation
- Ensure proper HTTP response codes

#### Connection Test Failed
- Verify API credentials
- Check network connectivity
- Review API endpoint URLs

### Debug Mode

Enable debug logging in gateway configuration:
```php
error_reporting(E_ALL);
ini_set('display_errors', 1);
```

### Log Files

Payment gateway logs are stored in:
- `logs/payment_gateways.log`
- `logs/webhooks.log`
- PHP error logs

## Support and Resources

### Documentation
- [Payment Gateway Development Guide](docs/payment-gateway-development.md)
- [API Reference](docs/api-reference.md)
- [Security Guidelines](docs/security.md)

### Community
- GitHub Repository
- Support Forums
- Developer Chat

### Professional Support
- Email: support@nuxsaas.com
- Professional Services Available
- Custom Gateway Development

## Changelog

### Version 1.0.0
- Initial release
- PayPal gateway support
- Stripe gateway support
- Manual payment processing
- Subscription management
- Webhook handling
- Admin interface

## License

This payment gateway system is part of NuxSaaS and follows the same licensing terms.

## Contributing

We welcome contributions! Please see our contributing guidelines for more information.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## Roadmap

### Upcoming Features
- Recurring billing automation
- Payment analytics dashboard
- Multi-currency support enhancement
- Additional payment gateways
- API rate limiting
- Payment scheduling
- Refund management interface

---

For the latest updates and documentation, visit: https://docs.nuxsaas.com/payment-gateways
