Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Real-World Projects

Project: A Bank-Transfer-Style Gateway

Build an offline bank-transfer style WooCommerce payment gateway: settings, on-hold order flow, payment reference, instructions in emails, manual matching and refunds.

Most gateway tutorials build a card gateway that talks to a provider. This project builds the opposite: an offline gateway, where the shopper pays by bank transfer and the shop owner confirms the money arrived. It is a great exercise because it has no provider SDK to hide behind. You must handle every step yourself: the order waits in on-hold, the customer needs clear instructions in the thank-you page and the email, the payment must be matched to the order by a reference, and the owner needs a safe way to confirm it.

The class is shown read-only (it needs WooCommerce). The matching and status rules are written as plain PHP so you can run them. If you have not yet read Building a Payment Gateway, do that first; the money concepts are in Payments Overview.

The flow we are building

stateDiagram-v2
    [*] --> pending: Customer places order
    pending --> on_hold: process_payment()
    on_hold --> processing: Transfer matched
    on_hold --> cancelled: Expired or declined
    processing --> completed: Order shipped
    processing --> refunded: Refund sent

The gateway moves the order to on-hold and waits; a person or an import moves it forward.

There is no webhook here, so "confirmation" is a human decision (or a bank-statement import). That is why matching and audit notes matter more than in an automated gateway.

Step 1: the gateway class and settings

PHP
<?php
class Acme_Transfer_Gateway extends WC_Payment_Gateway {

    public function __construct() {
        $this->id                 = 'acme_transfer';
        $this->method_title       = __( 'Bank transfer (Acme)', 'acme-transfer' );
        $this->method_description = __( 'Customers pay by bank transfer; you confirm the payment.', 'acme-transfer' );
        $this->has_fields         = false;
        $this->supports           = [ 'products', 'refunds' ];

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

        $this->title        = $this->get_option( 'title' );
        $this->description  = $this->get_option( 'description' );
        $this->instructions = $this->get_option( 'instructions' );

        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
        add_action( 'woocommerce_thankyou_' . $this->id, [ $this, 'thankyou_page' ] );
        add_action( 'woocommerce_email_before_order_table', [ $this, 'email_instructions' ], 10, 3 );
    }

    public function init_form_fields(): void {
        $this->form_fields = [
            'enabled'      => [ 'title' => __( 'Enable', 'acme-transfer' ), 'type' => 'checkbox', 'label' => __( 'Enable bank transfer', 'acme-transfer' ), 'default' => 'no' ],
            'title'        => [ 'title' => __( 'Title', 'acme-transfer' ), 'type' => 'text', 'default' => __( 'Bank transfer', 'acme-transfer' ) ],
            'description'  => [ 'title' => __( 'Checkout text', 'acme-transfer' ), 'type' => 'textarea', 'default' => __( 'Pay by transfer. Your order ships when the money arrives.', 'acme-transfer' ) ],
            'iban'         => [ 'title' => __( 'IBAN', 'acme-transfer' ), 'type' => 'text' ],
            'account_name' => [ 'title' => __( 'Account holder', 'acme-transfer' ), 'type' => 'text' ],
            'instructions' => [ 'title' => __( 'Extra instructions', 'acme-transfer' ), 'type' => 'textarea', 'desc_tip' => true ],
            'expiry_days'  => [ 'title' => __( 'Cancel after (days)', 'acme-transfer' ), 'type' => 'number', 'default' => '7' ],
        ];
    }
}

The bank details are not secrets in the way an API key is (customers see them), but they are integrity-sensitive: whoever can edit the settings can redirect payments. Only users with manage_woocommerce reach this screen, and you should log changes. Validate the IBAN format in a validate_iban_field() method (WooCommerce calls validate_{key}_field() when saving settings, see Adding Settings Pages and Tabs). WooCommerce already ships an offline "Direct bank transfer" gateway; building your own is about learning, or about adding behaviour (references, matching, expiry) the built-in one lacks.

Step 2: process_payment() puts the order on hold

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

    $reference = Acme_Reference::for_order( $order->get_id() );
    $order->update_meta_data( '_acme_payment_reference', $reference );
    $order->update_status(
        'on-hold',
        sprintf( __( 'Awaiting bank transfer, reference %s.', 'acme-transfer' ), $reference )
    );
    $order->save();

    WC()->cart->empty_cart();

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

Key points:

  • No payment_complete(). Nothing is paid yet. The order sits in on-hold, which is the status for "waiting for a payment or action outside WooCommerce". WooCommerce reduces stock when an order enters on-hold, so the goods are reserved without extra code (see Order Statuses and the Order Lifecycle).
  • A reference per order lets the owner (or an import) match the incoming money. Use the CRUD update_meta_data(), which is correct with HPOS (Orders and High-Performance Order Storage).
  • Unpaid on-hold orders do not expire by themselves. The built-in job that cancels unpaid orders applies to pending orders. Your gateway needs its own expiry, scheduled with Action Scheduler, or stock stays locked forever by customers who never pay.

Step 3: instructions in the thank-you page and email

PHP
<?php
public function thankyou_page( $order_id ): void {
    $order = wc_get_order( $order_id );
    echo wp_kses_post( wpautop( wptexturize( $this->instructions ) ) );
    echo '<ul class="order_details">';
    printf( '<li>%s <strong>%s</strong></li>', esc_html__( 'Account holder:', 'acme-transfer' ), esc_html( $this->get_option( 'account_name' ) ) );
    printf( '<li>%s <strong>%s</strong></li>', esc_html__( 'IBAN:', 'acme-transfer' ), esc_html( $this->get_option( 'iban' ) ) );
    printf( '<li>%s <strong>%s</strong></li>', esc_html__( 'Reference:', 'acme-transfer' ), esc_html( (string) $order->get_meta( '_acme_payment_reference' ) ) );
    printf( '<li>%s <strong>%s</strong></li>', esc_html__( 'Amount:', 'acme-transfer' ), wp_kses_post( wc_price( $order->get_total(), [ 'currency' => $order->get_currency() ] ) ) );
    echo '</ul>';
}

