EN
Magento Updated

How to Create Magento 2 Payment Module: Simple Solution with Great Capabilities

Jane Vyshnova

Jane Vyshnova

CEO

Author

How to Create Magento 2 Payment Module: Simple Solution with Great Capabilities

Time to read: 10 minutes

Content

  1. Case Description
  2. Acceptance Checklist for a Magento 2 Payment Module
  3. Why Start with Magento?
  4. What Magento Can Do for You
  5. How to Create Magento 2 Payment Module: Basic Tips for the Process
  6. Hiring Web Developers to Develop a Payment Module
Bookmark

Build a Magento 2 payment module on Magento's payment gateway framework, test every money movement against an acceptance checklist, and agree that checklist with your developer before work starts. Technically, that means not the old AbstractMethod class, which Magento marks as deprecated, but a module that depends on Magento_Sales, Magento_Payment and Magento_Checkout; default settings in etc/config.xml; a payment method facade, declared in etc/di.xml as a virtual type of Magento\Payment\Model\Method\Adapter; one gateway command per payment action (authorise, capture, void, refund), each with a request builder, transfer factory, client, validator and handlers; and a checkout renderer made of a layout file, two JavaScript components and a template. The checklist below covers the money movements to test, including refunds and failed payments.

Online payment providers want their services to work on as many commerce platforms as possible, so they publish modules or plugins for each one. If your company runs its own payment service or needs a payment flow that existing modules do not cover, you need the same: a payment module for each platform. This article shows how a Magento 2 payment module is put together, based on Adobe's developer documentation (checked on 18 November 2026) and Dinarys' work on payment modules. All code is illustrative: it shows the structure, not a production-ready integration.

Case Description

Dinarys has developed payment modules for a payment company and for a European crypto ecosystem. For ConnectPay, a Lithuanian e-money institution, Dinarys built modules for Magento and Shopware that let stores collect payments from customer bank accounts in the Netherlands, Germany, Finland and Lithuania. The modules include:

The team also prepared guides and instructions for uploading the modules to the Magento and Shopware marketplaces. (For the Shopware side, see how to choose the right Shopware payment gateway.) In a separate project, Dinarys developed a crypto payment plugin for a European crypto ecosystem, covering Magento and WooCommerce among other platforms and CMSs, with documentation detailed enough for merchants to install and configure it themselves.

Those four parts, plus documentation, are a good outline for most payment modules, and they map onto the steps below.

Acceptance Checklist for a Magento 2 Payment Module

Whether you build the module in-house or hire developers, agree on this checklist before development starts and run it on a staging store connected to the provider's sandbox.

ScenarioExpected result in MagentoWhere to check
Successful paymentOrder created with the right status; transaction ID stored on the paymentOrder view, Transactions tab
Declined paymentNo paid order; clear message; the buyer can retry with the cart intactStorefront checkout; order grid
Buyer abandons the provider's page (redirect flows)Order not marked as paid; it is cancelled or left pending according to your ruleOrder view; scheduled clean-up
Duplicate notification from the providerStatus updated once; no duplicate invoice or transactionOrder history and transactions
CaptureInvoice created and captured amount matches the provider's recordInvoice; provider dashboard
Void or cancel before captureAuthorisation released; order cancelledOrder view; provider dashboard
Full refundCredit memo issued online; refund confirmed by the providerCredit memo; provider dashboard
Partial refundOnly the selected items or amount refundedCredit memo; provider dashboard
CurrenciesAmount and currency sent match the orderRequest log with secrets masked
Configuration scopeMethod can be switched on, titled and limited per website or store viewStores > Settings > Configuration > Sales > Payment Methods
LogsRequests and responses logged for debugging with keys and personal data maskedPayment log files
Anatomy of a Magento 2 payment module Storefront: the checkout layout file declares a JavaScript component that registers the method renderer; the renderer uses a template; a config provider passes settings to checkout. Placing the order calls the back end. Back end: the payment method facade, a virtual type of the Magento Payment Method Adapter declared in di.xml, uses a value handler pool for configuration, a validator pool and a command pool. Each gateway command, such as authorise, capture, void or refund, runs a request builder, a transfer factory and a client that calls the provider's API, then a response validator and response handlers that update the order payment. Storefront checkout Back end Layout filecheckout_index_index.xml JS componentregisters the renderer Method rendererand its template Config provideretc/frontend/di.xml Payment method facade Adapter virtual type, declared in etc/di.xml Value handlerpool (config) Validatorpool Commandpool Gateway command authorise, capture, void or refund Request builder Transfer factory Client Provider API Responsevalidator Responsehandlers Order payment Placing the order calls the facade (arrow from the method renderer). Illustrative structure based on Adobe Commerce developer documentation and Magento's sample payment gateway module.
How the parts of a Magento 2 payment module fit together: the checkout renderer on the storefront, and the facade with its gateway commands in the back end.

