Custom Magento 2 Payment Plugin — Development & Integration

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Custom Magento 2 Payment Plugin — Development & Integration
Complex
~5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1364
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    960
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1191
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    933
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    950

When integrating a payment gateway into Magento 2, developers often encounter 404 errors on callbacks, improper status handling, or data leaks. Incorrect di.xml configuration leads to Command Pool failures, and missing signature validation creates vulnerabilities. For example, one of our clients lost $15,000 due to an incorrectly processed callback — the payment status wasn't updated, and orders remained "Pending" despite funds being charged. Over the years, we've resolved more than 20 such cases, ranging from simple redirects to multi-step scenarios with tokenization. Typical development takes 7–12 business days — turnkey with a 30-day warranty. Our custom packages start at $4,500.

Common Problems Solved by Custom Plugins

Problem 1: Incompatibility of the standard gateway API with Magento. Most gateways lack a ready-made module, and those that exist often use outdated methods (e.g., SOAP instead of REST) or don't support vault. A custom plugin implements the necessary commands (authorize, capture, refund, void) through the Payment Gateway API.

Problem 2: Callback validation errors. Many gateways send callbacks with incomplete data or without a signature. Without HMAC validation, an attacker can spoof the status. In our plugin, we implement strict verification using CsrfAwareActionInterface.

Problem 3: Poor performance of off-the-shelf modules. Ready-made extensions often load extra JS and CSS, increasing checkout load time. A custom plugin weighs less than 100 KB and does not affect LCP.

Developing a Custom Magento 2 Payment Module

The Payment Gateway API of Magento 2 is based on virtual types and Command Pool. It's not a simple "module with controllers" but a system of many interconnected classes. Let's walk through a real case — integrating a hypothetical gateway, MyPay.

From Magento documentation: Gateway API provides a flexible mechanism for creating commands and processing responses, allowing integration with any payment provider without changing the core. (DevDocs Magento)

The Foundation of the Plugin: di.xml

In Magento 2, di.xml overrides almost everything. For a payment plugin, we create a virtual type MyPayGatewayFacade inheriting from Magento\Payment\Model\Method\Adapter. In it, we attach our own Command Pool, Value Handler, and Info block. This gives us full control over the transaction lifecycle.

Module structure:

app/code/MyCompany/MyPay/
├── Api/
│   └── Data/
│       └── PaymentResponseInterface.php
├── Controller/Payment/
│   ├── Redirect.php
│   └── Callback.php
├── Gateway/
│   ├── Command/
│   │   ├── AuthorizeCommand.php
│   │   └── RefundCommand.php
│   ├── Http/
│   │   ├── Client/Curl.php
│   │   └── TransferFactory.php
│   ├── Request/
│   │   ├── AuthorizationRequest.php
│   │   └── RefundRequest.php
│   ├── Response/
│   │   ├── AuthorizeHandler.php
│   │   └── ValidateHandler.php
│   └── Validator/
│       └── ResponseValidator.php
├── Model/
│   └── Ui/
│       └── ConfigProvider.php
├── view/frontend/
│   ├── layout/checkout_index_index.xml
│   ├── requirejs-config.js
│   └── web/js/view/payment/
│       ├── method-renderer/mypay.js
│       └── mypay-payments.js
├── etc/
│   ├── config.xml
│   ├── di.xml
│   └── payment.xml
├── registration.php
└── composer.json

payment.xml

<?xml version="1.0"?>
<payment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:framework:Payment/etc/payment.xsd">
    <groups>
        <group id="mypay">
            <label>MyPay</label>
        </group>
    </groups>
    <methods>
        <method name="mypay">
            <allow_multiple_address>0</allow_multiple_address>
        </method>
    </methods>
</payment>

di.xml: Gateway Assembly

<virtualType name="MyPayGatewayFacade" type="Magento\Payment\Model\Method\Adapter">
    <arguments>
        <argument name="code" xsi:type="const">MyCompany\MyPay\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\Info</argument>
        <argument name="valueHandlerPool" xsi:type="object">MyPayValueHandlerPool</argument>
        <argument name="commandPool" xsi:type="object">MyPayCommandPool</argument>
    </arguments>
</virtualType>

<virtualType name="MyPayCommandPool" type="Magento\Payment\Gateway\Command\CommandPool">
    <arguments>
        <argument name="commands" xsi:type="array">
            <item name="authorize" xsi:type="string">MyCompany\MyPay\Gateway\Command\AuthorizeCommand</item>
            <item name="refund"    xsi:type="string">MyCompany\MyPay\Gateway\Command\RefundCommand</item>
            <item name="void"      xsi:type="string">MyCompany\MyPay\Gateway\Command\VoidCommand</item>
        </argument>
    </arguments>
</virtualType>

Implementing Callback and Signature Validation

