MageDelight Featured Image

How to Disable a Payment Method Programmatically in Magento 2?

 

Today, we’re going to teach you guys how to disable a payment method in Magento 2.

Learning how to disable a payment method in your Magento 2 store is extremely crucial.

For starters, it helps to reduce the risk of fraudulent transactions. And it also helps to provide your customers with a seamless checkout experience.

This, in turn, can streamline the checkout process in your store and improve customer satisfaction & loyalty by managing payment methods efficiently.

And in this blog, we’re going to show you exactly how to disable a payment method in your Magento 2 store.

Step-by-Step Process to Disable a Payment Method in Magento 2

Please follow the below steps to learn how to disable a payment method programmatically in your Magento 2 store.

Step – 1

First of all, create an events.xml file in the app\code\Vendor\Extension\etc\ folder and copy the following code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="payment_method_is_active">
        <observer name="disable_payment" instance="Vendor\Extension\Observer\Paymentmethoddisable" />
    </event>
</config>

Step – 2

After that, create a Paymentmethoddisable.php file in the app\code\Vendor\Extension\Observer\ folder and paste the following code.

<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
class Paymentmethoddisable implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if($observer->getEvent()->getMethodInstance()->getCode()=="checkmo"){  // Here you can replace required payment method code
            $checkResult = $observer->getEvent()->getResult();
            $checkResult->setData('is_available', false); 
        }
    }
}

“Also Read: How to Restrict Some Payment Methods in Magento 2?

Conclusion

And that’s about it! This is how easy it is to disable a payment method programmatically in Magento 2.

If you want more control over your payment method you can use our Magento 2 Payment Restrictions Extension.

Check our Front & back-end demos to explore more exciting features of our extension.

Also, you can refer this Magento 2 Payment Restrictions Extension’s FAQ Page for most common questions and it’s answers.

And if you need our professional assistance, feel free to contact us at any time.

Tags