Magento 2: Disable payment method programmatically
In this blog, Iβm going to explain that how you can disable any payment method programmatically at checkout page in Magento 2. I have done it by using Magento observer. So let’s get started with the process.
First, you will need to create events.xml file under app/code/Prashant/Custom/etc/. Here “Prashant” is the namespace and “Custom” is the module name. Then write “payment_method_is_active” event in it. This is the event which hits the checkout page for payment method availability.
<?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="custom_payment" instance="Prashant\Custom\Observer\PaymentMethodActive" /> </event> </config>
Now create a file PaymentMethodActive.php under Prashant/Custom/Observer/ and write following code in the file. I am disabling the Cash On Delivery payment method, you can change payment method code as per your need.
<?php namespace Prashant\Custom\Observer; use Magento\Framework\Event\ObserverInterface; class PaymentMethodActive implements ObserverInterface { /** * payment_method_is_active event handler. * * @param \Magento\Framework\Event\Observer $observer */ public function execute(\Magento\Framework\Event\Observer $observer) { // you can replace "cashondelivery" with your required payment method code if($observer->getEvent()->getMethodInstance()->getCode()=="cashondelivery"){ $checkResult = $observer->getEvent()->getResult(); $checkResult->setData('is_available', false); //this is disabling the payment method at checkout page } } }
Now the payment method Cash On Delivery is disabled from checkout page .
Hope this blog will help you to develop custom functionality in your own module in a better way. Try this and if you have any query then just comment me below. Happy Coding π
Nice article. very helpful.