# Payment Gateway Development Documentation

## Overview

NuxSaaS provides a comprehensive payment gateway system that allows developers to create custom payment gateway addons. This document explains how to develop, install, and configure payment gateways for the NuxSaaS platform.

## Table of Contents

1. [Getting Started](#getting-started)
2. [Gateway Structure](#gateway-structure)
3. [Manifest File](#manifest-file)
4. [Gateway Implementation](#gateway-implementation)
5. [Configuration Fields](#configuration-fields)
6. [Webhook Handling](#webhook-handling)
7. [Testing](#testing)
8. [Distribution](#distribution)
9. [Examples](#examples)

## Getting Started

### Prerequisites

- PHP 7.4 or higher
- Basic understanding of payment processing
- Access to payment provider's API documentation
- NuxSaaS development environment

### Development Environment Setup

1. Clone or download NuxSaaS
2. Navigate to `addons/payment_gateways/` directory
3. Create a new folder for your gateway (e.g., `stripe`, `paypal`, `razorpay`)

## Gateway Structure

Each payment gateway addon must follow this directory structure:

```
addons/payment_gateways/your_gateway/
├── manifest.json          # Gateway metadata and configuration
├── Gateway.php            # Main gateway implementation
├── install.php           # Optional installation script
├── README.md             # Gateway documentation
├── assets/               # Optional assets (logos, CSS, JS)
│   ├── logo.png
│   └── config.js
└── languages/            # Optional translations
    ├── en.json
    └── es.json
```

## Manifest File

The `manifest.json` file contains metadata about your gateway:

```json
{
    "name": "Your Gateway Name",
    "description": "Brief description of your payment gateway",
    "version": "1.0.0",
    "author": "Your Name",
    "author_email": "your.email@example.com",
    "website": "https://your-gateway-website.com",
    "min_nuxsaas_version": "1.0.0",
    "requirements": {
        "php": ">=7.4",
        "extensions": ["curl", "json", "openssl"]
    },
    "config_fields": [
        {
            "name": "api_key",
            "label": "API Key",
            "type": "password",
            "required": true,
            "description": "Your gateway API key"
        }
    ],
    "supported_features": [
        "one_time_payments",
        "subscriptions",
        "webhooks",
        "refunds"
    ],
    "webhooks": {
        "events": [
            "payment.completed",
            "payment.failed"
        ]
    }
}
```

### Manifest Fields

- **name**: Display name of your gateway
- **description**: Brief description
- **version**: Semantic version (major.minor.patch)
- **author**: Developer name
- **author_email**: Contact email
- **website**: Gateway or developer website
- **min_nuxsaas_version**: Minimum NuxSaaS version required
- **requirements**: PHP version and required extensions
- **config_fields**: Configuration fields for admin panel
- **supported_features**: List of supported features
- **webhooks**: Webhook events your gateway supports

## Gateway Implementation

Your main gateway class must extend the `BaseGateway` class and implement required methods:

```php
<?php
namespace PaymentGateway\YourGateway;

use PaymentGateway\BaseGateway;
use Exception;

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
    }
}
```

### Required Methods

#### processPayment($data)

Process a payment request.

**Parameters:**
- `$data['payment_id']`: Internal payment ID
- `$data['amount']`: Payment amount
- `$data['user_id']`: User ID making the payment
- `$data['subscription_id']`: Subscription ID (if applicable)
- `$data['return_url']`: Success return URL
- `$data['cancel_url']`: Cancel return URL
- `$data['webhook_url']`: Webhook notification URL

**Returns:**
```php
[
    'success' => true|false,
    'redirect_url' => 'https://gateway.com/checkout/...',  // Optional
    'payment_id' => 'gateway_payment_id',                  // Optional
    'message' => 'Error message if failed'                 // Optional
]
```

#### handleWebhook()

Handle webhook notifications from the payment provider.

**Returns:**
```php
[
    'success' => true|false,
    'message' => 'Status message'
]
```

#### verifyPayment($paymentId)

Verify payment status with the gateway.

**Returns:**
```php
[
    'success' => true|false,
    'status' => 'completed|failed|pending',
    'details' => [...],  // Optional additional details
    'message' => 'Status message'
]
```

#### getConfigFields()

Return configuration fields for the admin panel.

**Returns:**
```php
[
    'field_name' => [
        'label' => 'Field Label',
        'type' => 'text|password|select|checkbox',
        'options' => [...],  // For select type
        'required' => true|false,
        'description' => 'Field description'
    ]
]
```

#### testConnection()

Test connection to the payment gateway.

**Returns:**
```php
[
    'success' => true|false,
    'message' => 'Test result message'
]
```

### Helper Methods (Available from BaseGateway)

#### updatePaymentStatus($paymentId, $status, $details = [])

Update payment status in the database.

#### getPayment($paymentId)

Get payment details from the database.

#### processSubscriptionRenewal($subscriptionId, $paymentId)

Process subscription renewal after successful payment.

#### sendPaymentNotification($paymentId, $status)

Send payment notification email to user.

#### generateHash($data, $secret)

Generate secure hash for payment verification.

#### validateSignature($payload, $signature, $secret)

Validate webhook signature.

## Configuration Fields

Configuration fields are defined in the manifest.json and can be of various types:

### Field Types

#### Text Field
```json
{
    "name": "api_key",
    "label": "API Key",
    "type": "text",
    "required": true,
    "description": "Your gateway API key"
}
```

#### Password Field
```json
{
    "name": "secret_key",
    "label": "Secret Key",
    "type": "password",
    "required": true,
    "description": "Your gateway secret key"
}
```

#### Select Field
```json
{
    "name": "mode",
    "label": "Mode",
    "type": "select",
    "options": {
        "sandbox": "Sandbox",
        "live": "Live"
    },
    "default": "sandbox",
    "required": true
}
```

#### Checkbox Field
```json
{
    "name": "enable_logging",
    "label": "Enable Logging",
    "type": "checkbox",
    "default": false,
    "description": "Enable detailed logging"
}
```

## Webhook Handling

Implement webhook handling to receive real-time payment notifications:

```php
public function handleWebhook()
{
    try {
        // Get webhook payload
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        // Verify webhook signature
        $headers = getallheaders();
        if (!$this->verifyWebhookSignature($input, $headers)) {
            throw new Exception('Invalid webhook signature');
        }
        
        // Process webhook event
        switch ($data['event_type']) {
            case 'payment.completed':
                $this->handlePaymentCompleted($data);
                break;
            case 'payment.failed':
                $this->handlePaymentFailed($data);
                break;
        }
        
        return ['success' => true];
        
    } catch (Exception $e) {
        error_log('Webhook error: ' . $e->getMessage());
        return ['success' => false, 'message' => $e->getMessage()];
    }
}
```

### Webhook URL

Your gateway webhook URL will be:
`https://your-domain.com/payment/webhook?gateway=your_gateway_id`

## Testing

### Test Connection

Implement the `testConnection()` method to verify API credentials:

```php
public function testConnection()
{
    try {
        // Make a test API call
        $response = $this->makeApiCall('/test');
        
        if ($response['success']) {
            return [
                'success' => true,
                'message' => 'Connection successful'
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Connection failed: ' . $response['error']
            ];
        }
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}
```

### Sandbox Mode

Always implement sandbox/test mode for development:

```php
public function __construct($config, $conn)
{
    parent::__construct($config, $conn);
    
    $this->apiUrl = $config['mode'] === 'live' 
        ? 'https://api.gateway.com' 
        : 'https://sandbox.gateway.com';
}
```

## Distribution

### Package Structure

Create a ZIP file with your gateway:

```
your_gateway_v1.0.0.zip
├── manifest.json
├── Gateway.php
├── README.md
└── assets/
    └── logo.png
```

### Installation

Users can install your gateway by:

1. Uploading the ZIP file to `addons/payment_gateways/`
2. Extracting the files
3. Going to Admin > Payment Gateways
4. Installing and configuring the gateway

## Examples

### Basic Payment Processing

```php
public function processPayment($data)
{
    try {
        // Prepare payment data
        $paymentData = [
            'amount' => $data['amount'],
            'currency' => $this->config['currency'] ?? 'USD',
            'return_url' => $data['return_url'],
            'cancel_url' => $data['cancel_url'],
            'webhook_url' => $data['webhook_url']
        ];
        
        // Make API call to create payment
        $response = $this->makeApiCall('/payments', 'POST', $paymentData);
        
        if ($response && $response['status'] === 'created') {
            // Update payment record
            $this->updatePaymentStatus($data['payment_id'], 'processing', [
                'gateway_payment_id' => $response['id'],
                'gateway_response' => $response
            ]);
            
            return [
                'success' => true,
                'redirect_url' => $response['checkout_url']
            ];
        } else {
            throw new Exception('Payment creation failed');
        }
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }
}
```

### Webhook Processing

```php
private function handlePaymentCompleted($data)
{
    $gatewayPaymentId = $data['payment']['id'];
    
    // Find payment in database
    $sql = "SELECT id, subscription_id FROM payments WHERE gateway_payment_id = ?";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute([$gatewayPaymentId]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($payment) {
        // Update payment status
        $this->updatePaymentStatus($payment['id'], 'completed', $data);
        
        // Process subscription renewal if applicable
        if ($payment['subscription_id']) {
            $this->processSubscriptionRenewal(
                $payment['subscription_id'], 
                $payment['id']
            );
        }
        
        // Send notification
        $this->sendPaymentNotification($payment['id'], 'completed');
    }
}
```

## Best Practices

1. **Security**: Always validate webhook signatures
2. **Error Handling**: Implement comprehensive error handling
3. **Logging**: Log important events for debugging
4. **Testing**: Thoroughly test in sandbox mode
5. **Documentation**: Provide clear setup instructions
6. **Validation**: Validate all input data
7. **Timeouts**: Set appropriate API timeouts
8. **Retries**: Implement retry logic for failed API calls

## Support

For questions or issues with payment gateway development:

- Email: support@nuxsaas.com
- Documentation: https://docs.nuxsaas.com
- GitHub: https://github.com/nuxsaas/payment-gateways

## License

Payment gateways should be compatible with NuxSaaS licensing terms.
