ARTICLE

Building a Custom Payment Method in Magento 2: Payment Config, the Method Adapter Facade, Gateway Commands, and Offline Methods

Building a Custom Payment Method in Magento 2: Payment Config, the Method Adapter Facade, Gateway Commands, and Offline Methods

A custom Magento 2 payment method is a module with three layers: a config.xml block under payment/your_code that sets title, payment action, and capabilities; a facade in di.xml, which is a virtual type of Magento\Payment\Model\Method\Adapter wired to value handler, validator, and command pools; and a checkout renderer that shows the method to shoppers.

The Adobe documentation explains each piece, but it does so with Braintree as the running example, spread across a dozen pages, and it leaves out the parts teams trip over in real projects: how payment actions map to command names, what an offline method actually needs, and what happens when the storefront uses Hyva Checkout instead of the Luma checkout. This guide puts the whole build in one place. If you are comparing ready-made gateways before deciding to build, read our comparison of Magento payment gateways on Hyva first, because building your own only makes sense when no maintained extension fits.

When to build a custom payment method at all

Most stores should not. Adobe, PSPs, and the extension market already cover the major card processors, wallets, and buy now pay later providers. Custom builds make sense in a narrower set of cases:

  • A regional or niche processor with no maintained Magento module.
  • A B2B payment flow, such as charging against an account in your ERP, that does not fit company credit.
  • An offline method with business rules, such as “pay at pickup” limited to certain stores or customer groups.
  • Replacing an abandoned extension whose code you would otherwise have to fork and own anyway.

In every one of these, the work is mostly integration and testing, not Magento plumbing. The plumbing is well defined once you see it end to end.

The module layout

A gateway-style method usually ends up looking like this:

app/code/ExampleCorp/Pay/
  registration.php
  etc/module.xml
  etc/config.xml            payment/examplecorp_pay defaults
  etc/adminhtml/system.xml  admin fields under Sales > Payment Methods
  etc/di.xml                facade, pools, commands
  etc/frontend/di.xml       checkout config provider
  Gateway/Request/          request builders
  Gateway/Http/             transfer factory and client
  Gateway/Response/         response handlers
  Gateway/Validator/        response and availability validators
  Model/Ui/ConfigProvider.php
  view/frontend/layout/checkout_index_index.xml
  view/frontend/web/js/view/payment/...   Luma checkout renderer
  view/frontend/web/template/payment/...  Knockout template

An offline method needs far less: config.xml, system.xml, the facade, and the renderer. No Gateway folder at all.

Step 1: payment options in config.xml

Every method’s defaults live in etc/config.xml under default, payment, and your method code. Adobe’s payment option configuration reference lists the standard keys:

Key What it does
model The facade virtual type that Sales and Checkout instantiate
active Enables the method
title Label shown at checkout and on the order
payment_action authorize or authorize_capture
can_authorize, can_capture, can_void Capability flags the order screens and the Adapter check
can_use_checkout Show on the storefront checkout
can_use_internal Allow in admin order creation
is_gateway Marks an online gateway method
order_status Status for new orders placed with this method
currency Allowed currency
debug, debugReplaceKeys Logging, with listed keys masked
privateInfoKeys, paymentInfoKeys Which additional_information keys are stored and shown
sort_order Position in the method list

Adobe’s own Braintree example also sets can_refund and can_cancel even though the table does not list them; any key you add is readable through the value handler pool, so the list is a starting set, not a limit. Note that the payment_action description in the same reference also mentions “sale”, which is the Braintree command name, not a config value. The values Magento’s Adapter reads are authorize and authorize_capture.

Add the matching admin fields in etc/adminhtml/system.xml under section payment so merchants can change title, credentials, and allowed countries per scope. Our guide to Magento 2 system.xml and config.xml covers field types, scopes, and encrypted backend models for API keys.

Step 2: the facade, a virtual type of the Adapter

The facade is the object Magento treats as “the payment method”. Instead of writing a class, you configure Magento\Payment\Model\Method\Adapter with a virtual type in di.xml. Adobe’s facade configuration docs list six arguments, all mandatory:

<virtualType name="ExampleCorpPayFacade" type="Magento\Payment\Model\Method\Adapter">
    <arguments>
        <argument name="code" xsi:type="const">ExampleCorp\Pay\Model\Ui\ConfigProvider::CODE</argument>
        <argument name="formBlockType" xsi:type="string">Magento\Payment\Block\Form</argument>
        <argument name="infoBlockType" xsi:type="string">Magento\Payment\Block\ConfigurableInfo</argument>
        <argument name="valueHandlerPool" xsi:type="object">ExampleCorpPayValueHandlerPool</argument>
        <argument name="validatorPool" xsi:type="object">ExampleCorpPayValidatorPool</argument>
        <argument name="commandPool" xsi:type="object">ExampleCorpPayCommandPool</argument>
    </arguments>
