Creating a Custom WooCommerce Payment Gateway Plugin

Creating a WooCommerce Payment Gateway Plugin allows developers to integrate custom payment options into WooCommerce, the popular e-commerce platform for WordPress. While WooCommerce supports various payment methods out of the box, there may be times when you need to add a payment gateway not natively supported by WooCommerce, such as a regional payment processor or a unique custom payment method.

A custom WooCommerce Payment Gateway Plugin provides flexibility by letting store owners offer payment options tailored to specific customer needs or geographical areas. By following WordPress and WooCommerce’s coding standards, developers can create secure, user-friendly, and highly functional payment gateways that integrate seamlessly into WooCommerce’s checkout process. This guide walks through the process, covering essential concepts like setting up the plugin, configuring the gateway settings, handling payments, and adding frontend customizations.

 

Prerequisites:

  1. Basic knowledge of PHP, HTML, and WooCommerce.
  2. Access to a WooCommerce development environment (localhost or staging).
  3. Familiarity with WordPress plugins and WooCommerce.

 

Folder Structure for the WooCommerce Payment Gateway Plugin

worldwin-coder-payment-gateway/
├── includes/
│   └── class-wc-gateway-worldwin.php
├── assets/
│   ├── css/
│   │   └── style.css             # Optional: CSS for any custom styling
│   └── js/
│       └── script.js             # Optional: JS for custom JavaScript (if needed)
├── languages/
│   └── worldwin-coder-payment-gateway.pot # Optional: For translation files
├── worldwin-coder-payment-gateway.php
└── README.txt                    # Optional: Description and setup instructions

Explanation of Each File

  1. worldwin-coder-payment-gateway.php
    • The main plugin file that initializes the payment gateway plugin. It contains the plugin header and setup code.
  2. includes/class-wc-gateway-worldwin.php
    • Contains the main payment gateway class (WC_Gateway_WorldWin) where the custom gateway functionality is defined, including settings, form fields, and the payment processing logic.
  3. assets/css/style.css (Optional)
    • Custom styles for the plugin (e.g., styling for custom checkout fields). This file is optional unless you need additional CSS.
  4. assets/js/script.js (Optional)
    • Custom JavaScript for the plugin. Use this file for any JavaScript that enhances checkout functionality, if required.
  5. languages/worldwin-coder-payment-gateway.pot (Optional)
    • A .pot file for translation. This is optional but recommended if you want the plugin to support multiple languages.
  6. README.txt (Optional)
    • A README file that provides plugin description, setup instructions, and any special notes. This file is especially helpful for sharing or distributing the plugin.

Creating a Custom WooCommerce Payment Gateway Plugin

Step 1: Setup Plugin Directory and Files

  1. Navigate to your WordPress installation directory: Go to wp-content/plugins/ and create a folder named worldwin-coder-payment-gateway.
  2. Create the main plugin file: Inside the folder, create a file named worldwin-coder-payment-gateway.php. This file will be the main plugin file.
  3. Add Plugin Header: Open worldwin-coder-payment-gateway.php and add the plugin header information:

 

<?php
/*
Plugin Name: WorldWin Coder Custom Payment Gateway
Plugin URI: https://example.com
Description: Custom Payment Gateway for WooCommerce
Version: 1.0
Author: Your Name
Author URI: https://example.com
*/

 

Step 2: Initialize the Payment Gateway Class

  1. Hook to initialize the gateway: Add the following code to hook your gateway initialization:
    if (!defined('ABSPATH')) exit; // Exit if accessed directly
    
    add_action('plugins_loaded', 'worldwin_coder_init', 0);
    
    function worldwin_coder_init() {
        if (!class_exists('WC_Payment_Gateway')) return;
        include_once 'includes/class-wc-gateway-worldwin.php';
        add_filter('woocommerce_payment_gateways', 'add_worldwin_coder_gateway');
    }
    
    function add_worldwin_coder_gateway($methods) {
        $methods[] = 'WC_Gateway_WorldWin';
        return $methods;
    }
    
  2. Create the payment gateway class file: Inside your plugin folder, create a new folder named includes. Inside the includes folder, create a file named class-wc-gateway-worldwin.php.

