How to Disable Payment Method in Magento 2 Programmatically?
Introduction:
In the ever-evolving world of e-commerce, striking the perfect balance between user-friendly checkout experiences and cost-effective management is paramount for successful store owners. The multitude of payment methods offered can either enhance user satisfaction or become a cumbersome burden on the business. Enter the solution: Programmatically Disable Payment Method in Magento 2.
Imagine tailoring your payment methods to specific customer groups, ensuring VIPs enjoy a seamless experience while judiciously managing costs for others. Whether it's restricting payment options based on product attributes or order specifics, a method to disable payment methods programmatically provides the flexibility your online store needs. Join me as we explore a customizable code that ensures payment methods remain invisible on the frontend, optimising your e-commerce operations with finesse.
Step For Disable Payment Method Programmatically in Magento 2
Step 1: Place an events.xml file in the specified directory
path:- app/code/Vendor/Module/etc/.
Now, insert the provided code snippet.
Step 2: Now, place PaymentMethodRestriction.php file in the specified
directory path: app/code/Vendor/Module/Observer/.
After that, copy and paste the provided code.
<?php namespace Vendor\Module\Observer; use Magento\Framework\Event\ObserverInterface; class PaymentMethodRestriction implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $currentMethod = $observer->getEvent()->getMethodInstance()->getCode(); // Replace "checkmo" with the restrict payment method code. if ($currentMethod === "checkmo") { //Your custom logic here... $restrictMethodResult = $observer->getEvent()->getResult(); $restrictMethodResult->setData('is_available', false); } } } |
Conclusion:
By implementing the provided steps, you can effortlessly disable payment method in Magento 2 programmatically, ensuring a seamless payment process. If you encounter any challenges during the implementation, feel free to share your queries in the comments section below. I’m here to assist you! Additionally, for a hassle-free solution, consider exploring the Magento 2 Payment Restrictions extension, offering similar robust functionality.