</virtualType>

The formBlockType is only used in the admin order form. infoBlockType renders payment details on the order view and emails; Adobe suggests the default ConfigurableInfo block for most cases, and it reads the keys you listed in paymentInfoKeys.

The value handler pool

The Adapter never reads config directly. It asks the value handler pool, which must have a default handler:

<virtualType name="ExampleCorpPayConfig" type="Magento\Payment\Gateway\Config\Config">
    <arguments>
        <argument name="methodCode" xsi:type="const">ExampleCorp\Pay\Model\Ui\ConfigProvider::CODE</argument>
    </arguments>
</virtualType>
<virtualType name="ExampleCorpPayConfigValueHandler" type="Magento\Payment\Gateway\Config\ConfigValueHandler">
    <arguments>
        <argument name="configInterface" xsi:type="object">ExampleCorpPayConfig</argument>
    </arguments>
</virtualType>
<virtualType name="ExampleCorpPayValueHandlerPool" type="Magento\Payment\Gateway\Config\ValueHandlerPool">
    <arguments>
        <argument name="handlers" xsi:type="array">
            <item name="default" xsi:type="string">ExampleCorpPayConfigValueHandler</item>
        </argument>
    </arguments>
</virtualType>

Add named handlers for values that need logic. A can_void handler, for example, can return false once an order is partially captured, without touching config.

The validator pool

The validator pool decides whether the method is available. The common entries are country, currency, availability, and global. A country validator can be Magento\Payment\Gateway\Validator\CountryValidator pointed at your config, which respects the “Payment from Applicable Countries” setting. Custom rules, such as hiding the method for orders over a limit or for a customer group, belong in a class extending AbstractValidator.

Step 3: gateway commands and the command pool

This is where an online method talks to the processor. Adobe’s gateway command docs describe the default command class, Magento\Payment\Gateway\Command\GatewayCommand, as a chain of five parts:

Part Interface Job
Request builder (required) Magento\Payment\Gateway\Request\BuilderInterface Turns the payment and order into an array for the API
Transfer factory (required) Magento\Payment\Gateway\Http\TransferFactoryInterface Wraps that array with URI, method, headers, and auth
Client (required) Magento\Payment\Gateway\Http\ClientInterface Sends the request and returns the decoded response
Validator (optional) Magento\Payment\Gateway\Validator\ValidatorInterface Checks the response and fails the command with messages
Handler (optional) Magento\Payment\Gateway\Response\HandlerInterface Writes transaction IDs and flags back to the payment

Each operation gets its own command, and the command pool maps operation names to them:

<virtualType name="ExampleCorpPayCommandPool" type="Magento\Payment\Gateway\Command\CommandPool">
    <arguments>
        <argument name="commands" xsi:type="array">
            <item name="authorize" xsi:type="string">ExampleCorpPayAuthorizeCommand</item>
            <item name="capture" xsi:type="string">ExampleCorpPayCaptureCommand</item>
            <item name="refund" xsi:type="string">ExampleCorpPayRefundCommand</item>
            <item name="void" xsi:type="string">ExampleCorpPayVoidCommand</item>
        </argument>
    </arguments>
</virtualType>

How payment actions map to command names

This is the part that confuses most first builds. The Adapter runs commands by name when the order lifecycle calls its methods:

Lifecycle event Adapter method Command name it runs
Order placed, payment_action authorize authorize() authorize
Order placed, payment_action authorize_capture capture() capture
Admin invoices an authorized order online capture() capture
Online credit memo refund() refund
Void from the order view void() void
Cancel on an authorized order cancel() cancel

Notice there is no “sale” in that list. Braintree registers a capture command that is itself a strategy: it checks whether an authorization exists and then runs either a settlement or a sale. If your processor has a one-step sale endpoint, you can do the same, or simply have the capture request builder detect that there is no prior authorization transaction and send a sale. Either way, the name the Adapter calls is capture.

The handler is where order state is set up for later steps. Store the processor’s transaction ID with setTransactionId(), set setIsTransactionClosed(false) on authorizations so a later capture can find the parent, and put anything the admin needs to see into additional_information. If you skip this, the online Refund button on credit memos will not appear, because Magento has no captured transaction to refund against. Our article on Magento 2 invoices, shipments, and credit memos explains that lifecycle from the merchant’s side.

Step 4: the checkout renderer

On the Luma checkout, Adobe’s add a payment method tutorial lays out the frontend pieces:

  1. A renderer component that extends Magento_Checkout/js/view/payment/default, with a Knockout template.
  2. A registration component that pushes your method code and renderer path into Magento_Checkout/js/model/payment/renderer-list.
  3. A checkout_index_index.xml layout update that adds the registration component under the billing step’s payment renders.
  4. Optionally, a ConfigProviderInterface class registered on Magento\Checkout\Model\CompositeConfigProvider in etc/frontend/di.xml, which exposes values like a public key on window.checkoutConfig.

