Disable a Payment Method Programmatically in Magento 2
Payment system management can be considered as one of the cores of the Magento 2 store system as a good handling system can help you optimize your sales, profits as well as your efforts.
Sometimes, you will want to restrict specific payment methods based on the customer groups, product/order attributes, shipping parameters, etc. In other words, it’s time when you can programmatically disable a payment method from your Magento 2 backend configuration. For example, with customers who are coming from India, you can deactivate other payment methods and only display the CCAvenue method.
In today’s article, I will show you 2 simple stages to disable payment method programmatically in Magento 2.
2 Steps to Disable a Payment Method Programmically in Magento 2:
Step 1: Edit config.xml file
To disable the Payment Method Programmatically, firstly, you need to open the config.xml
file and then add the following code to that file:
<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>
Step 2: Edit Observer.php file
In this step, the below code should be added in the Observer.php
file
<?php
class Vendor_Extension_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;
}
}
}
}
Related Post:
- How to Add Product Attribute Programmatically in Magento 2?
- How to Create Invoice Programmatically in Magento 2?
- How to Create Customer Programmatically in Magento 2?
Conclusion
That’s all about how to disable a Payment Method Programmically. Implement these stages correctly, you can control the payment methods choices at your checkout page according to different conditions. For the full solution to restrict payment choices, you can view Mageplaza Payment Restrictions module.
I hope this tutorial is helpful for you. If you have any question about this topic or face any issue while following the steps, feel free to let me know.
Thanks for reading!
- How to create a simple Hello World module for Magento 2
- Magento 2 Block Template Ultimate Guides
- How to Create Module in Magento 2
- How to Create Controller in Magento 2
- How to create CRUD Models in Magento 2
- How to Create Magento 2 Block, Layout and Templates
- Configuration - System.xml
- How To Create Admin Menu In Magento 2
- Admin ACL
- Admin Grid