Search

How to build a WooCommerce custom payment gateway plugin?

Listen to this article
XUQvMeEqYPhYorxYo3ubfnMB3sX1dxKNi7I0EfP z4KiK22u92oRyRBuuaC Cyc50EJxEmJyOaZHd6RQL2d7smUAN MeYFH bSvWXuz 5

With WooCommerce being one of the most popular e-commerce platforms, having the ability to integrate a custom payment gateway can set your store apart from the competition.

By developing a payment solution tailored to your specific business needs, you can optimize the checkout process, increase customer trust, and ultimately boost conversions.

In WooCommerce building a payment gateway is as simple as extending a WooCommerce class.  

And to help you navigate the process with ease, we’ll cover the fundamental steps required to build a custom payment gateway for WooCommerce.

From understanding the payment gateway architecture to implementing the necessary code, you’ll have the knowledge and tools needed to succeed. 

So without any further ado, let’s dive in.

Note: If you are unfamiliar with code/templates and resolving potential conflicts, reach out to our WooExperts for assistance

When should you opt to create a custom payment gateway?

A custom payment gateway would be required in the following scenarios:

  1. You have created a new payment gateway such as Stripe or Paypal and wish to provide compatibility with WooCommerce.
  2. You need an existing payment gateway to be made compatible with WooCommerce.

What are the prerequisites to creating a custom gateway?

steps to set up a woocommerce custom payment gateway

For creating a custom payment gateway for WooCommerce, you’ll need a few things.  

For example, a server that processes payments – this is separate from WordPress.

A payment gateway needs to be in place where the actual payments will be processed.

To better understand this, take the example of Stripe

Stripe has a Woocommerce payment gateway integration plugin. However, to see the payments, Stripe provides an admin dashboard of its own. This dashboard is not a part of the WordPress website being used but is available as a separate site.

What are the required files/classes/functions that need to be extended/implemented?eOQIycQ796Pd8gBSePw5yTTrBCe7oEAftlstC5S kurXyqY92pv2 jknpDFwWoaQ9JEfPd0sk

Initialization

A custom payment gateway should be added as a separate plugin. 

Let’s begin with the structure you can follow for the plugin. Having the following structure is recommended:

  • Folder with Plugin Name
  • Assets Folder: Folder containing all js/css/images required for the plugin
  • Includes Folder: Folder for classes you will be using for payment gateway implementation
  • Plugin-name.php: The file with plugin details and initialization

Within the plugin-name.php, include a file from the “includes” folder that contains the code for the payment gateway. Let’s call the file includes-gateway-class-extend.php. From the file name, you understand we need to extend something that WooCommerce provides.

We need to extend the WC_Payment_Gateway class provided by WooCommerce. This needs to be done once the plugins are loaded. This is important because we need WooCommerce and its classes to be available before we extend and use their classes. 

For this, use the plugins_loaded hook as follows:

add_action( ‘plugins_loaded’, ‘wdm_init_gateway_class’ );

The function mentioned above then needs to then extend the class mentioned above:

function wdm_init_gateway_class() {

class WDM_Custom_Payment_Gateway extends WC_Payment_Gateway {}

}

However, for WooCommerce to recognize the payment gateway, we also need to inform WooCommerce by adding it to the list of payment gateways. The list is created by WooCommerce and custom plugins can use a filter to add to this list. 

The filter being used is ‘woocommerce_payment_gateways’ and to add your payment gateway, the following code would be required:

function wdm_add_payment_gateway_list( $methods ) 

{

    $methods[] = ‘WDM_Custom_Payment_Gateway’; 

    return $methods;

}

add_filter( ‘woocommerce_payment_gateways’, ‘wdm_add_payment_gateway_list’ );

Here “$methods” is the array that has all the payment methods.

Next, we need to start showing the details for the payment gateway. We first start with the constructor for our class which will have some required variables. Your __construct function within the WDM_Custom_Payment_Gateway should be something similar to this:

function __construct() {

            $this->id = “wdm_custom_payment_gateway”;

            $this->method_title = __( “WDM Custom Payment Gateway”, ‘wdm-custom-payment-gateway’ ); // title on the admin settings page

            $this->method_description = __( “WDM Payment Gateway for WooCommerce”, ‘wdm-custom-payment-gateway’ ); // Description to show on admin settings page

            $this->title = __( “WDM Custom Payment Gateway title”, ‘wdm-custom-payment-gateway’ ); // to show by default to the customers on checkout page

            $this->icon = null;

            $this->init_form_fields();

            $this->init_settings();

 }

Note: Does this feel overwhelming? Let our Woo Experts make things easier!

Contact Woo Experts.

The steps performed above will result in the gateway showing up in the WooCommerce payment settings:

If you enable this option, it should start showing up on the checkout page like so:building a woocommerce custom payment gateway

9Lm WQZx09BCOwbizyI3ruYkKj2t3rBQIxHLxXs4GzcRL2uD7QN8sLx4VFn5vFoKN48eND I 2pIEeBxj u 04vxyaqi2Wlb6wBhCFt8Ah8wU7lsrwAgfUx3YZJ9OwFnrt X bXJXJo7HT9ZO2mkzXU

