When a store needs a payment provider that WooCommerce doesn't support out of the box (a local bank, a crypto processor, an internal billing system), you write a payment gateway. A gateway is a small WordPress plugin with one PHP class that extends WC_Payment_Gateway. WooCommerce handles the checkout, the order and the admin UI; your class adds its settings, takes the payment and reports the result.
This guide builds a gateway step by step: the class, its settings, payment processing, the callback from the provider, and the extra registration that modern block-based checkout needs. I used the same structure for the WooCommerce recurring payments project.
Choose the type of gateway
Start by deciding where the customer enters their payment details, because that shapes the rest of the code.
| Type | How it works | has_fields |
|---|---|---|
| Redirect (form-based) | The customer clicks "Place order" and is sent to the provider's hosted payment page, then back to your store. | false |
| Iframe | The provider's payment form loads inside an iframe on your checkout page. | true |
| Direct | Card or account fields are rendered on your checkout and the payment is made when the order is placed. | true |
| Offline | No money moves online: bank transfer, cheque, cash on delivery. | false |
A redirect gateway is the most common and the easiest to keep PCI-compliant, since card data never touches your server. The example below is a redirect gateway.
Create the gateway class
Put the gateway in its own plugin. Define the class once all plugins are loaded, so WC_Payment_Gateway already exists:
<?php
/**
* Plugin Name: My Payment Gateway
* Requires Plugins: woocommerce
*/
add_action( 'plugins_loaded', 'my_gateway_init' );
function my_gateway_init() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
return;
}
class WC_Gateway_My_Gateway extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'my_gateway'; // Unique ID, used in option names.
$this->icon = plugin_dir_url( __FILE__ ) . 'assets/logo.svg';
$this->has_fields = false; // Redirect gateway: no fields on checkout.
$this->method_title = 'My Gateway'; // Shown in WooCommerce → Settings → Payments.
$this->method_description = 'Redirects customers to My Gateway to pay by card.';
$this->supports = [ 'products', 'refunds' ];
$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' ]
);
}
}
}Then tell WooCommerce the gateway exists by adding the class name to the woocommerce_payment_gateways filter:
add_filter( 'woocommerce_payment_gateways', function ( $gateways ) {
$gateways[] = 'WC_Gateway_My_Gateway';
return $gateways;
} );The gateway now shows up under WooCommerce → Settings → Payments. The woocommerce_update_options_payment_gateways_{id} hook in the constructor is what saves its settings when the admin clicks "Save changes".
Add the settings
Settings are declared in init_form_fields() with the WooCommerce Settings API. Every gateway should have at least enabled, title and description. The title and description here are what customers see at checkout; method_title and method_description from the constructor are only for the admin.
public function init_form_fields() {
$this->form_fields = [
'enabled' => [
'title' => __( 'Enable/Disable', 'my-gateway' ),
'type' => 'checkbox',
'label' => __( 'Enable My Gateway', 'my-gateway' ),
'default' => 'no',
],
'title' => [
'title' => __( 'Title', 'my-gateway' ),
'type' => 'text',
'description' => __( 'Payment method name the customer sees at checkout.', 'my-gateway' ),
'default' => __( 'Credit card', 'my-gateway' ),
'desc_tip' => true,
],
'description' => [
'title' => __( 'Description', 'my-gateway' ),
'type' => 'textarea',
'default' => __( 'You will be redirected to a secure payment page.', 'my-gateway' ),
],
'api_key' => [
'title' => __( 'API key', 'my-gateway' ),
'type' => 'password',
],
'testmode' => [
'title' => __( 'Test mode', 'my-gateway' ),
'type' => 'checkbox',
'label' => __( 'Use the sandbox API', 'my-gateway' ),
'default' => 'yes',
],
];
}init_settings() loads the saved values, and $this->get_option( 'api_key' ) reads them anywhere in the class.
Process the payment
When the customer places an order, WooCommerce creates it with the status pending and calls process_payment() with its ID. The method must return an array with result and redirect. For a redirect gateway, redirect is the provider's payment page:
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
$response = wp_remote_post( 'https://api.mygateway.example/v1/payments', [
'headers' => [ 'Authorization' => 'Bearer ' . $this->get_option( 'api_key' ) ],
'body' => wp_json_encode( [
'amount' => $order->get_total(),
'currency' => $order->get_currency(),
'reference' => $order->get_id(),
'return_url' => $this->get_return_url( $order ),
'callback_url' => WC()->api_request_url( 'my_gateway' ),
] ),
'timeout' => 30,
] );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
wc_add_notice( __( 'Payment could not be started. Please try again.', 'my-gateway' ), 'error' );
return [ 'result' => 'failure' ];
}
$payment = json_decode( wp_remote_retrieve_body( $response ), true );
$order->update_meta_data( '_my_gateway_payment_id', $payment['id'] );
$order->save();
return [
'result' => 'success',
'redirect' => $payment['checkout_url'],
];
}A few details matter here:
get_return_url( $order )is the order's "Thank you" page. Without the$orderargument you get the generic one, without the order details.- Read amounts with
$order->get_total()and the currency with$order->get_currency(). The order's currency can differ from the store default when a multi-currency plugin is active. - Store the provider's payment ID with
update_meta_data()andsave(), notupdate_post_meta(). Orders live in their own tables when High-Performance Order Storage (HPOS) is on, which is the default for new stores. - Don't reduce stock yourself. WooCommerce does it when the order is paid or put on hold, and it clears the cart when the customer lands on the "Thank you" page.
For an offline method there is nothing to call. Put the order on hold and send the customer to the "Thank you" page:
$order->update_status( 'on-hold', __( 'Awaiting bank transfer.', 'my-gateway' ) );
return [
'result' => 'success',
'redirect' => $this->get_return_url( $order ),
];Handle the provider's callback
With a redirect gateway, the customer coming back to the "Thank you" page proves nothing: they could close the tab before returning, or open the URL by hand. The reliable signal is the server-to-server callback (webhook) from the provider.
WooCommerce gives every gateway an endpoint for this. WC()->api_request_url( 'my_gateway' ) returns a URL like https://shop.example/wc-api/my_gateway/, and a request to it fires the woocommerce_api_my_gateway action. Register the handler in the gateway's constructor:
add_action( 'woocommerce_api_my_gateway', [ $this, 'handle_callback' ] );public function handle_callback() {
$payload = file_get_contents( 'php://input' );
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
// Never trust a callback you haven't verified.
$expected = hash_hmac( 'sha256', $payload, $this->get_option( 'api_key' ) );
if ( ! hash_equals( $expected, $signature ) ) {
status_header( 401 );
exit;
}
$event = json_decode( $payload, true );
$order = wc_get_order( absint( $event['reference'] ) );
if ( $order && ! $order->is_paid() && 'paid' === $event['status'] ) {
$order->payment_complete( $event['payment_id'] );
$order->add_order_note( 'Payment confirmed by My Gateway.' );
} elseif ( $order && ! $order->is_paid() && 'failed' === $event['status'] ) {
$order->update_status( 'failed', 'Payment declined by My Gateway.' );
}
status_header( 200 );
exit;
}payment_complete() sets the order to processing (or completed for virtual, downloadable products), saves the transaction ID, reduces stock and sends the order emails. The is_paid() check makes the handler idempotent: providers retry callbacks, and a second "paid" event must not run all of that again. How the signature is computed depends on the provider; most use an HMAC of the raw body. If the provider sends the amount, compare it with $order->get_total() before completing the order.
Support the block-based checkout
Since WooCommerce 8.3, new stores get the Cart and Checkout blocks instead of the classic shortcode checkout. A gateway that only extends WC_Payment_Gateway works in the classic checkout but doesn't appear in the block checkout at all. Blocks need two extra pieces: a PHP integration class and a small script that registers the payment method in the browser.
First, declare compatibility with HPOS and the checkout blocks in the main plugin file:
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 );
}
} );Then add a payment method type that tells the blocks which script to load and what data to pass to it. It extends a WooCommerce class, so it goes in its own file, loaded only once WooCommerce Blocks is ready:
<?php
use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
final class My_Gateway_Blocks extends AbstractPaymentMethodType {
protected $name = 'my_gateway'; // Same as the gateway ID.
public function initialize() {
$this->settings = get_option( 'woocommerce_my_gateway_settings', [] );
}
public function is_active() {
return 'yes' === ( $this->settings['enabled'] ?? 'no' );
}
public function get_payment_method_script_handles() {
wp_register_script(
'my-gateway-blocks',
plugin_dir_url( __DIR__ ) . 'assets/blocks.js', // The plugin's root folder.
[ 'wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-html-entities' ],
'1.0.0',
true
);
return [ 'my-gateway-blocks' ];
}
public function get_payment_method_data() {
return [
'title' => $this->settings['title'] ?? '',
'description' => $this->settings['description'] ?? '',
];
}
}In the main plugin file:
add_action( 'woocommerce_blocks_loaded', function () {
require_once __DIR__ . '/includes/class-my-gateway-blocks.php';
add_action( 'woocommerce_blocks_payment_method_type_registration', function ( $registry ) {
$registry->register( new My_Gateway_Blocks() );
} );
} );The script registers the method on the client side. For a redirect gateway it only shows the description; the payment itself still goes through process_payment() on the server:
const { registerPaymentMethod } = window.wc.wcBlocksRegistry;
const { getSetting } = window.wc.wcSettings;
const { decodeEntities } = window.wp.htmlEntities;
const { createElement } = window.wp.element;
const settings = getSetting("my_gateway_data", {});
const label = decodeEntities(settings.title || "My Gateway");
const Content = () => decodeEntities(settings.description || "");
registerPaymentMethod({
name: "my_gateway",
label: createElement("span", null, label),
ariaLabel: label,
content: createElement(Content),
edit: createElement(Content),
canMakePayment: () => true,
});Test it before going live
- Run the whole flow in the provider's sandbox with the gateway's test mode on: a successful payment, a declined card and a customer who abandons the payment page.
- Send the same callback twice and check that the order is completed once, with one set of emails.
- Test both checkouts: the block checkout and the classic
[woocommerce_checkout]shortcode, since existing stores still use it. - Log provider responses with
wc_get_logger()so failed payments can be traced in WooCommerce → Status → Logs.
Wrapping up
A custom gateway comes down to four jobs: declare settings, start the payment in process_payment(), confirm it from a verified callback with payment_complete(), and register itself for the block checkout. Keep the order status changes in the callback rather than on the return page, and the gateway stays correct even when customers never come back to the store.
If you need a gateway built for a specific provider, or recurring billing on top of WooCommerce Subscriptions, that's the kind of work I do in WordPress & WooCommerce development.
