Magento 2: Disable Payment Method Programmatically

Magento 2: Disable Payment Method Programmatically

Effective payment system is crucial to an ecommerce’s success. As an International E-commerce store owner, your priority should be to offer optimized payment methods according to each country. As payment methods vary from country to country and so are people’s preferences, you may want to disable a payment method. For the sake of your store’s profitability too, it’s a good practice to disable payment methods that are costly or difficult to manage.

Offering a perfect balance of cost effective and easy payment methods on the checkout page will tremendously increase your conversion rate. Unoptimized payment methods are one of the common reasons of cart abandonment.

You may also want to disable a payment method based on customer groups, product or product attributes. So let’s see how to do this programmatically in Magento 2. If you are not a programmer and want an extension that does this for you along with many other features, you can go for Magento 2 Payment Restrictions extension.

How to Disable Payment Method Programmatically in Magento 2?

Follow this step by step method to programmatically disable payment method in Magento 2 store.

Step 1: Create events.xml file under app/code/Company/Module/etc/
<?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="Company\Module\Observer\PaymentMethodAvailable" />
 </event>
</config>

Step 2: Now create PaymentMethodAvailable.php under Company/Module/Observer/ and write the following code.

<?php
namespace Company\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class PaymentMethodAvailable implements ObserverInterface
{
 public function execute(\Magento\Framework\Event\Observer $observer)
 {

 //Note: Replace "payment_method_code" with desired payment method code
 if($observer->getEvent()->getMethodInstance()->getCode()=="payment_method_code"){
 $checkResult = $observer->getEvent()->getResult();
 $checkResult->setData('is_available', false); 
 }
 }
}

The above code is a prototype of how to disable payment method programmatically in Magento 2. You can customize it to impose restrictions based on conditions like customer groups, products, attributes, etc.

That’s it for this tutorial. If you find any issue regarding this article, then ask our expert Magento support team.