Today we are going to learn how to hide payment methods in Magento2. Magento2 provides a number of online and offline payment methods to make payments. Sometimes merchants are required to hide payment methods based on some condition, let’s take one example, cash on delivery method should not display in the admin/frontend side. There are many more scenarios like minimum order amount to display payment method, specific customer group, frontend/admin side or specific shipping method selection, in those cases, we have to customize code to make working according to it. This is basic code that must be required to hide payment methods for all those cases plus some additional code required to make it complete.
Magento2 natively does not provide to hide payment methods for specific conditions. In order to hide the payment method in the frontend checkout page and the admin create order page, let’s follow the below steps.
Method to hide a Payment Method in frontend and admin side Magento 2
1) Create the events.xml file at app/code/Vendor/Extension/etc directory
<?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="hide_cod_payment_method" instance="Cogentcommerce\RestrictPaymentMethod\Observer\RestrictCODPaymentMethodObserver" />
</event>
</config>
2) Create RestrictCODPaymentMethodObserver.php file at Vendor\Extension\Observer directory
<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class RestrictCODPaymentMethodObserver implements ObserverInterface
{
/**
* Hide Cash on delivery payment method in frontend and backend side
*
* @param EventObserver $observer
* @return void
*/
public function execute(EventObserver $observer)
{
$event = $observer->getEvent();
$method = $event->getMethodInstance();
if ($method->getCode() == 'cashondelivery') {
/* @var \Magento\Framework\DataObject $result /
$result = $event->getResult();
$result->setData('is_available', false);
}
}
}
Using the above-mentioned code, you can hide a payment method on the front and admin side.
If you are required to hide the payment method in some other conditional base then feel free to ask us in a comment or contact us on info@cogentcommerce.com
Thank you for reading…We hope it helps you out. For any assistance contact us.
Follow us on Linkedin