In this post I am going to explain how to disable payment method programmatically in magento 2.

First, We need to write the “payment_method_is_active” event, which checks on checkout for payment method availability.

So, we are going to create event.xml file on below path.

Path: app/code/Ht/Mymodule/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="custom_payment" instance="Ht\Mymodule\Observer\PaymentMethodAvailable" />
    </event>
</config>

Next to that, we are going to create observer PaymentMethodAvailable.php on below path.

Path: app/code/Ht/Mymodule/Observer/

Here I have given you the example to disable the check and money order payment method, you can change payment method code as per your requirement.

<?php

namespace Ht\Mymodule\Observer;

use Magento\Framework\Event\ObserverInterface;


class PaymentMethodAvailable implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // replace "checkmo" with your payment method code
		
        if($observer->getEvent()->getMethodInstance()->getCode()=="checkmo"){
            $checkResult = $observer->getEvent()->getResult();
            $checkResult->setData('is_available', false);
        }
    }
}

 

Thats it. Enjoy Magento 2!!