# Developer Examples

This document provides practical examples for developers integrating with the RedPay plugin.

## Basic Integration

### 1. Plugin Detection

Check if the plugin is active before integrating:

```php
if (class_exists('RedpayPaymentGateway') && function_exists('WC')) {
    // Plugin is active and WooCommerce is available
    $gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    
    if ($gateway && $gateway->enabled === 'yes') {
        // Gateway is enabled and ready to use
    }
}
```

### 2. Process Custom Payment

Create a custom payment outside of WooCommerce checkout:

```php
function process_custom_payment($amount, $card_data, $customer_data) {
    $gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    
    if (!$gateway) {
        return array('success' => false, 'message' => 'Gateway not available');
    }
    
    // Create a temporary order
    $order = wc_create_order();
    $order->set_total($amount);
    $order->set_currency(get_woocommerce_currency());
    $order->set_billing_email($customer_data['email']);
    $order->set_billing_first_name($customer_data['first_name']);
    $order->set_billing_last_name($customer_data['last_name']);
    $order->save();
    
    // Simulate POST data
    $_POST = array(
        'redpay_payment_gateway_card_number' => $card_data['number'],
        'redpay_payment_gateway_card_expiry' => $card_data['expiry'],
        'redpay_payment_gateway_card_cvc' => $card_data['cvc']
    );
    
    // Process payment
    $result = $gateway->process_payment($order->get_id());
    
    return $result;
}

// Usage
$result = process_custom_payment(29.99, array(
    'number' => '4111111111111111',
    'expiry' => '12/25',
    'cvc' => '123'
), array(
    'email' => 'customer@example.com',
    'first_name' => 'John',
    'last_name' => 'Doe'
));
```

### 3. Custom Refund Processing

Process refunds programmatically:

```php
function process_custom_refund($order_id, $amount, $reason = '') {
    $order = wc_get_order($order_id);
    
    if (!$order) {
        return new WP_Error('invalid_order', 'Order not found');
    }
    
    $gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    
    if (!$gateway) {
        return new WP_Error('gateway_unavailable', 'Gateway not available');
    }
    
    // Process refund
    $result = $gateway->process_refund($order_id, $amount, $reason);
    
    if (is_wp_error($result)) {
        return $result;
    }
    
    // Log refund
    $order->add_order_note(sprintf(
        'Custom refund processed: %s (%s)',
        wc_price($amount),
        $reason
    ));
    
    return array('success' => true, 'refund_id' => $result);
}
```

## Advanced Customization

### 1. Custom Payment Form

Create a custom payment form with your own styling:

```php
function custom_payment_form() {
    if (!is_checkout()) {
        return;
    }
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Replace default payment form
        $('#redpay-payment-gateway-form').html(`
            <div class="custom-payment-form">
                <h4>Enter Card Details</h4>
                <div class="card-input-group">
                    <input type="text" id="custom_card_number" placeholder="Card Number" />
                    <input type="text" id="custom_expiry" placeholder="MM/YY" />
                    <input type="text" id="custom_cvc" placeholder="CVC" />
                </div>
            </div>
        `);
        
        // Copy values to original fields when submitted
        $('form.checkout').on('checkout_place_order', function() {
            $('#redpay_payment_gateway_card_number').val($('#custom_card_number').val());
            $('#redpay_payment_gateway_card_expiry').val($('#custom_expiry').val());
            $('#redpay_payment_gateway_card_cvc').val($('#custom_cvc').val());
        });
    });
    </script>
    <style>
    .custom-payment-form {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 20px;
        border-radius: 10px;
        color: white;
    }
    .card-input-group {
        display: flex;
        gap: 10px;
        margin-top: 15px;
    }
    .card-input-group input {
        flex: 1;
        padding: 10px;
        border: none;
        border-radius: 5px;
    }
    </style>
    <?php
}
add_action('wp_footer', 'custom_payment_form');
```

### 2. Custom API Integration

Integrate directly with the payment API:

