5

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?

3

1 Answer 1

3

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 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

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.