Why Start with Magento?

Magento suits payment modules because its payment architecture separates the checkout interface from the communication with the provider. When you create a custom payment module in Magento 2, you define the fields the buyer interacts with at checkout and the API logic used to carry out each payment action, and the gateway framework gives that logic a consistent structure that can be maintained and extended later.

Magento is also available in two editions: Magento Open Source, free under the Open Software License 3.0, and Adobe Commerce, licensed commercially by Adobe. The same module structure applies to both, which makes one well-built module useful to a wide range of merchants.

What Magento Can Do for You

Magento supports a range of ready-made payment methods and integrations with payment providers, which create and process transactions based on order details. If you need more than the standard set, you can create a payment module and connect your store to almost any third-party payment service. Magento's web APIs can also place orders, so if you support headless storefronts, plan how your method passes its data through them.

Security needs care. Adobe's documentation recommends the payment gateway framework for new integrations and states that, to keep PCI compliance, you must not store sensitive credit card information. Neither Magento nor a payment module makes a store PCI compliant on its own: PCI DSS applies to entities that store, process or transmit cardholder data, and which validation a merchant needs is set by the payment brands and confirmed by the merchant's acquirer. The safest design for most modules is to let the provider collect card data through its hosted page or embedded fields and to pass only tokens and transaction references through Magento.

How to Create Magento 2 Payment Module: Basic Tips for the Process

Before writing code, decide which payment provider and payment methods the module will support, which payment actions it needs and how many methods buyers will see. Make sure the team has sandbox access and all the credentials the provider requires, such as API keys, secret keys and signing keys, so that the module can be tested end to end. If the store sells in several currencies, check which currencies the provider accepts for each method.

The steps below follow Adobe's payment integration documentation and its sample payment gateway module. Names such as Acme_Pay and acme_pay are placeholders. Adobe states that the sample module's code is not supported, so treat it as a structural reference only.

Step 1: Choose the payment flow

Decide how the buyer pays. With a redirect or hosted payment page, the buyer completes the payment on the provider's side and comes back to the store; with embedded fields, the provider's script collects the card data inside your checkout and returns a token; with a server-to-server flow, Magento calls the provider directly with a token or reference. List the payment actions you need: authorise only, authorise and capture, capture on invoice, void and refund. This choice decides which commands and which checkout behaviour you build.

Step 2: Declare the module and its dependencies

Register the module with registration.php and declare it in etc/module.xml. Adobe's documentation lists the dependencies: Magento_Sales to get order details, Magento_Payment for the gateway infrastructure and Magento_Checkout to add the method to checkout (optional if the storefront checkout is not used). Add them to the sequence element in module.xml and to the require section of composer.json. Do not edit Magento's core code: keep all customisations in your own module so that upgrades stay possible.

Step 3: Set defaults and admin settings

Default values go in etc/config.xml under the payment section and your method code. Adobe's documentation describes the main options: model names the payment method facade, active enables the method by default, title sets the name buyers see, payment_action is authorize or authorize_capture, and flags such as can_authorize declare what the method supports. Admin fields go in etc/adminhtml/system.xml; store API keys with Magento's encrypted backend model (Magento\Config\Model\Config\Backend\Encrypted) rather than in plain text.

Step 4: Configure the payment method facade and gateway commands

The facade is the entity that carries out payment actions between Magento's sales management and the payment provider. You declare it in etc/di.xml as a virtual type of Magento\Payment\Model\Method\Adapter, instead of writing a payment model class:

<virtualType name="AcmePayFacade" type="Magento\Payment\Model\Method\Adapter">
    <arguments>
        <argument name="code" xsi:type="const">Acme\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">AcmePayValueHandlerPool</argument>
        <argument name="commandPool" xsi:type="object">AcmePayCommandPool</argument>
    </arguments>
</virtualType>

The value handler pool reads the method's configuration, an optional validator pool checks, for example, that the method is allowed for the billing country, and the command pool lists one gateway command per payment action. Each command is usually a virtual type of Magento\Payment\Gateway\Command\GatewayCommand, which Adobe describes as the default command implementation: it takes a request builder and a transfer factory, a client that calls the provider and, optionally, a response validator and a response handler.

