Want to build a custom WooCommerce payment gateway plugin? Here’s the quick guide:

  • Why Build One?

    • Control integration with specific payment providers.
    • Save on third-party fees.
    • Customize your checkout experience.
    • Add features like subscriptions or split payments.
    • Ensure compliance with local payment regulations.
  • What You’ll Need:

    • Skills: PHP (7.4+), REST APIs, WooCommerce architecture.
    • Tools: Local WordPress setup (e.g., XAMPP, Docker), a code editor (VS Code), and WooCommerce developer docs.
  • Steps to Build:

    1. Set up your development environment with XAMPP or similar tools.
    2. Create a plugin folder structure (e.g., wp-content/plugins/your-gateway-name).
    3. Extend the WC_Payment_Gateway class to define your gateway.
    4. Add admin settings for configuration (e.g., API keys, titles).
    5. Implement payment processing logic (e.g., process_payment method).
    6. Test rigorously in a sandbox environment.
  • Testing & Debugging:

    • Enable test and debug modes in WooCommerce.
    • Use logging to track issues.
    • Test various scenarios like refunds, tax calculations, and invalid inputs.
  • Advanced Features:

    • Add subscription support or multi-currency handling.
    • Follow secure coding practices to protect sensitive data.

Custom WooCommerce Payment Gateway Integration for E-commerce Shop

WooCommerce

Development Environment Setup

Installing Development Tools

To get started, you’ll need to install the necessary development tools. Visual Studio Code is a popular choice thanks to its PHP and WordPress extensions. If you prefer, you can also use PHPStorm or Sublime Text.

Next, set up a local server environment. XAMPP is a reliable option, and it includes the following components:

Component Version Requirements Purpose
Apache 2.4 or higher Web server
MySQL 5.7 or higher Database management
PHP 7.4 or higher Programming language
phpMyAdmin Latest stable Database administration

Once XAMPP is installed, follow these steps to configure it:

  1. Open XAMPP and start both Apache and MySQL.
  2. Use phpMyAdmin to create a new database.
  3. Download and extract WordPress into C:\xampp\htdocs\your-project-name.
  4. Install the WooCommerce plugin (version 7.0 or higher).

With everything configured, you’re ready to start building your plugin.

Plugin Structure Setup

Begin by creating a new directory for your plugin in the WordPress plugins folder:

wp-content/plugins/your-gateway-name/
├── includes/
│   ├── admin/
│   │   └── settings.php
│   ├── frontend/
│   │   └── payment-form.php
│   └── process/
│       └── payment-processor.php
├── assets/
│   ├── css/
│   └── js/
├── languages/
└── your-gateway-name.php

In your main plugin file (your-gateway-name.php), use the following code to define your plugin’s metadata and basic setup:

<?php
/**
 * Plugin Name: Your Gateway Name
 * Plugin URI: https://yourwebsite.com
 * Description: Custom WooCommerce payment gateway
 * Version: 1.0.0
 * Author: Your Name
 * Author URI: https://yourwebsite.com
 * Text Domain: your-gateway-name
 * Domain Path: /languages
 * Requires PHP: 7.4
 * WC requires at least: 7.0
 * WC tested up to: 8.0
 */

if (!defined('ABSPATH')) {
    exit;
}

To keep your project organized, add a .gitignore file with the following content:

.DS_Store
node_modules/
vendor/
.env
*.log

This setup ensures that unnecessary files are excluded from version control, keeping your repository clean.

sbb-itb-e45557c

Creating the Payment Gateway

Basic Gateway Class Setup

To build a custom payment gateway, you’ll need to extend the WC_Payment_Gateway class in your main plugin file. Here’s a basic example to get started:

class YourGateway_Payment extends WC_Payment_Gateway {
    public function __construct() {
        $this->id = 'your_gateway';
        $this->method_title = 'Your Payment Gateway';
        $this->method_description = 'Custom gateway for processing payments';
        $this->has_fields = true;
        $this->supports = array(
            'products',
            'refunds',
            'default_credit_card_form'
        );

        $this->init_form_fields();
        $this->init_settings();

        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description');

        add_action('woocommerce_update_options_payment_gateways_' . $this->id, 
            array($this, 'process_admin_options'));
    }
}

Admin Settings Configuration

To add admin settings for your gateway, define the init_form_fields() method. This allows you to create configuration options within WooCommerce’s payment settings interface:

public function init_form_fields() {
    $this->form_fields = array(
        'enabled' => array(
            'title' => 'Enable/Disable',
            'type' => 'checkbox',
            'label' => 'Enable Payment Gateway',
            'default' => 'no'
        ),
        'title' => array(
            'title' => 'Title',
            'type' => 'text',
            'description' => 'Payment method title that customers see',
            'default' => 'Credit Card Payment',
            'desc_tip' => true
        ),
        'api_key' => array(
            'title' => 'API Key',
            'type' => 'password',
            'description' => 'Enter your payment gateway API key',
            'default' => ''
        )
    );
}

Tip: Always validate and sanitize user inputs before saving them to the database. Use WordPress functions like sanitize_text_field() or wp_kses() to protect against security risks.

Once this is done, you can move on to implementing the payment processing logic.

Payment Processing Functions

Here’s an example of a process_payment function to handle the core payment logic:

public function process_payment($order_id) {
    $order = wc_get_order($order_id);

    try {
        // Execute payment processing
        $payment_result = $this->process_payment_request($order);

        if ($payment_result['success']) {
            $order->payment_complete();
            $order->add_order_note('Payment processed successfully');
            $woocommerce->cart->empty_cart();

            return array(
                'result' => 'success',
                'redirect' => $this->get_return_url($order)
            );
        } else {
            throw new Exception('Payment processing failed');
        }
    } catch (Exception $e) {
        wc_add_notice($e->getMessage(), 'error');
        return array(
            'result' => 'fail',
            'redirect' => ''
        );
    }
}

