Create a WooCommerce Payment Gateway Plugin from Scratch

A WooCommerce payment gateway plugin from scratch

When a regional payment provider has no WooCommerce plugin, you write one. The gateway class extends WC_Payment_Gateway: settings for the API keys and a test mode, process_payment() to start the payment, and a webhook that confirms it. The common case today is a redirect gateway: the customer pays on the provider’s page and comes back.

Problem: A store needs a payment method for a provider that offers a REST API with hosted payment pages and webhooks, but no WooCommerce integration.

Solution: Register a WC_Payment_Gateway subclass with the woocommerce_payment_gateways filter, define its settings in init_form_fields(), create the payment at the provider in process_payment() and return the redirect URL, confirm the order in a webhook handler registered on woocommerce_api_{id} after checking the signature, and declare compatibility with HPOS and the Checkout block.

The plugin and the class

<?php
/**
 * Plugin Name: HA Pay for WooCommerce
 * WC requires at least: 8.0
 */

add_action( 'plugins_loaded', function () {
    if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
        return;
    }

    class HA_Pay_Gateway extends WC_Payment_Gateway {

        public function __construct() {
            $this->id                 = 'ha_pay';
            $this->method_title       = 'HA Pay';
            $this->method_description = __( 'Redirects customers to the HA Pay payment page.', 'textdomain' );
            $this->has_fields         = false;
            $this->supports           = [ 'products' ];

            $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, [ $this, 'process_admin_options' ] );
            add_action( 'woocommerce_api_' . $this->id, [ $this, 'webhook' ] );
        }

        public function init_form_fields() {
            $this->form_fields = [
                'enabled'     => [ 'title' => __( 'Enable', 'textdomain' ), 'type' => 'checkbox', 'default' => 'no' ],
                'title'       => [ 'title' => __( 'Title', 'textdomain' ), 'type' => 'text', 'default' => 'HA Pay' ],
                'description' => [ 'title' => __( 'Description', 'textdomain' ), 'type' => 'textarea', 'default' => '' ],
                'testmode'    => [ 'title' => __( 'Test mode', 'textdomain' ), 'type' => 'checkbox', 'default' => 'yes' ],
                'api_key'     => [ 'title' => __( 'API key', 'textdomain' ), 'type' => 'password' ],
                'webhook_key' => [ 'title' => __( 'Webhook secret', 'textdomain' ), 'type' => 'password' ],
            ];
        }

        private function api_base() {
            return 'yes' === $this->get_option( 'testmode' ) ? 'https://sandbox.hapay.example/v1' : 'https://api.hapay.example/v1';
        }

        public function process_payment( $order_id ) {
            $order    = wc_get_order( $order_id );
            $response = wp_remote_post( $this->api_base() . '/payments', [
                'timeout' => 20,
                'headers' => [ 'Authorization' => 'Bearer ' . $this->get_option( 'api_key' ), 'Content-Type' => 'application/json' ],
                'body'    => wp_json_encode( [
                    'amount'      => (int) round( $order->get_total() * 100 ),
                    'currency'    => $order->get_currency(),
                    'reference'   => (string) $order->get_id(),
                    'return_url'  => $this->get_return_url( $order ),
                    'cancel_url'  => wc_get_checkout_url(),
                    'webhook_url' => WC()->api_request_url( $this->id ),
                ] ),
            ] );
            $data = json_decode( wp_remote_retrieve_body( $response ), true );

            if ( is_wp_error( $response ) || empty( $data['payment_url'] ) ) {
                wc_add_notice( __( 'The payment could not be started. Please try again.', 'textdomain' ), 'error' );
                return [ 'result' => 'failure' ];
            }

            $order->update_meta_data( '_ha_pay_id', sanitize_text_field( $data['id'] ) );
            $order->update_status( 'pending', __( 'Waiting for HA Pay.', 'textdomain' ) );
            $order->save();

            return [ 'result' => 'success', 'redirect' => esc_url_raw( $data['payment_url'] ) ];
        }

        public function webhook() {
            $body      = file_get_contents( 'php://input' );
            $signature = $_SERVER['HTTP_X_HAPAY_SIGNATURE'] ?? '';
            if ( ! hash_equals( hash_hmac( 'sha256', $body, $this->get_option( 'webhook_key' ) ), $signature ) ) {
                status_header( 401 );
                exit;
            }
            $event = json_decode( $body, true );
            $order = wc_get_order( absint( $event['reference'] ?? 0 ) );
            if ( $order && 'paid' === ( $event['status'] ?? '' ) && ! $order->is_paid() ) {
                $order->payment_complete( sanitize_text_field( $event['id'] ) );
            }
            status_header( 200 );
            exit;
        }
    }

    add_filter( 'woocommerce_payment_gateways', function ( $gateways ) {
        $gateways[] = 'HA_Pay_Gateway';
        return $gateways;
    } );
} );

The provider’s API is invented; the structure is what every redirect gateway looks like. The amount is sent in the smallest currency unit as most APIs expect. The order is marked as paid only from the webhook, never from the return URL, because the customer can open the return URL without paying. payment_complete() sets the status, reduces the stock and sends the emails; the is_paid() check makes repeated webhooks harmless. Outgoing requests: wp_remote_post() with JSON and bearer tokens.

HPOS and the Checkout block

add_action( 'before_woocommerce_init', function () {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
    }
} );

The gateway uses only order methods (update_meta_data(), get_total()), never get_post_meta() on orders, so it works with High-Performance Order Storage. Since WooCommerce 8.3 new stores use the Checkout block, which lists a gateway only if it also registers a small JavaScript integration (registerPaymentMethod from @woocommerce/blocks-registry, with a PHP class extending AbstractPaymentMethodType). Declare cart_checkout_blocks as compatible only after adding it.

NOTE: Test the whole cycle in the provider’s sandbox: success, cancellation, a failed card, a webhook that arrives twice and a webhook that arrives before the customer returns. The class_exists() check keeps the site working when WooCommerce is deactivated.

Update (2024): WordPress 6.5 added the Requires Plugins: woocommerce plugin header, which prevents activating the gateway before WooCommerce is installed and active.