```php
class CustomPaymentProcessor {
    private $gateway;
    
    public function __construct() {
        $this->gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    }
    
    public function create_subscription_payment($customer_id, $amount) {
        // Get stored customer payment method
        $payment_method = $this->get_stored_payment_method($customer_id);
        
        if (!$payment_method) {
            return array('success' => false, 'message' => 'No payment method found');
        }
        
        // Create payment data
        $payment_data = array(
            'amount' => $amount,
            'currency' => get_woocommerce_currency(),
            'customer_id' => $customer_id,
            'payment_method_id' => $payment_method['id'],
            'description' => 'Subscription payment',
            'metadata' => array(
                'type' => 'subscription',
                'customer_id' => $customer_id
            )
        );
        
        // Make API request
        $response = $this->gateway->make_api_request('POST', '/payments', $payment_data);
        
        if ($response && $response['status'] === 'success') {
            // Log successful payment
            $this->log_subscription_payment($customer_id, $amount, $response['transaction_id']);
            
            return array(
                'success' => true,
                'transaction_id' => $response['transaction_id']
            );
        }
        
        return array(
            'success' => false,
            'message' => $response['message'] ?? 'Payment failed'
        );
    }
    
    private function get_stored_payment_method($customer_id) {
        // Implementation depends on how you store payment methods
        return get_user_meta($customer_id, '_payment_method', true);
    }
    
    private function log_subscription_payment($customer_id, $amount, $transaction_id) {
        // Log to custom table or WordPress options
        $log_entry = array(
            'customer_id' => $customer_id,
            'amount' => $amount,
            'transaction_id' => $transaction_id,
            'date' => current_time('mysql'),
            'type' => 'subscription'
        );
        
        $existing_logs = get_option('subscription_payment_logs', array());
        $existing_logs[] = $log_entry;
        update_option('subscription_payment_logs', $existing_logs);
    }
}
```

### 3. Webhook Handler Extension

Extend webhook handling for custom functionality:

```php
function custom_webhook_handler($data) {
    // Handle custom webhook events
    switch ($data['event']) {
        case 'payment.completed':
            handle_completed_payment($data['data']);
            break;
        case 'payment.failed':
            handle_failed_payment($data['data']);
            break;
        case 'subscription.created':
            handle_subscription_created($data['data']);
            break;
    }
}

function handle_completed_payment($payment_data) {
    $order_id = $payment_data['order_id'];
    $order = wc_get_order($order_id);
    
    if (!$order) {
        return;
    }
    
    // Custom logic for completed payments
    
    // Send custom email
    wp_mail(
        $order->get_billing_email(),
        'Payment Confirmation',
        'Your payment has been successfully processed.'
    );
    
    // Update custom database
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'custom_payments',
        array(
            'order_id' => $order_id,
            'transaction_id' => $payment_data['transaction_id'],
            'amount' => $payment_data['amount'],
            'status' => 'completed',
            'processed_at' => current_time('mysql')
        ),
        array('%d', '%s', '%f', '%s', '%s')
    );
    
    // Trigger custom action
    do_action('custom_payment_completed', $order, $payment_data);
}

function handle_failed_payment($payment_data) {
    // Custom logic for failed payments
    
    // Send admin notification
    wp_mail(
        get_option('admin_email'),
        'Payment Failed',
        'A payment failed for order: ' . $payment_data['order_id']
    );
    
    // Log failed payment
    error_log('Payment failed: ' . json_encode($payment_data));
}

// Hook into the gateway's webhook processing
add_action('redpay_payment_gateway_webhook_received', 'custom_webhook_handler');
```

## Custom Filters and Actions

### 1. Modify Payment Data

```php
// Add custom metadata to payments
add_filter('redpay_payment_gateway_api_request_data', function($data, $order) {
    $data['metadata']['customer_type'] = get_user_meta($order->get_customer_id(), 'customer_type', true);
    $data['metadata']['order_source'] = $order->get_meta('_order_source');
    
    return $data;
}, 10, 2);

// Modify payment description
add_filter('redpay_payment_gateway_payment_description', function($description, $order) {
    return 'Order #' . $order->get_order_number() . ' - ' . get_bloginfo('name');
}, 10, 2);
```

