How to Restrict Payment On Checkout in Magento 2?

 

In this blog; we will be guiding you through the process of restricting active payments on the checkout page in accordance with the requirements.

We can restrict some active payment methods for some particular product type or for some particular country, etc.

For this, we will have to create an observer to restrict active payments.

First, we’ll have to create an event.xml file inside the etc folder. Simply use the below-mentioned 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="MageDelight\PaymentRestriction\Observer\RestrictActivePayment"/>

</event>

</config>

In the next step, we’ll create an observer. Just use the code provided below in your observer file.


<?php

namespace MageDelight\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);

}

}

}

After running this code the observer will restrict the desired active payment method. A reference image is shown below.

Conclusion

Hence, with these simple steps, you can restrict active payment methods on the checkout page.

To get 360-degree control over payment methods for your store, you can opt for our Magento 2 Payment Restrictions Extension.

Also, you can refer to this blog if you want to disable the payment method in your Magento 2 store programmatically.

Explore the highly advanced features we provide by checking out our front & back-end demos.

Also, feel free to contact us anytime for any professional assistance required or if you are looking for extension customization services.