Step 3: Build the Payment Gateway Class

  1. Define your custom payment gateway: Open class-wc-gateway-worldwin.php and add the following code:
  2. <?php
    class WC_Gateway_WorldWin extends WC_Payment_Gateway {
    
        public function __construct() {
            $this->id                 = 'worldwin';
            $this->icon               = ''; // URL of the icon
            $this->has_fields         = true;
            $this->method_title       = 'WorldWin Coder Gateway';
            $this->method_description = 'Custom Payment Gateway for WooCommerce';
    
            // Load the settings
            $this->init_form_fields();
            $this->init_settings();
    
            // Define user settings variables
            $this->title              = $this->get_option('title');
            $this->description        = $this->get_option('description');
            $this->instructions       = $this->get_option('instructions');
    
            // Save admin options
            add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
        }
    
        public function init_form_fields() {
            $this->form_fields = [
                'enabled' => [
                    'title'   => 'Enable/Disable',
                    'type'    => 'checkbox',
                    'label'   => 'Enable WorldWin Payment Gateway',
                    'default' => 'yes'
                ],
                'title' => [
                    'title'       => 'Title',
                    'type'        => 'text',
                    'description' => 'This controls the title shown during checkout.',
                    'default'     => 'WorldWin Payment',
                    'desc_tip'    => true,
                ],
                'description' => [
                    'title'       => 'Description',
                    'type'        => 'textarea',
                    'description' => 'This controls the description shown during checkout.',
                    'default'     => 'Pay securely with WorldWin.',
                ],
                'instructions' => [
                    'title'       => 'Instructions',
                    'type'        => 'textarea',
                    'description' => 'Instructions for the customer after order completion.',
                    'default'     => 'Thank you for using WorldWin Payment.',
                ]
            ];
        }
    }
    

Step 4: Add Payment Processing Logic

  1. Add payment process method: Inside the class, add a function to handle the payment processing. Modify it to fit the specifics of your payment gateway API:
    public function process_payment($order_id) {
        global $woocommerce;
    
        $order = wc_get_order($order_id);
    
        // Mark order as processing (can also use 'completed')
        $order->update_status('processing', 'Order processed with WorldWin Gateway.');
    
        // Reduce stock levels
        wc_reduce_stock_levels($order_id);
    
        // Clear cart
        $woocommerce->cart->empty_cart();
    
        // Redirect to order confirmation page
        return [
            'result'   => 'success',
            'redirect' => $this->get_return_url($order)
        ];
    }
    
  2. Add custom checkout fields (optional): If you need custom fields on the checkout page, define them in payment_fields:
    public function payment_fields() {
        echo '<p>' . esc_html($this->description) . '</p>';
    }
    

Step 5: Final Testing and Debugging

  1. Activate the plugin: Go to your WordPress dashboard, navigate to “Plugins,” and activate “WorldWin Coder Custom Payment Gateway.”
  2. Test the gateway:
    • Go to WooCommerce settings, click on “Payments,” and enable the WorldWin Coder gateway.
    • Try a test checkout to ensure it processes as expected.
  3. Debugging and Logging (optional): Add logging features if you need to troubleshoot errors. WooCommerce provides a logger:
    $this->log = new WC_Logger();
    $this->log->add('worldwin', 'Logging message here...');
    

     

Step 6: Finalizing and Packaging

  1. Document any setup instructions for users and package the plugin files into a .zip for distribution.

With this setup, you have a functional custom WooCommerce payment gateway plugin. Modify the process_payment method to connect with any specific payment API your gateway requires.

Happy coding!

What’s your Biggest WooCommerce Challenge Right Now?

Let’s Talk