Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Payments and Shipping

Building a Payment Gateway

Learn how a WooCommerce payment gateway works: WC_Payment_Gateway, settings fields, process_payment, redirect vs direct flows, refunds, notes and idempotent charges.

A payment gateway is the class that turns "the customer pressed Place order" into "money was authorized or captured, and the order is now paid". In WooCommerce a gateway is a PHP class that extends WC_Payment_Gateway. It declares its settings, decides when it is available, handles the payment attempt in process_payment(), and optionally handles refunds. Everything else (the cart, the order, stock, emails) is done by WooCommerce around it.

This lesson shows the anatomy of a gateway, the two main flows (direct and redirect), refunds, order notes and availability rules, and finishes with a runnable fake gateway that charges idempotently. The real class needs WordPress and WooCommerce, so it is read-only; the stand-in is plain PHP and says exactly where it differs. For the money side of payments (authorize, capture, refund, 3-D Secure), read Payments Overview and Authorize, Capture and Refund first. Webhooks and security are the next lesson.

The life of a payment

sequenceDiagram
    participant S as Shopper
    participant W as WooCommerce
    participant G as Your gateway
    participant P as Payment provider
    S->>W: Place order
    W->>W: Create order (pending)
    W->>G: process_payment(order_id)
    G->>P: Create charge (idempotency key)
    P-->>G: Result
    G->>W: payment_complete() or on-hold
    G-->>W: array(result, redirect)
    W-->>S: Redirect to thank-you page

WooCommerce creates the order first; your gateway only decides what happens to it.

Note the order: the order already exists as pending before your code runs. If the payment fails, the order stays pending or becomes failed, and the customer can retry. Details of statuses are in Order Statuses and the Order Lifecycle.

A minimal gateway class

Here is the skeleton (read-only). Notice how little of it is about payments; most of it is configuration:

PHP
<?php
class Acme_Gateway extends WC_Payment_Gateway {

    public function __construct() {
        $this->id                 = 'acme_pay';          // unique, used in option and URL names
        $this->method_title       = __( 'Acme Pay', 'acme' );
        $this->method_description = __( 'Pay by card through Acme.', 'acme' );
        $this->has_fields         = false;               // true if you render fields at checkout
        $this->supports           = [ 'products', 'refunds' ];

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

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

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

    public function init_form_fields(): void {
        $this->form_fields = [
            'enabled' => [
                'title'   => __( 'Enable', 'acme' ),
                'type'    => 'checkbox',
                'label'   => __( 'Enable Acme Pay', 'acme' ),
                'default' => 'no',
            ],
            'title' => [
                'title'   => __( 'Title', 'acme' ),
                'type'    => 'text',
                'default' => __( 'Credit card', 'acme' ),
            ],
            'secret_key' => [
                'title' => __( 'Secret key', 'acme' ),
                'type'  => 'password',
            ],
        ];
    }
}

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

The pieces:

  • $id must be unique and stable. It becomes part of option names, hook names and the _payment_method stored on every order, so changing it later orphans old orders.
  • init_form_fields() describes the settings page, rendered for free under WooCommerce > Settings > Payments. The field array format is the same one you meet in Adding Settings Pages and Tabs. Keep gateway code in a class that is loaded after WooCommerce, from plugins_loaded (see Your First WooCommerce Extension), because WC_Payment_Gateway does not exist before that.
  • $supports is a promise: add 'refunds' only if you implement process_refund(), and 'tokenization' only if you handle saved methods.
  • A password field hides the value on screen but does not encrypt it in the database. Treat stored keys as secrets, never print them, and never log them (more in the next lesson).

process_payment()

This method does the work. It receives the order id and must return an array with result and redirect:

PHP
<?php
public function process_payment( $order_id ) {
    $order = wc_get_order( $order_id );

    try {
        $charge = $this->client()->charge( [
            'amount'          => (int) round( $order->get_total() * 100 ),
            'currency'        => $order->get_currency(),
            'idempotency_key' => $order->get_order_key() . '-' . $order->get_id(),
        ] );
    } catch ( Acme_Api_Exception $e ) {
        wc_add_notice( __( 'Payment failed. Please try another card.', 'acme' ), 'error' );
        $order->add_order_note( 'Acme charge failed: ' . $e->getCode() );   // no secrets, no card data
        return [ 'result' => 'failure' ];
    }

    if ( 'succeeded' === $charge['status'] ) {
        $order->payment_complete( $charge['id'] );     // sets status, stores transaction id, reduces stock
        $order->add_order_note( 'Acme charge ' . $charge['id'] . ' succeeded.' );
        WC()->cart->empty_cart();
    } else {
        $order->update_status( 'on-hold', 'Awaiting Acme confirmation.' );
    }

    return [
        'result'   => 'success',
        'redirect' => $this->get_return_url( $order ),
    ];
}

Points worth learning by heart:

