Disable a Payment Method Programmatically in Magento 2

Payment system management can be considered as one of the cores of the Magento 2 store system as a good handling system can help you optimize your sales, profits as well as your efforts.

Sometimes, you will want to restrict specific payment methods based on the customer groups, product/order attributes, shipping parameters, etc. In other words, it’s time when you can programmatically disable a payment method from your Magento 2 backend configuration. For example, with customers who are coming from India, you can deactivate other payment methods and only display the CCAvenue method.

In today’s article, I will show you 2 simple stages to disable payment method programmatically in Magento 2.

2 Steps to Disable a Payment Method Programmically in Magento 2:

Step 1: Edit config.xml file

To disable the Payment Method Programmatically, firstly, you need to open the config.xml file and then add the following code to that file:

<global>
    ...
    <events>
        <payment_method_is_active>
            <observers>
                <disable_paymentmethod>
                    <class>Vendor_Extension_Model_Observer</class>
                    <method>paymentMethodIsActive</method>
                </disable_paymentmethod>
            </observers>
        </payment_method_is_active>
    </events>
    ...
</global>

Step 2: Edit Observer.php file

In this step, the below code should be added in the Observer.php file

<?php
class Vendor_Extension_Model_Observer {
    public function paymentMethodIsActive(Varien_Event_Observer $observer) {
        $method = $observer->getMethodInstance();
        
        if ($method->getCode() == 'payment_method_code') {
            
            if (condition) {
                $result = $observer->getResult();
                $result->isAvailable = false;
            }
        }
        
    }
}

Related Post:

Conclusion

That’s all about how to disable a Payment Method Programmically. Implement these stages correctly, you can control the payment methods choices at your checkout page according to different conditions. For the full solution to restrict payment choices, you can view Mageplaza Payment Restrictions module.

I hope this tutorial is helpful for you. If you have any question about this topic or face any issue while following the steps, feel free to let me know.

Thanks for reading!

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.
x