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?
-
you have declared sortOrder two times in di.xml.could you please remove it.– Renu MishraCommented Jan 3, 2019 at 9:33
-
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review– Teja Bhagavan KolleparaCommented Jan 3, 2019 at 10:02
-
please check this magento 2 extension github.com/5mehulhelp5/Magento-2-Extensions/tree/main/…– Mehul ChaudhariCommented Aug 6 at 5:46
1 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 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.
-
2
-
For reference, I found this answer helpful magento.stackexchange.com/a/189530/41603 Commented Jul 3, 2018 at 10:14
-
Any help magento.stackexchange.com/q/323397/57334 Thanks @Khoa TruongDinh– zusCommented Oct 1, 2020 at 2:57