# API Documentation

## Overview

The RedPay plugin integrates with RedPay’s API to process payments. For full endpoint URLs, request/response formats, and authentication, see **RedPay’s official documentation**: [https://gateway-documentation.redpay.africa/#/](https://gateway-documentation.redpay.africa/#/).

This document describes the integration patterns and data the plugin sends; actual API base URLs and paths are defined by RedPay.

### Authentication

All API requests require authentication using API keys:

```http
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

## Payment Processing

### Create Payment

**Endpoint**: `POST /payments`

Creates a new payment transaction.

**Request Body**:
```json
{
    "amount": 29.99,
    "currency": "USD",
    "order_id": "wc_order_123",
    "customer_email": "customer@example.com",
    "customer_name": "John Doe",
    "card_number": "4111111111111111",
    "card_expiry": "12/25",
    "card_cvc": "123",
    "billing_address": {
        "line1": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "postal_code": "12345",
        "country": "US"
    },
    "metadata": {
        "woocommerce_order_id": "123",
        "customer_id": "456"
    }
}
```

**Success Response** (200):
```json
{
    "status": "success",
    "transaction_id": "txn_1234567890",
    "amount": 29.99,
    "currency": "USD",
    "created_at": "2024-01-15T10:30:00Z",
    "payment_method": {
        "type": "credit_card",
        "last4": "1111",
        "brand": "visa"
    }
}
```

**Error Response** (400):
```json
{
    "status": "error",
    "error_code": "invalid_card",
    "message": "The provided card number is invalid",
    "details": {
        "field": "card_number",
        "code": "invalid_format"
    }
}
```

### Get Payment Status

**Endpoint**: `GET /payments/{transaction_id}`

Retrieves the current status of a payment.

**Response**:
```json
{
    "transaction_id": "txn_1234567890",
    "status": "completed",
    "amount": 29.99,
    "currency": "USD",
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:31:00Z",
    "order_id": "wc_order_123"
}
```

## Refund Processing

### Create Refund

**Endpoint**: `POST /refunds`

Creates a refund for a completed payment.

**Request Body**:
```json
{
    "transaction_id": "txn_1234567890",
    "amount": 15.00,
    "reason": "Customer requested refund",
    "metadata": {
        "refund_type": "partial",
        "woocommerce_refund_id": "789"
    }
}
```

**Response**:
```json
{
    "status": "success",
    "refund_id": "rfnd_0987654321",
    "transaction_id": "txn_1234567890",
    "amount": 15.00,
    "currency": "USD",
    "status": "completed",
    "created_at": "2024-01-15T14:30:00Z"
}
```

## Webhooks

### Webhook Events

The API sends webhooks for the following events:

- `payment.completed` - Payment successfully processed
- `payment.failed` - Payment failed to process
- `payment.cancelled` - Payment was cancelled
- `refund.completed` - Refund successfully processed
- `refund.failed` - Refund failed to process

### Webhook Payload

**Payment Completed**:
```json
{
    "event": "payment.completed",
    "data": {
        "transaction_id": "txn_1234567890",
        "order_id": "wc_order_123",
        "amount": 29.99,
        "currency": "USD",
        "status": "completed",
        "created_at": "2024-01-15T10:30:00Z",
        "payment_method": {
            "type": "credit_card",
            "last4": "1111",
            "brand": "visa"
        }
    },
    "created_at": "2024-01-15T10:31:00Z"
}
```

### Webhook Verification

Webhooks are signed using HMAC SHA256:

```php
function verify_webhook_signature($payload, $signature, $secret) {
    $expected = hash_hmac('sha256', $payload, $secret);
    return hash_equals($expected, $signature);
}
```

The signature is sent in the `X-Webhook-Signature` header.

## Error Handling

### Error Codes

| Code | Description |
|------|-------------|
| `invalid_api_key` | API key is invalid or missing |
| `insufficient_funds` | Card has insufficient funds |
| `invalid_card` | Card number is invalid |
| `expired_card` | Card has expired |
| `invalid_cvc` | CVC code is invalid |
| `card_declined` | Card was declined by issuer |
| `processing_error` | General processing error |
| `rate_limited` | Too many requests |
| `service_unavailable` | Service temporarily unavailable |

### HTTP Status Codes

- `200` - Success
- `400` - Bad Request (invalid parameters)
- `401` - Unauthorized (invalid API key)
- `402` - Payment Required (insufficient funds)
- `404` - Not Found (resource doesn't exist)
- `429` - Rate Limited
- `500` - Internal Server Error
- `503` - Service Unavailable

## Rate Limits

API requests are rate limited:

- **Test Environment**: 100 requests per minute
- **Live Environment**: 1000 requests per minute

Rate limit headers are included in responses:
- `X-RateLimit-Limit` - Request limit per window
- `X-RateLimit-Remaining` - Remaining requests in window
- `X-RateLimit-Reset` - Time when window resets

## Testing

### Test Cards

Use these card numbers in test mode:

**Successful Cards**:
- Visa: `4111111111111111`
- Mastercard: `5555555555554444`
- American Express: `378282246310005`
- Discover: `6011111111111117`

**Error Cards**:
- Declined: `4000000000000002`
- Insufficient Funds: `4000000000009995`
- Expired Card: `4000000000000069`
- Processing Error: `4000000000000119`

### Test Scenarios

**Testing**:

Use RedPay’s test mode and test cards as described in [RedPay documentation](https://gateway-documentation.redpay.africa/#/). The plugin uses RedPay’s API for payment verification and refunds; direct `curl` examples depend on RedPay’s current endpoints and are not reproduced here.

## WordPress Integration

### Plugin API Methods

The plugin provides these methods for developers:

```php
// Get gateway instance
$gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];