  • Return failure, not an exception, for expected problems. wc_add_notice( ..., 'error' ) shows the message to the shopper. Use a friendly, generic text; put technical detail in an order note or the log.
  • payment_complete() is the finish line. It records the transaction id, moves the order to processing (or completed for virtual downloadable orders), and triggers stock reduction. Call it once; the next lesson explains why webhooks can make it run twice.
  • Amounts go to the provider in minor units, as integers. The conversion above multiplies a decimal string and rounds, which works for two-decimal currencies; zero-decimal currencies (JPY) differ, as shown in Representing Money Correctly.
  • Use an idempotency key so that a double click or a timeout-and-retry creates one charge, not two. See Idempotency.
  • Order notes are an audit trail. They are visible to admins (and optionally to customers), so never put card numbers, tokens or keys in them.

Direct versus redirect gateways

There are two main designs:

Direct (on-site) Redirect (hosted page)
Card fields On your checkout (has_fields = true), ideally provider-hosted iframes On the provider's page
process_payment returns Redirect to the thank-you page Redirect to the provider's payment URL
Order becomes paid In process_payment, or after a confirmation callback After the shopper returns and/or a webhook arrives
Security burden Higher (still use hosted fields so card data never touches your server) Lowest

For a redirect gateway, process_payment() creates a payment session at the provider, leaves the order pending (or on-hold), and returns the provider's URL as redirect. The order is marked paid only when the provider confirms, which usually means a webhook. Because the shopper might close the tab, never rely on the return trip alone. See PCI Scope and 3-D Secure for why hosted fields keep you out of the heaviest compliance level.

Refunds

When the gateway supports refunds, the admin's refund button calls process_refund():

PHP
<?php
public function process_refund( $order_id, $amount = null, $reason = '' ) {
    $order = wc_get_order( $order_id );
    $txn   = $order->get_transaction_id();

    if ( ! $txn || null === $amount || $amount <= 0 ) {
        return new WP_Error( 'acme_refund', __( 'Nothing to refund.', 'acme' ) );
    }

    try {
        $refund = $this->client()->refund( $txn, (int) round( $amount * 100 ) );
    } catch ( Acme_Api_Exception $e ) {
        return new WP_Error( 'acme_refund', __( 'The provider rejected the refund.', 'acme' ) );
    }

    $order->add_order_note( sprintf( 'Refunded %s (refund %s).', wc_price( $amount ), $refund['id'] ) );
    return true;
}

Return true on success and a WP_Error on failure; WooCommerce shows the error and does not record the refund. WooCommerce creates the refund object after your method returns true, so do not create one yourself. Make refunds idempotent too, and remember providers can refuse more than the captured amount.

Availability

A gateway can decide it is not usable for this cart. Override is_available(), or filter the list site-wide:

PHP
<?php
add_filter( 'woocommerce_available_payment_gateways', function ( array $gateways ): array {
    if ( is_admin() ) {
        return $gateways;                      // do not hide gateways on admin screens
    }
    if ( WC()->cart && WC()->cart->get_total( 'edit' ) < 5 ) {
        unset( $gateways['acme_pay'] );        // too small for this provider
    }
    return $gateways;
} );

Typical rules are minimum amounts, currency, country and shipping method. Check that a cart exists first, because this filter runs in places (such as admin or REST) where it does not.

Tokenization in one paragraph

Saved payment methods work through tokens: after a successful payment the provider returns a reusable reference (never the card number), and the gateway stores it as a WC_Payment_Token_CC for the customer. Next time the shopper picks "Use saved card" and process_payment() receives the token id. To support it you add 'tokenization' to $supports and implement the token saving and listing. Treat tokens as sensitive references: they can charge a card. The concept is explained in Payments Overview.

Runnable stand-in: a fake gateway with an idempotent charge

This is not WooCommerce: there is no WC_Order or hook system. The stand-in models the decisions a gateway makes: converting the amount, building an idempotency key, handling failures without leaking secrets, and ensuring that retries do not charge twice.

PHP Fake gateway: charge, retry and refund

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three calls reach the provider but only one charge exists, because the key is derived from the order. A real key should also change if the amount changes, so a modified cart is not silently treated as the same payment.

A second stand-in shows how availability rules compose:

PHP Gateway availability rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must process_payment() return for a successful payment?

    WooCommerce reads the returned array. result must be success or failure, and redirect is where the shopper is sent next, usually the thank-you page or the provider's payment page.
  2. 2. Why should a charge request carry an idempotency key?

    Timeouts and double clicks cause repeated requests. With the same key, the provider returns the original result instead of charging again.
  3. 3. When should a redirect-style gateway call payment_complete()?

    At the moment of redirect nothing has been paid. Marking the order paid early would fulfil unpaid orders.
  4. 4. What does adding 'refunds' to $supports promise?

    The refund button calls process_refund() on gateways that declare support, so the method must really talk to the provider and report success or failure.
  5. 5. Which of these may be written into an order note?

    Notes are an audit trail visible to admins. Keep identifiers and outcomes there, never secrets or card data.

Summary

  • A gateway extends WC_Payment_Gateway, declares settings in init_form_fields(), and is registered with the woocommerce_payment_gateways filter.
  • process_payment() returns result and redirect, uses wc_add_notice() for shopper-facing errors and payment_complete() once money is confirmed.
  • Direct gateways finish in the request; redirect gateways wait for a provider confirmation.
  • Support refunds only by implementing process_refund(); return true or a WP_Error.
  • Use idempotency keys, keep secrets out of notes and logs, and filter availability by amount, currency and country.
  • Block checkout needs an extra integration, see Cart and Checkout Blocks Extensibility.

Next: Webhooks, Signatures and Payment Security