In the constructor for the class, we had two functions:

  • init_form_fields()
  • This function is where you can define the fields that need to show up as settings for your custom payment gateway.
  • init_settings()
  • Once the settings are defined, this function allows you to get the settings and their values.

Lastly, in the constructor, we need to save the settings by adding the following:

add_action( ‘woocommerce_update_options_payment_gateways_’ . $this->id, array( $this, ‘process_admin_options’ ) );

At this point, you can define the form fields like so:

public function init_form_fields()

        {

            $this->form_fields = array(

                ‘enabled’ => array(

                    ‘title’ => __( ‘Enable/Disable’, ‘wdm-custom-payment-gateway’ ),

                    ‘type’ => ‘checkbox’,

                    ‘label’ => __( ‘Enable Custom Payment’, ‘wdm-custom-payment-gateway’ ),

                    ‘default’ => ‘yes’

                ),

                ‘title’ => array(

                    ‘title’ => __( ‘Title’, ‘wdm-custom-payment-gateway’ ),

                    ‘type’ => ‘text’,

                    ‘description’ => __( ‘This controls the title which the user sees during checkout.’, ‘wdm-custom-payment-gateway’ ),

                    ‘default’ => __( ‘Custom Payment’, ‘wdm-custom-payment-gateway’ ),

                    ‘desc_tip’      => true,

                ),

                ‘description’ => array(

                    ‘title’ => __( ‘Customer Message’, wdm-custom-payment-gateway),

                    ‘type’ => ‘textarea’,

                    ‘default’ => ”

                )

            );

        }

At this point, the settings will start showing up on the payment settings page for the admin:
woocommerce custom payment gateway

However, if you save these settings, they will not show up on the checkout page for the customers. 

For the customers to be able to see these, the following lines need to be added after init_settings() is called in the constructor:

$this->init_settings();

$this->title       = $this->get_option( ‘title’ );

$this->enabled     = $this->get_option( ‘enabled’ );

$this->description     = $this->get_option( ‘description’ );

Once this is done and you save the settings, the custom messages will start showing up for the customers:

There will be other settings that each payment gateway will require based on the use such as Authentication keys which will need to be defined in the init_form_fields().

Now to the most important part – you need to make sure that the payment is handled and the processing happens correctly, you need to add the process_payment( $order_id ) function to your class. 6Ou0pyHDzon7egTZdq T FK6mjQR7Bqjesxf29HKtCUiyDto24uj2Ji5VyKfsV0UyMGU7eZeXmlc7 BN

The function needs to perform the following:

  • Based on the order_id, update the status of the order – This depends on the payment processor. If you can immediately verify the order status, the payment complete() should be called instead of updating just the order status.
  • Make sure the cart is cleared once the order is placed
  • Provide the status of the transaction – whether it was successful or not. In case it is not successful, WooCommerce should be notified by throwing an error which will show up directly on the checkout page. 

The error can be thrown as follows:

  • wc_add_notice( __(‘Payment error:’, ‘wdm-custom-payment-gateway’) . $error_message, ‘error’ );

return;

  • Provide information on where the user should be redirected to once the payment processing is done

This will be different for different payment gateways but a sample reference is of the Cheque gateway:

function process_payment( $order_id ) {

    global $woocommerce;

    $order = new WC_Order( $order_id );

    // Mark as on-hold (we’re awaiting the cheque)

    $order->update_status(‘on-hold’, __( ‘Awaiting cheque payment’, ‘woocommerce’ ));

    // Remove cart

    $woocommerce->cart->empty_cart();

    // Return thankyou redirect

    return array(

        ‘result’ => ‘success’,

        ‘redirect’ => $this->get_return_url( $order )

    );

}

This completes the basic payment gateway structure. 

Also Read: How To Develop a Woocommerce Plugin from Scratch

How to make sure the payment gateway is working properly?

The points that need to be taken care of to make sure the gateway plugin works are as follows:

  • Providing settings for the payment gateway credentials to link to an account on the payment processor
  • Adding order status and order notes based on the processor response in the process_payment()
  • If your payment gateway requires any further actions to be taken by the customer for the payment to be completed, this information can be added to the WooCommerce order detail emails.
  • Refund option needs to be provided if this functionality is to be made available from within WooCommerce dashboard.
  • Retry payment for failed payments is a feature that can be provided as long as the processor can handle such requests.
  • What all should the payment gateway support? Eg. subscription/part payment, refunds, order notes, order status, retry payment, etc.

Conclusion

So that was it!

I hope you found this article helpful.

If you feel stuck at any step or need more clarity on how to build a custom payment gateway, feel free to ask in the comments below or get in touch with our WooCommerce Experts.

Having spent over 10+ years in the WooCommerce space and working on 300+ projects, we know exactly how to help you.


 

Nishant Nihar

Nishant Nihar

Leave a Reply

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

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads