Restrict Payment Methods Based on Conditions
Take Full Control of Allowed Payment Methods in Your Store Using Meetanshi’s Magento 2 Payment Restrictions.
Successful E-commerce store owners have learned the criticality of offering and managing various payment methods at checkout. In the process of providing numerous payment methods, the business ends up messing with the management or incur a loss due to offering such facilities. There should be a balance between maintaining user experience and offering payment methods that do not load the management or be too costly for the store.
The best way to gain this perfect balance is to disable payment method programmatically in Magento 2 on the checkout page, making a payment method visible only to admin. The payment methods can be disabled based on customer groups or for specific products. For example, keep the priority of providing excellent user experience to VIP customers whereas don’t waste your bucks in offering payment facilities to guest customers!
Also, you may want to restrict payment methods based on product or order attributes. For all these above conditions and more, I’ve come up with a method to disable payment method programmatically in Magento 2. The code can be customized to disable payment methods as per the conditions like customer groups, products, etc.
With this method, the payment method won’t be displayed in the frontend.
Method to disable payment method programmatically in Magento 2:
1. Create events.xml at app/code/Vendor/Extension/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="disable_payment" instance="Vendor\Extension\Observer\PaymentMethodAvailable" /> </event> </config>
2. Create PaymentMethodAvailable.php at app/code/Vendor/Extension/Observer/
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\ObserverInterface; class PaymentMethodAvailable implements ObserverInterface { 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); } } }
With the above code, impose all the restrictions you want in the payment methods in Magento 2 store.
If you want to skip the tedious implementation process, try Magento 2 Payment Restrictions extension offering similar functionality!