# PayGate (Redsys) Settings Configuration

This module provides a comprehensive web-based configuration interface for managing PayGate/Redsys payment gateway settings.

## Features

- **Web-Based Configuration**: Easy-to-use settings screen accessible through the application interface
- **Connection Testing**: Validate your PayGate configuration before processing live payments
- **Environment Management**: Separate sandbox and production environments
- **Secure Storage**: Sensitive data (secret keys) are encrypted in the configuration
- **Real-time Validation**: AJAX-based form validation for immediate feedback

## Accessing Settings

Navigate to: `/NGauge/paygate/settings/index`

Or use the application menu to access **PayGate Settings**.

## Configuration Fields

### API Connection Settings

| Field | Description | Required | Example |
|-------|-------------|----------|---------|
| **Enable PayGate Integration** | Toggle to enable/disable the module | Yes | ✓ |
| **Environment** | Select Sandbox or Production | Yes | Production |
| **Merchant Code (FUC)** | Your merchant identification number | Yes | 999008881 |
| **Terminal Number** | Terminal assigned by your bank | Yes | 001 |
| **Currency Code** | ISO 4217 currency code | Yes | 978 (EUR) |
| **Transaction Type** | Type of transaction to perform | Yes | 0 |
| **Secret Key (SHA-256)** | Encryption key from your bank | Yes | *(encrypted)* |

### Payment Settings

| Field | Description | Default |
|-------|-------------|---------|
| **Auto Capture Payments** | Automatically capture after authorization | Yes |
| **Enable Debug Logging** | Log detailed transaction information | No |

### URL Configuration

| Field | Description | Example |
|-------|-------------|---------|
| **Notification URL** | Webhook endpoint for payment notifications | https://example.com/paygate/notification |
| **Success Return URL** | Redirect URL after successful payment | https://example.com/payment/success |
| **Error Return URL** | Redirect URL after payment failure | https://example.com/payment/error |

## Currency Codes

- **978** - EUR (Euro)
- **826** - GBP (British Pound Sterling)
- **840** - USD (US Dollar)

## Transaction Types

- **0** - Standard Authorization (immediate capture)
- **A** - Pre-authorization (reserve funds)
- **1** - Pre-authorization Confirmation

## Environment Setup

### Sandbox (Testing)

- Use sandbox credentials provided by your bank
- API URL: `https://sis-t.redsys.es:25443/sis/realizarPago`
- Test card numbers available in Redsys documentation
- No real money is charged

### Production (Live)

- Use production credentials from your bank
- API URL: `https://sis.redsys.es/sis/rest/trataPeticionREST`
- Real transactions will be processed
- Real money will be charged to customers

## Testing Connection

1. Fill in all required configuration fields
2. Click the **Test Configuration** button
3. The system will validate:
   - API URL accessibility
   - Merchant code format
   - Terminal number format
   - Currency code format
   - Secret key validity

## Security Considerations

### Data Encryption

Sensitive configuration data is automatically encrypted:
- Secret keys are encrypted using `Security::encryptSensitiveData()`
- Encrypted values are stored in the params configuration file

### Access Control

- Settings page requires authentication
- Only authenticated users can access configuration
- Role-based access control can be added through Yii2's RBAC system

## Configuration Storage

Settings are stored in: `@common/config/params.php`

Example configuration structure:
```php
'paygate' => [
    'enabled' => true,
    'environment' => 'production',
    'merchant_code' => '999008881',
    'terminal' => '001',
    'currency' => '978',
    'transaction_type' => '0',
    'secret_key' => '[ENCRYPTED]',
    'auto_capture' => true,
    'debug' => false,
    'notification_url' => 'https://example.com/paygate/notification',
    'success_url' => 'https://example.com/payment/success',
    'error_url' => 'https://example.com/payment/error',
]
```

## Usage in Code

### Accessing Configuration

```php
// Get PayGate settings
$settings = Yii::$app->params['paygate'];

// Check if enabled
if ($settings['enabled'] ?? false) {
    // PayGate is enabled
}

// Get merchant code
$merchantCode = $settings['merchant_code'];

// Get decrypted secret key
$secretKey = Security::decryptSensitiveData($settings['secret_key']);
```

### Getting API URL

```php
use PortalPeople\paygate\models\Paygate;

$environment = Yii::$app->params['paygate']['environment'] ?? 'production';
$apiUrl = $environment === 'sandbox' 
    ? Paygate::sandboxUrl 
    : Paygate::productionUrl;
```

## API Endpoints

The settings controller provides the following endpoints:

- **GET/POST** `/paygate/settings/index` - Display and save settings
- **POST** `/paygate/settings/validate` - AJAX validation
- **POST** `/paygate/settings/test-connection` - Test configuration

## Troubleshooting

### Connection Test Fails

1. **Verify credentials**: Ensure merchant code and secret key are correct
2. **Check environment**: Make sure you're using the right environment (sandbox/production)
3. **Validate formats**:
   - Merchant code: 1-9 digits
   - Terminal: 1-3 digits
   - Currency: exactly 3 digits
4. **Review firewall**: Ensure your server can connect to Redsys servers

### Settings Not Saving

1. **File permissions**: Check write permissions on `@common/config/params.php`
2. **Validation errors**: Check for form validation messages
3. **Server logs**: Review application logs for error details

### Secret Key Issues

1. **Length**: Secret key should be at least 20 characters
2. **Format**: Typically Base64 encoded
3. **Source**: Obtain from your bank's merchant panel

## Integration with Existing Code

The configuration automatically integrates with the existing Module bootstrap:

```php
// The Module.php bootstrap can now read from params
$settings = Yii::$app->params['paygate'] ?? [];

$app->setComponents(["{$this->id}" => [
    'class' => 'PortalPeople\paygate\Module',
    'connection' => [
        'url' => $settings['environment'] === 'sandbox' 
            ? Paygate::sandboxUrl 
            : Paygate::productionUrl,
        'merchantcode' => $settings['merchant_code'] ?? '',
        'terminal' => $settings['terminal'] ?? '1',
        'currency' => $settings['currency'] ?? '978',
        'transactiontype' => $settings['transaction_type'] ?? '0',
        'secret' => Security::decryptSensitiveData($settings['secret_key'] ?? ''),
    ]
]]);
```

## Resources

- [Redsys Integration Manual](https://sis.redsys.es/sis/Manual/PDF/Manual_integracion_2020_es.pdf)
- [API Documentation](https://pagosonline.redsys.es/conexion-insite.html)
- [Test Environment](https://sis-t.redsys.es:25443/canales/)

## Support

For issues or questions:
- Check application logs: `@app/runtime/logs/`
- Review Redsys documentation
- Contact your bank's technical support for credential issues

## License

MIT License - See LICENSE.md file for details