Anything the customer enters, such as a token from the processor’s hosted fields, travels to the server in additional_data on the payment, and a data assign observer copies it into the payment’s additional_information where your request builder can read it. Never let raw card numbers reach your server. Use the processor’s hosted fields or tokenization so the store stays out of the heaviest PCI scope.

What changes with Hyva Checkout

Hyva Checkout replaces the Knockout checkout with server-rendered components built on Magewire and Alpine.js, so the renderer from Step 4 does not apply there. Everything from Steps 1 to 3 stays the same: config, facade, pools, and commands are PHP and do not care which checkout collected the payment.

In practice:

  • A method with no customer input, like most offline methods, generally appears in Hyva Checkout from its config alone.
  • A method with fields or a processor SDK needs a Hyva Checkout integration: a template, usually with a Magewire component, that collects the token and writes it to the payment’s additional data before the order is placed.
  • If you keep the Luma checkout on a Hyva theme through the fallback approach, the Knockout renderer still works on that route.

Budget for the Hyva Checkout integration as its own task with its own tests. Our Hyva Checkout cost, compatibility, and rollout guide covers how payment compatibility fits into a checkout migration, and our Hyva development services page explains how we scope that work.

Offline methods: the short path

An offline method, like “pay by invoice” or “pay at pickup”, has no gateway calls. The core examples live in Magento_OfflinePayments: check or money order, bank transfer, cash on delivery, and purchase order. Those core classes still extend the older Magento\Payment\Model\Method\AbstractMethod, which carries a deprecation note in favor of the Adapter, so treat them as a reference for config and templates rather than for the class structure.

For new code, the Adapter works for offline methods too:

  • Leave payment_action out of config, as the core check or money order method does. Order placement only runs authorize or capture when a payment action is set, so the order is placed without calling any command, and the merchant invoices it offline.
  • Keep the command pool empty and the can_authorize and can_capture flags off, so nothing tries to reach a gateway that does not exist.
  • Put your availability rules in the validator pool, such as allowed stores, customer groups, or a minimum order total.
  • Set order_status to pending or a custom status so the team knows payment has not been collected.

Testing before go-live

  • Sandbox credentials per environment. Store them as encrypted config, and keep production keys out of staging databases.
  • Every lifecycle path. Authorize then capture, authorize_capture, partial invoice, partial refund, void, and cancel. Each one runs a different command.
  • Admin order creation, if can_use_internal is on, because it uses formBlockType instead of the storefront renderer.
  • Declines and timeouts. Your response validator should turn processor errors into clear messages without exposing raw API output to shoppers.
  • Logging with masking. Use debugReplaceKeys so tokens and keys never land in logs.

For end to end coverage of the checkout UI itself, the same Playwright approach we use for Hyva storefronts works for payment flows. Payment code is the last place to cut testing corners, and it is usually the first thing an upgrade or a processor API change breaks.

Beyond Magento

On other platforms the pattern is different. Shopify restricts payment integrations to approved payments apps, so most custom flows on our Shopify development projects use existing providers. Shopware development uses payment handlers registered as services. On BigCommerce development work, payments run through the platform’s supported gateways and its payments API. Magento gives you the most control of the four, which is also why the build and the testing take more care. That depth is the core of our Magento development services.

FAQ

What is the Magento 2 payment method facade?

It is a virtual type of Magento\Payment\Model\Method\Adapter configured in di.xml with a method code, form and info blocks, a value handler pool, a validator pool, and a command pool. The config.xml model key points to it, and Magento treats it as the payment method.

Why does my custom payment method not show at checkout?

Check active and can_use_checkout in config, the allowed countries and currency, and every validator in the validator pool, since any failing one hides the method. On Luma checkout, also confirm the renderer is registered in checkout_index_index.xml. On Hyva Checkout, a method with custom fields needs its own Hyva Checkout integration.

What is the difference between authorize and authorize_capture?

With authorize, placing the order only reserves funds and the merchant captures later when invoicing. With authorize_capture, the Adapter runs the capture command at order placement and the invoice is created right away. The choice is the payment_action value in config.xml.

Is AbstractMethod still usable for Magento payment methods?

It still works, and the core offline methods extend it, but it carries a deprecation note in favor of the Adapter with gateway commands. New methods should use the Adapter facade.

Why is the online Refund button missing on credit memos?

Magento only offers an online refund when the invoice was captured online and the payment has a capture transaction to refund against. Make sure your capture response handler sets the transaction ID and that can_refund is true in config.

Bemeir is a Brooklyn ecommerce agency that builds Magento, Adobe Commerce, and Hyva storefronts; read more about Bemeir, see our technology partners, or get in touch at Bemeir.

Let us help you get started on a project with Building a Custom Payment Method in Magento 2: Payment Config, the Method Adapter Facade, Gateway Commands, and Offline Methods and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.