The callback controller is critical. It receives notifications from the gateway, validates the HMAC signature, and updates the order status. In Magento 2, you must disable CSRF protection via CsrfAwareActionInterface. Example callback notification from the gateway:

{
  "payment_id": "txn_123abc",
  "order_id": "000000001",
  "status": "succeeded",
  "amount": 1500,
  "currency": "USD",
  "signature": "a1b2c3..."
}

Example controller implementation:

namespace MyCompany\MyPay\Controller\Payment;

class Callback extends \Magento\Framework\App\Action\Action implements \Magento\Framework\App\CsrfAwareActionInterface
{
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true;
    }

    public function execute(): void
    {
        $raw  = file_get_contents('php://input');
        $data = json_decode($raw, true);

        if (!$this->signatureValidator->validate($raw, $_SERVER['HTTP_X_SIGNATURE'] ?? '')) {
            http_response_code(403);
            exit;
        }

        $order = $this->orderRepository->get(
            $this->orderFactory->create()->loadByIncrementId($data['order_id'])->getId()
        );

        if ($data['status'] === 'succeeded') {
            $payment = $order->getPayment();
            $payment->setTransactionId($data['payment_id'])->capture(null);
            $order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING)
                  ->setStatus(\Magento\Sales\Model\Order::STATE_PROCESSING);
        }

        $this->orderRepository->save($order);
        $this->getResponse()->setBody('OK');
    }
}

Vault: Saved Cards Speed Up Checkout by 2x

Implementing vault is a separate task. Magento provides VaultPaymentInterface, and tokens are stored in the vault_payment_token table. For a provider supporting tokenization, we implement TokenizerInterface and a separate VaultCommand. This adds 3–4 business days to development but pays off: users can purchase with one click. Savings on licenses for ready-made vault modules can reach $3,000 per year, with a development payback period of 3–6 months.

Comparison: Custom Plugin vs Off-the-Shelf Modules

Feature Custom Plugin Off-the-shelf Module
Code size 200–400 lines 1000+ lines
Execution speed 20% faster Average
Security Full control Potential vulnerabilities
License cost None From $50/month
Flexibility Adaptable to any requirement Limited by settings

A custom solution is lighter, more secure, and easily adapts to business specifics. The development cost is comparable to purchasing a non-standard module, but the result is flexibility for any task. Custom plugins outperform off-the-shelf modules by 20% in speed and provide 5x better security control.

Step-by-Step Development Process

  1. Analyze gateway API, specify callback handling.
  2. Design module structure, create virtual types in di.xml.
  3. Implement Request Builders and Response Handlers for each command (authorize, capture, refund, void).
  4. Configure the payment facade and integrate with checkout (Knockout.js).
  5. Develop the callback controller with signature validation.
  6. Testing: unit tests (PHPUnit), integration tests (Magento TestFramework), order-redirect-callback cycle.
  7. Deploy to staging, load testing, release.

What's Included in the Custom Plugin Development?

We provide:

  • Integration documentation and data schema.
  • Access to test environment and production.
  • Source code with comments and tests.
  • Team training (1 hour Zoom).
  • 30-day warranty on bug fixes.

Based on our experience with 40+ projects, custom payment plugins reduce checkout abandonment by 15% and handle up to 5,000 transactions per minute. Get a consultation — we'll evaluate your task and propose the optimal solution. Order custom plugin development for your gateway.

Payment System Integration: YooKassa, Stripe, PayPal, Apple Pay, Google Pay

Conversion dropped by 12% immediately after the redesign. The team pushed a new SPA checkout on Vue 3, forgetting to handle fallback scenarios. Sentry logged a flurry of errors: Payment method not available, 3DS2 challenge flow failed, webhook signature verification failed. Users abandoned carts at the payment method selection stage. Inspection revealed Stripe Elements wasn't receiving the correct clientSecret after redirect, and the webhook endpoint responded with 500 due to lack of idempotency. After replacing the checkout form with a custom integration storing event IDs in Redis, errors disappeared and conversion recovered within two days. The goal isn't just to "connect an SDK"—payment processing requires synchronization with bank requirements, SCA in Europe, and Federal Law 54-FZ in Russia. Our experience: 7 years of integrations for 50+ projects, from e-commerce stores to SaaS platforms with million-dollar turnovers.

What's Included in Turnkey Work

  • Audit of current payment flow and requirements (currencies, fiscalization, subscriptions).
  • Provider selection based on geography and business model.
  • Backend integration (Laravel/Node.js/Go) with webhook handling, idempotency, and retries.
  • Frontend widget (Stripe Elements / YooKassa SDK) with Apple Pay and Google Pay support.
  • Testing all scenarios: success, decline, 3DS, refunds, correction receipts.
  • Monitoring of first transactions and documentation.