### 2. Custom Validation

```php
// Add custom validation rules
add_filter('redpay_payment_gateway_validate_payment', function($is_valid, $order) {
    // Check if customer has reached payment limit
    $customer_id = $order->get_customer_id();
    $monthly_total = get_monthly_payment_total($customer_id);
    $payment_limit = get_user_meta($customer_id, 'monthly_payment_limit', true);
    
    if ($payment_limit && ($monthly_total + $order->get_total()) > $payment_limit) {
        wc_add_notice('Payment exceeds monthly limit', 'error');
        return false;
    }
    
    return $is_valid;
}, 10, 2);

function get_monthly_payment_total($customer_id) {
    $orders = wc_get_orders(array(
        'customer_id' => $customer_id,
        'status' => 'completed',
        'date_created' => '>' . (time() - MONTH_IN_SECONDS)
    ));
    
    $total = 0;
    foreach ($orders as $order) {
        $total += $order->get_total();
    }
    
    return $total;
}
```

### 3. Custom Email Notifications

```php
// Send custom emails after payment
add_action('redpay_payment_gateway_payment_complete', function($order, $transaction_id) {
    // Send email to fulfillment team
    if ($order->get_total() > 100) {
        send_high_value_order_notification($order, $transaction_id);
    }
    
    // Send SMS notification
    if (has_sms_notification_enabled($order->get_customer_id())) {
        send_payment_sms($order, $transaction_id);
    }
}, 10, 2);

function send_high_value_order_notification($order, $transaction_id) {
    $fulfillment_email = get_option('fulfillment_team_email');
    
    if ($fulfillment_email) {
        wp_mail(
            $fulfillment_email,
            'High Value Order - Priority Processing',
            sprintf(
                'Order #%s requires priority processing.\nAmount: %s\nTransaction ID: %s',
                $order->get_order_number(),
                $order->get_formatted_order_total(),
                $transaction_id
            )
        );
    }
}
```

## Testing Examples

### 1. Unit Testing

```php
class TestRedpayPaymentGateway extends WP_UnitTestCase {
    
    private $gateway;
    
    public function setUp(): void {
        parent::setUp();
        $this->gateway = new Redpay_Payment_Gateway();
    }
    
    public function test_validate_card_number() {
        // Test valid card
        $this->assertTrue($this->gateway->validate_card_number('4111111111111111'));
        
        // Test invalid card
        $this->assertFalse($this->gateway->validate_card_number('1234567890123456'));
    }
    
    public function test_format_expiry() {
        $this->assertEquals('12/25', $this->gateway->format_expiry('1225'));
        $this->assertEquals('01/30', $this->gateway->format_expiry('0130'));
    }
    
    public function test_payment_processing() {
        // Create test order
        $order = WC_Helper_Order::create_order();
        
        // Set up test data
        $_POST = array(
            'redpay_payment_gateway_card_number' => '4111111111111111',
            'redpay_payment_gateway_card_expiry' => '12/25',
            'redpay_payment_gateway_card_cvc' => '123'
        );
        
        // Process payment
        $result = $this->gateway->process_payment($order->get_id());
        
        $this->assertEquals('success', $result['result']);
        $this->assertNotEmpty($result['redirect']);
    }
}
```

### 2. Integration Testing

