Hello Friends!!
In today’s blog, I will recommend a solution to restrict the active payments on the checkout page according to our requirements.
For example, we can restrict some active payment methods for some particular product type or for some particular country, etc.
We will create an observer to set Magento 2 Payment Restrictions.
So firstly let us create an events.xml file inside the etc folder. You can simply use the below code in your events.xml file.
<?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="active_payment_methods" instance="Webkul\PaymentRestriction\Observer\RestrictActivePayment"/> </event> </config>
Now let us create an observer.
You can simply use the below code in your observer file.
<?php namespace Webkul\PaymentRestriction\Observer; use Magento\Framework\Event\ObserverInterface; class RestrictActivePayment implements ObserverInterface { /** * Restrict active payment method * * @param \Magento\Framework\Event\Observer $observer */ public function execute(\Magento\Framework\Event\Observer $observer) { if($observer->getEvent()->getMethodInstance()->getCode() == "cashondelivery"){ $checkResult = $observer->getEvent()->getResult(); $checkResult->setData('is_available', false); } } }
Now, the observer will restrict the active payment method as we desired.
Shown as in the below Image.
That’s all about on how to restrict active payment methods on the checkout page. Hope this will be helpful.
This blog can be useful for various cart and payment-related operations including Magento 2 partial payment
If you have any questions please comment below, and we will try to respond to you. Also, check our complete range of Magento 2 Extensions.
Thanks for visiting the Webkul blog! 🙂
Be the first to comment.