// Process payment
$result = $gateway->process_payment($order_id);

// Process refund
$result = $gateway->process_refund($order_id, $amount, $reason);

// Make API request
$response = $gateway->make_api_request('POST', '/payments', $data);
```

### Custom Hooks

**Filter payment data before API call**:
```php
add_filter('redpay_payment_gateway_api_request_data', function($data, $order) {
    // Modify payment data
    $data['custom_field'] = 'custom_value';
    return $data;
}, 10, 2);
```

**Action after successful payment**:
```php
add_action('redpay_payment_gateway_payment_complete', function($order, $transaction_id) {
    // Custom logic after payment
    update_post_meta($order->get_id(), '_custom_transaction_data', $transaction_id);
}, 10, 2);
```

**Filter webhook data**:
```php
add_filter('redpay_payment_gateway_webhook_data', function($data) {
    // Process webhook data
    return $data;
});
```

### Database Schema

The plugin creates these custom tables:

**Transaction Logs** (`wp_redpay_payment_gateway_transactions`):
```sql
CREATE TABLE wp_redpay_payment_gateway_transactions (
    id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    order_id bigint(20) unsigned NOT NULL,
    transaction_id varchar(255) NOT NULL,
    transaction_type enum('payment','refund') NOT NULL,
    amount decimal(10,2) NOT NULL,
    currency varchar(3) NOT NULL,
    status varchar(50) NOT NULL,
    gateway_response text,
    created_at datetime NOT NULL,
    updated_at datetime NOT NULL,
    PRIMARY KEY (id),
    KEY order_id (order_id),
    KEY transaction_id (transaction_id),
    KEY status (status)
);
```

### Security Considerations

1. **API Keys**: Store securely using WordPress constants or encrypted options
2. **Webhook Verification**: Always verify webhook signatures
3. **SSL**: Required for live payments
4. **Input Validation**: Sanitize and validate all input data
5. **Logging**: Log security events and failed attempts

### Performance Optimization

1. **Caching**: Cache API responses where appropriate
2. **Async Processing**: Use WordPress cron for webhook processing
3. **Database Indexes**: Proper indexing on transaction tables
4. **Rate Limiting**: Implement client-side rate limiting

## SDK Usage

### PHP SDK Example

```php
<?php
require_once 'path/to/plugin/includes/class-redpay-payment-gateway.php';

$gateway = new MyPaymentGateway\Client([
    'api_key' => 'your_api_key',
    'environment' => 'test' // or 'live'
]);

// Process payment
try {
    $payment = $gateway->payments()->create([
        'amount' => 29.99,
        'currency' => 'USD',
        'card_number' => '4111111111111111',
        'card_expiry' => '12/25',
        'card_cvc' => '123'
    ]);
    
    echo "Payment successful: " . $payment['transaction_id'];
} catch (MyPaymentGateway\Exception $e) {
    echo "Payment failed: " . $e->getMessage();
}
```

### JavaScript SDK Example

```javascript
const gateway = new MyPaymentGateway({
    apiKey: 'your_public_key',
    environment: 'test'
});

// Tokenize card
gateway.tokenizeCard({
    cardNumber: '4111111111111111',
    expiryMonth: '12',
    expiryYear: '25',
    cvc: '123'
}).then(token => {
    // Send token to server for payment processing
    return fetch('/process-payment', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({token: token.id, amount: 2999})
    });
}).catch(error => {
    console.error('Payment failed:', error);
});
```