Many older tutorials suggest a Model/Payment/Simple.php class extending AbstractMethod. Magento's source marks AbstractMethod as deprecated and points to the Adapter facade and the gateway framework instead, so new modules should follow the structure above.

Step 5: Implement the request builder, client, validator and handler

Each gateway command needs a few small classes. The request builder turns order data into the provider's request:

namespace Acme\Pay\Gateway\Request;

use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;

class AuthorizeRequest implements BuilderInterface
{
    public function build(array $buildSubject): array
    {
        $paymentDO = SubjectReader::readPayment($buildSubject);
        $order = $paymentDO->getOrder();

        return [
            'merchant_reference' => $order->getOrderIncrementId(),
            'amount' => SubjectReader::readAmount($buildSubject),
            'currency' => $order->getCurrencyCode(),
        ];
    }
}

The client implements Magento\Payment\Gateway\Http\ClientInterface and sends the request to the provider's API; the response validator checks the result; and a response handler writes it to the order payment:

namespace Acme\Pay\Gateway\Response;

use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Response\HandlerInterface;

class TransactionIdHandler implements HandlerInterface
{
    public function handle(array $handlingSubject, array $response): void
    {
        $payment = SubjectReader::readPayment($handlingSubject)->getPayment();
        $payment->setTransactionId($response['transaction_id']);
        $payment->setIsTransactionClosed(false);
    }
}

For redirect flows and provider notifications, you will also need a controller that receives the buyer's return or the provider's callback, verifies its signature with the provider's method and updates the order only once, even if the same notification arrives twice.

Step 6: Add the payment method to checkout

The payment method's interface at checkout is a UI component. Adobe's checkout tutorial describes four pieces. Create view/frontend/layout/checkout_index_index.xml in your module and declare your component under the payment step (checkout > steps > billing-step > payment > renders). The component registers your renderer in the renderer list:

define([
    'uiComponent',
    'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
    'use strict';

    rendererList.push({
        type: 'acme_pay',
        component: 'Acme_Pay/js/view/payment/method-renderer/acme_pay'
    });

    return Component.extend({});
});

The renderer usually extends Magento's default payment renderer and points to your template in view/frontend/web/template/:

define([
    'Magento_Checkout/js/view/payment/default'
], function (Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Acme_Pay/payment/form'
        }
    });
});

For a redirect flow, set the renderer not to redirect to the success page after the order is placed and send the buyer to the provider in its afterPlaceOrder step instead. Settings the checkout needs, such as the method title or the provider's public key, are passed through a config provider class registered with Magento\Checkout\Model\CompositeConfigProvider in etc/frontend/di.xml.

Step 7: Work with caches and generated code

Keep caches enabled during development and clean only what your change affects, which is faster than switching caches off. Adobe's documentation lists what to clear:

Developer mode generates these files on demand. If you work with LESS styles, the bin/magento dev:source-theme:deploy command collects and publishes source files for a theme, which replaces the non-existent bin/magento/dev:css:deploy command quoted in some older guides. The older advice to clear var/di and var/generation applies to early Magento 2 versions, which used those folders before generated code moved to generated/.

Step 8: Test every money movement

Run the acceptance checklist above on staging with the provider's sandbox, then repeat the key scenarios on production with a small real payment and a refund. Establishing trust is critical when you handle customers' financial data, so the team that builds the module also needs the time and people to test it at every stage of development. Document installation and configuration for merchants, as Dinarys did for the crypto payment plugin, and prepare marketplace upload guides, as for ConnectPay, if you plan to distribute the module through Adobe Commerce Marketplace or another channel.

Hiring Web Developers to Develop a Payment Module

Building software that handles payment data is not easy. You can use existing modules, but they may be outdated, unsupported or missing the functionality you need, and most companies do not have a spare team for a separate payment project. An experienced Magento team can compare the available modules, tell you what to keep and what to build, and deliver the module with tests and documentation.

When you compare developers, ask:

Dinarys develops and integrates payment extensions for existing stores, so you can extend your store's payment options without changing platform. See our Magento extension development services.

Do you have a similar project in mind? Contact our team to discuss your requirements and find the best solution to your challenge.

Lassen Sie Profis Ihre Herausforderung meistern

Unsere zertifizierten Spezialisten finden die optimale Lösung für Ihr Unternehmen.

Bitte einen gültigen Namen eingeben
Bitte geben Sie ein gültiges Unternehmen ein
Bitte geben Sie eine gültige Telefonnummer an
Bitte geben Sie eine gültige E-Mail-Adresse ein
Kurze Botschaft

    Ihre Nachricht wurde erfolgreich verschickt. Wir melden uns in Kürze! Success icon