You should also implement additional methods to ensure your gateway works seamlessly:

Function Purpose Required Parameters
validate_fields() Verifies the checkout form fields None
process_refund() Handles refunds for payments Order ID, Amount, Reason
payment_scripts() Loads necessary payment form scripts None

These methods help ensure your gateway integrates smoothly with WooCommerce and provides a complete payment solution.

Testing and Troubleshooting

Test Environment Setup

Set up a dedicated test environment using tools like Local by Flywheel or XAMPP. In your wp-config.php file, include the following lines to enable test and debug modes:

define('WC_PAYMENT_GATEWAY_TEST_MODE', true);
define('WC_PAYMENT_GATEWAY_DEBUG', true);

Create test products with prices such as $9.99, $99.99, and $999.99 to check currency formatting and decimal handling. Use these scenarios to test your payment gateway:

Test Case Configuration Expected Outcome
Basic Payment Single product, no tax Successful transaction
Tax Calculation Multiple products with tax Correct tax computation
Refund Processing Full/partial refund Proper refund handling
Error Handling Invalid card data Appropriate error message

Thorough testing ensures your payment gateway complies with secure transaction standards.

Error Logging Setup

Logging is essential for diagnosing issues during testing. Add the following method to your gateway class for logging:

public function log($message, $level = 'info') {
    if ($this->debug_mode) {
        $logger = wc_get_logger();
        $context = array('source' => $this->id);
        $logger->log($level, $message, $context);
    }
}

Enable debug logging in your gateway’s settings by adding this configuration:

'debug' => array(
    'title'       => 'Debug Mode',
    'type'        => 'checkbox',
    'label'       => 'Enable logging',
    'default'     => 'no',
    'description' => 'Log payment events to WooCommerce > Status > Logs'
)

This allows you to track payment events and errors for troubleshooting.

Problem-Solving Guide

With testing and logging in place, address common issues using these steps:

  1. SSL Certificate Errors
    If SSL verification causes issues, temporarily bypass it by adding this filter:

    add_filter('https_ssl_verify', '__return_false');
    

    Note: Remove this filter before deploying to production to maintain security.

  2. Payment Validation Failures
    Ensure proper input validation for payment fields. For example:

    public function validate_fields() {
        if (empty($_POST['card_number'])) {
            wc_add_notice('Card number is required', 'error');
            return false;
        }
    
        $card_number = sanitize_text_field($_POST['card_number']);
        if (!preg_match('/^[0-9]{13,19}$/', $card_number)) {
            wc_add_notice('Invalid card number format', 'error');
            return false;
        }
    
        return true;
    }
    
  3. Transaction Processing Errors
    Monitor response codes and handle errors effectively:

    try {
        $response = $this->process_api_request($order_data);
        if ($response->status !== 'success') {
            $this->log("Transaction failed: " . $response->error_message, 'error');
            throw new Exception($response->error_message);
        }
    } catch (Exception $e) {
        $this->log("Exception caught: " . $e->getMessage(), 'error');
        wc_add_notice('Payment error: ' . $e->getMessage(), 'error');
        return false;
    }
    

Additionally, test edge cases such as zero-decimal currencies, international transactions, and scenarios involving multiple tax rates.

For more advanced troubleshooting tips and extra code examples, visit WOW WP at https://wowwp.com. Continue refining and expanding your plugin’s functionality in the next steps.

Final Steps

Development Summary

Creating a WooCommerce payment gateway plugin requires a strong focus on secure coding practices and rigorous input validation. Here’s an example of how to handle admin options securely:

public function process_admin_options() {
    $this->init_settings();
    $post_data = $this->get_post_data();

    foreach ($this->get_form_fields() as $key => $field) {
        if ('title' !== $this->get_field_type($field)) {
            $this->settings[$key] = $this->get_field_value($key, $field, $post_data);
        }
    }

    return update_option($this->get_option_key(), apply_filters(
        'woocommerce_settings_api_sanitized_fields_' . $this->id,
        $this->settings
    ));
}

Once the basic functionality is secure, you can work on adding more advanced features to your plugin.

Advanced Features Guide

Here are some advanced features to consider, along with their implementation and security measures:

Feature Implementation Security Consideration
Subscription Support WC_Subscriptions_Payment_Gateway interface Encrypt stored tokens
Multi-Currency Currency conversion API integration Validate exchange rates

For example, to add subscription support, you can extend your gateway class like this:

class WC_Custom_Payment_Gateway extends WC_Payment_Gateway {
    public function supports($feature) {
        return in_array($feature, array(
            'products',
            'subscriptions',
            'subscription_cancellation',
            'subscription_suspension',
            'subscription_reactivation'
        ));
    }
}

Once you’ve implemented these advanced features, you can deepen your knowledge with additional learning materials.

Additional Learning Materials

Here are some resources to help you expand your expertise:

  • Official Documentation

    • WooCommerce Payment Gateway API documentation
    • WordPress Plugin Security Guidelines
  • Development Tools

    • Use PHPUnit for testing payment flows
    • Validate SSL certificates with appropriate tools
  • Code Resources

    • WOW WP’s collection of WooCommerce code snippets
    • Examples of secure coding practices and implementation tips

These resources can help refine your skills and ensure your plugin meets both functional and security standards.

Related Blog Posts


Leave a Reply

Your email address will not be published. Required fields are marked *