Magento 2 Payment Methods – Admin Only Payment Method

magento2overridespayment-gatewaypayment-methods

When working with Magento 2, sometimes we want to disable Payment methods on the Front page and use it only for Admin. Or, if we want to set more rules for Payment methods to check whether payment method can be used. How we can do that?

Best Answer

We should take a look at the payment abstract class vendor/magento/module-payment/Model/Method/AbstractMethod.php. We can see the method public function isAvailable() - This class will check whether payment method can be used.

   public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null)
    {
        if (!$this->isActive($quote ? $quote->getStoreId() : null)) {
            return false;
        }

        $checkResult = new DataObject();
        $checkResult->setData('is_available', true);

        // for future use in observers
        $this->_eventManager->dispatch(
            'payment_method_is_active',
            [
                'result' => $checkResult,
                'method_instance' => $this,
                'quote' => $quote
            ]
        );

        return $checkResult->getData('is_available');
    }

As can we see, there is an Observer event, like Magento 1, we can use Observer to disable our Payment Methods. It's Magento 1 way. However, Magento 2 introduces to developers a new way - Plugin.

Create DI on front page: app/code/{Vendor}/{Module Name}/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Payment\Model\Method\AbstractMethod">
        <plugin sortOrder="5" name="testValidate"
                type="{Vendor}\{Module Name}\Plugin\Model\Method\Available" sortOrder="1" disabled="false" />
    </type>
</config>

app/code/{Vendor}/{Module Name}/Plugin/Model/Method/Available.php

<?php

namespace {Vender}\{Module Name}\Plugin\Model\Method;

class Available
{
   /**
     *
     * @param \Magento\Payment\Model\Method\AbstractMethod $subject
     * @param $result
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterIsAvailable(\Magento\Payment\Model\Method\AbstractMethod $subject, $result)
    {

        if($subject->getCode() == 'your payment code, eg: cashondelivery') {
            return false;
        }
        return $result;
    }
}

$subject is the current Payment Method Model.

enter image description here

Related Topic