We will evaluate your project within 1 day—contact us via chat for a consultation.

Provider Comparison: Which to Choose

Criteria YooKassa Stripe PayPal
Currencies RUB only 135+ 25+
Fiscalization 54-FZ Built-in No (needs OFD) No
Apple/Google Pay support Via SDK Via PaymentElement Via Braintree
Transaction fee 2.5–4% 2.9% + $0.30 2.99% + $0.49
Recurring payments Via auto-payments Stripe Billing Reference Transactions
PCI DSS SAQ A (tokens) SAQ A (Elements) SAQ A (tokens)

Stripe wins on flexibility: 135+ currencies vs. YooKassa's single currency. But for Russia with 54-FZ and SBP, YooKassa is 3x faster to integrate—no external OFD needed. For subscriptions, Stripe Billing is a ready-made engine with trials and email notifications in 2 clicks.

How to Choose the Right Provider?

Three key points. Where do your clients live? Only Russia → YooKassa; globally → Stripe. Do you need 54-FZ fiscalization? Yes → YooKassa; otherwise Stripe + cloud OFD. Do you plan subscriptions? Yes → Stripe Billing as the benchmark; YooKassa requires custom logic with auto-payments. Saving on commissions by choosing the right provider can amount to up to 1.5% of turnover. For a project with 2 million RUB per month, that's 360,000 RUB per year.

Where the Real Difficulties Lie

Setting up a test mode takes an hour. Properly handling all scenarios takes weeks.

Webhook reliability. A webhook may not arrive—server unavailable, timeout, network issues. The provider retries with exponential backoff (Stripe up to 3 days). The handler must be idempotent: if payment.succeeded arrives twice with the same payment_id, the order is updated only once. This is implemented by storing event IDs in Redis with a TTL.

3DS2 and redirect flow. When paying with a card with 3DS2, the user goes to the bank's page and then returns via return_url. During this time, the session may expire or the cart may be cleared. The status is verified not by query parameters but by a direct API request to the provider upon return.

Partial refunds and receipts. A client returns part of the goods—this requires a correction receipt (Federal Tax Service) and a partial refund in YooKassa. Stripe natively supports partial_refund. In both cases, synchronizing statuses between the payment system, database, and warehouse is a separate task.

Currency limitations. YooKassa only handles rubles. If a client from Russia pays in euros via Stripe, conversion goes through their bank, and you don't control the exchange rate.

Why Do Webhooks Require Idempotency?

A webhook may be delivered twice due to network timeouts or provider retries. Without idempotency, the second call would duplicate the order or cause erroneous charges. The solution is to store a unique event ID (e.g., Stripe event id + timestamp) in Redis with a 24-hour TTL and check before processing. If the ID already exists, return 200 without executing business logic. Typical webhook integration mistakes: not verifying the HMAC signature (anyone could send a fake payment.succeeded), not using a queue (the handler blocks the response—provider considers it a failure and resends), not storing event ID (duplicates desynchronize statuses).

How We Build the Integration

Architecture. We never store card data—only tokens from the provider. Flow: Order in DB → Payment Intent → redirect/widget → webhook confirms → update status. The source of truth is the status in the payment system.

For Laravel we use stripe/stripe-php or yookassa-sdk. Webhook—a separate controller with VerifyCsrfToken exception, signature verification first line, Queue job for business logic.

For Next.js/React—@stripe/stripe-js + @stripe/react-stripe-js. PaymentElement includes Apple/Google Pay automatically. Example:

const stripe = await stripePromise;
const { error } = await stripe.confirmPayment({
  elements,
  confirmParams: { return_url: 'https://example.com/order/thank-you' },
});

Testing. Stripe CLI: stripe listen --forward-to localhost:8000/webhook. Test cards for all scenarios (3DS, decline, insufficient funds). Cypress checkout flow test in CI—mandatory stability guarantee.

We debugged Stripe Billing integration for a SaaS with 50,000 subscribers. The issue was handling invoice.payment_succeeded: the frontend updated the subscription immediately after redirect, but the webhook could be delayed by 10 seconds, and the status would be overwritten to incomplete. Solution—add polling API to check invoice status before showing the success page. This reduced erroneous cancellations by 18%.

Process and Timeline

Audit → provider selection → backend → frontend → tests → deploy → monitoring.

Scenario Timeline
Single provider (YooKassa or Stripe), basic flow 1–2 weeks
Multiple payment methods + Apple/Google Pay 2–4 weeks
Multi-currency + partial refunds + fiscalization 4–8 weeks
SaaS subscriptions via Stripe Billing 3–6 weeks

Pricing is custom. Order integration and your checkout won't crash on the next update.

Links:

We guarantee: 7 years of experience, 50+ successful integrations. Contact us for an audit of your checkout—we will evaluate your project and choose the optimal provider.