```php
class TestPaymentIntegration extends WP_UnitTestCase {
    
    public function test_complete_checkout_flow() {
        // Create product
        $product = WC_Helper_Product::create_simple_product();
        
        // Add to cart
        WC()->cart->add_to_cart($product->get_id());
        
        // Create order from cart
        $order = wc_create_order_from_cart();
        
        // Set payment method
        $order->set_payment_method('redpay_payment_gateway');
        
        // Set billing info
        $order->set_billing_email('test@example.com');
        $order->set_billing_first_name('Test');
        $order->set_billing_last_name('Customer');
        
        $order->save();
        
        // Process payment
        $gateway = new Redpay_Payment_Gateway();
        
        // Mock successful payment
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, 'redpay') !== false) {
                return array(
                    'response' => array('code' => 200),
                    'body' => json_encode(array(
                        'status' => 'success',
                        'transaction_id' => 'test_txn_123'
                    ))
                );
            }
            return $preempt;
        }, 10, 3);
        
        $result = $gateway->process_payment($order->get_id());
        
        $this->assertEquals('success', $result['result']);
        $this->assertEquals('processing', $order->get_status());
    }
}
```

### 3. JavaScript Testing

```javascript
// Jest test for frontend JavaScript
describe('RedpayPaymentGateway', () => {
    beforeEach(() => {
        // Set up DOM
        document.body.innerHTML = `
            <form id="checkout-form">
                <input id="redpay_payment_gateway_card_number" />
                <input id="redpay_payment_gateway_card_expiry" />
                <input id="redpay_payment_gateway_card_cvc" />
            </form>
        `;
        
        // Initialize gateway
        RedpayPaymentGateway.init();
    });
    
    test('validates card number correctly', () => {
        expect(RedpayPaymentGateway.validateCardNumber('4111111111111111')).toBe(true);
        expect(RedpayPaymentGateway.validateCardNumber('1234567890123456')).toBe(false);
    });
    
    test('formats card number with spaces', () => {
        const input = document.getElementById('redpay_payment_gateway_card_number');
        input.value = '4111111111111111';
        
        RedpayPaymentGateway.formatCardNumberInput({target: input});
        
        expect(input.value).toBe('4111 1111 1111 1111');
    });
    
    test('validates form before submission', () => {
        // Set invalid data
        document.getElementById('redpay_payment_gateway_card_number').value = '123';
        document.getElementById('redpay_payment_gateway_card_expiry').value = '';
        document.getElementById('redpay_payment_gateway_card_cvc').value = '';
        
        expect(RedpayPaymentGateway.validateForm()).toBe(false);
    });
});
```

## Performance Optimization

### 1. Caching API Responses

```php
function cached_api_request($endpoint, $data = array()) {
    $cache_key = 'redpay_payment_gateway_' . md5($endpoint . serialize($data));
    $cached_response = get_transient($cache_key);
    
    if ($cached_response !== false) {
        return $cached_response;
    }
    
    $gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    $response = $gateway->make_api_request('GET', $endpoint, $data);
    
    // Cache for 5 minutes
    if ($response && !isset($response['error'])) {
        set_transient($cache_key, $response, 300);
    }
    
    return $response;
}
```

### 2. Async Webhook Processing

```php
function queue_webhook_processing($webhook_data) {
    // Queue webhook for background processing
    wp_schedule_single_event(time(), 'process_payment_webhook', array($webhook_data));
}

add_action('process_payment_webhook', 'process_webhook_in_background');

function process_webhook_in_background($webhook_data) {
    // Process webhook without blocking response
    $gateway = WC()->payment_gateways->payment_gateways()['redpay_payment_gateway'];
    $gateway->process_webhook($webhook_data);
}
```

### 3. Database Optimization

```php
// Optimize transaction queries
function get_recent_transactions($limit = 50) {
    global $wpdb;
    
    $cache_key = 'recent_transactions_' . $limit;
    $transactions = wp_cache_get($cache_key);
    
    if ($transactions === false) {
        $transactions = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}redpay_payment_gateway_transactions 
             ORDER BY created_at DESC 
             LIMIT %d",
            $limit
        ));
        
        wp_cache_set($cache_key, $transactions, '', 300); // Cache for 5 minutes
    }
    
    return $transactions;
}
```

This documentation provides comprehensive examples for developers to integrate and extend the RedPay plugin functionality.