Disable payment method programmatically in Magento2

Disable payment method programmatically in Magento2.

Today I am going to explain that how you can disable any payment method programmatically at checkout page in magento 2 in this article. I have done it by using observer.

So lets get started with the process.

First you will need to create events.xml file under app/code/Company/Module/etc/. Then write “payment_method_is_active” event in it. This is the event which hits on 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="Company\Module\Observer\PaymentMethodAvailable" />
    </event>
</config>

 

Now create PaymentMethodAvailable.php under Company/Module/Observer/ and write following code in the file. I am disabling the check money order payment method, you can change payment method code according to your need.

 

<?php

namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;


class PaymentMethodAvailable 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 "checkmo" with your required payment method code
        if($observer->getEvent()->getMethodInstance()->getCode()=="checkmo"){
            $checkResult = $observer->getEvent()->getResult();
            $checkResult->setData('is_available', false); //this is disabling the payment method at checkout page
        }
    }
}

 

Now the payment method Check Money Order is disabled from checkout page .

Hope this blog will help you to develop custom functionality in your module in a better way. Try this and if you have any query then just comment below 🙂

. . .

Comments (4)

Add Your Comment

  • Pradeep Tiwari
    i need to restrict cod orders on certain zip codes with this, how can i do it?
    • Webkul Support
      to accomplish that you need to get the shipping address zip code from checkout session and compare with the zip codes list you have. to get zip code from the session use below code:
      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
      $objectManager->get(“MagentoCheckoutModelSession”)->getQuote()->getShippingAddress()->getPostalcode();
      I have not tested the above code but it will work.
  • oviliz
    So, what is the use case for this? It would have been nice to provide some ideas.
    • Webkul Support
      Well its based on the requirement. thanks
  • css.php