Disable a Payment Method Programmatically in Magento 2

To disable a payment method

Edit config.xml file

To disable the payment method, open the config.xml file and add the following code:

<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>

Edit Observer.php file

The below code should be added to the Observer.php:

<?php
class VendorName_ModuleName_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;
            }
        }
        
    }
}

 

If you are looking for Magento Developers, visit Magento Web Agency.