public function email_instructions( $order, $sent_to_admin, $plain_text = false ): void {
    if ( $sent_to_admin || $order->get_payment_method() !== $this->id || ! $order->has_status( 'on-hold' ) ) {
        return;
    }
    $this->thankyou_page( $order->get_id() );
}

Two rules to follow. First, only show instructions while the order is on hold; once the money arrived, the email must not ask for it again. Second, the instructions are repeated in the "order on hold" email, because shoppers lose thank-you pages but keep emails. This hook prints HTML; a plain-text variant should print plain text, see Custom Transactional Emails. All values are escaped at output.

Step 4: webhook-less confirmation

You have three realistic ways to confirm a payment:

  1. Manual: the owner checks the bank, opens the order and changes the status to Processing. Cheap, error-prone, but zero code. Add a note field or a custom order action ("Mark transfer received") that records who confirmed and when.
  2. CSV import: the owner uploads the bank statement; your code matches lines to orders by reference and amount (the runnable example below).
  3. Bank API / open banking: a scheduled job pulls transactions. This is a webhook-less integration, so it must be idempotent and handle duplicates (see Idempotency).

A custom order action keeps the audit trail clean:

PHP
<?php
add_filter( 'woocommerce_order_actions', function ( array $actions ): array {
    $actions['acme_mark_received'] = __( 'Mark bank transfer received', 'acme-transfer' );
    return $actions;
} );

add_action( 'woocommerce_order_action_acme_mark_received', function ( WC_Order $order ) {
    if ( ! current_user_can( 'edit_shop_orders' ) || ! $order->has_status( 'on-hold' ) ) {
        return;
    }
    $order->payment_complete();     // moves to processing or completed, stock already reduced
    $order->add_order_note( sprintf( 'Transfer confirmed by user %d.', get_current_user_id() ) );
} );

Call payment_complete() only for on-hold or pending orders, so a double click cannot confirm twice.

Step 5: refunds

An offline gateway cannot move money itself. Still, you can support the refund button so that the record in WooCommerce stays accurate, and make clear that the actual bank transfer is the owner's job:

PHP
<?php
public function process_refund( $order_id, $amount = null, $reason = '' ) {
    $order = wc_get_order( $order_id );
    if ( null === $amount || (float) $amount <= 0 ) {
        return new WP_Error( 'acme_refund', __( 'Enter an amount to refund.', 'acme-transfer' ) );
    }
    $order->add_order_note( sprintf(
        'Refund of %s recorded. Send the money back manually from the bank account. %s',
        wc_price( $amount ),
        $reason ? 'Reason: ' . wc_clean( $reason ) : ''
    ) );
    return true;
}

Returning true makes WooCommerce create the refund record. The note reminds the owner that nothing was sent. For bigger shops, add a "refund IBAN" field on the order and a task list of pending payouts.

Step 6: checkout blocks

The block-based checkout does not use the classic payment_fields() rendering. A gateway needs a small PHP class extending AbstractPaymentMethodType and a JavaScript registration with registerPaymentMethod(); for an offline gateway the JavaScript only needs a label and a description element. Without it the gateway silently does not appear in a block checkout. Declare compatibility only after you added it (Cart and Checkout Blocks Extensibility).

Runnable stand-in: references, matching and expiry

The following code is not WooCommerce. It models the rules the gateway needs: a reference with a check digit that survives sloppy typing, matching of bank lines to on-hold orders, and detection of amounts that are too low, too high or already used.

PHP Reference codes and statement matching

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.

Notice the last line: the same payment arriving twice is ignored because the order is no longer on hold. That is the idempotency rule in action. The "underpaid" case is deliberately not auto-confirmed.

A second stand-in is the expiry sweep your scheduled action would run:

PHP Expiring unpaid on-hold orders

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.

In the real plugin the loop would query wc_get_orders( [ 'status' => 'on-hold', 'payment_method' => 'acme_transfer', 'date_created' => '<' . $cutoff, 'limit' => 50 ] ) and call $order->update_status( 'cancelled', ... ); cancelling returns the reserved stock automatically.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status should an offline gateway use after process_payment() when the shopper still has to pay?

    On-hold means the order waits for something outside WooCommerce. It reserves stock and is not fulfilled until someone confirms the money.
  2. 2. Why include a check digit in the payment reference?

    Customers retype references by hand. A check digit catches most single-digit errors and swaps, so mistaken lines go to manual review instead of confirming the wrong order.
  3. 3. What prevents the same bank line, imported twice, from confirming an order twice?

    Status checks make the confirmation idempotent. After the first match the order is processing, so the duplicate is ignored.
  4. 4. Why does a bank-transfer gateway need its own expiry job?

    Without an expiry, customers who never pay block stock indefinitely. A scheduled action cancels old on-hold orders and releases the stock.
  5. 5. What does returning true from process_refund() do for an offline gateway?

    The method only reports success. For an offline method the note should remind the owner to send the money back manually.

Summary

  • An offline gateway puts the order on hold, shows payment instructions, and waits for a person or an import to confirm.
  • Generate a reference with a check digit, store it with the CRUD API, and match incoming money by reference and amount.
  • Show instructions only while the order is on hold, in the thank-you page and the email, escaping every value.
  • Confirm payments idempotently, flag under- and overpayments, and expire unpaid orders with a scheduled action.
  • Support refunds as records, add block checkout support, and log who changed the bank details.

Next: Project: Delivery Date Slots