0

I want to enable/disable the COD payment method based on product attribute. I tried this: Disable Payment Method at Checkout in Magento 2 Based on Product Attribute

But I am having an issue when I have 2 products in cart where, cod value of one product is set to "yes" and another one set to "no". Any help will be appreciated.

mechanic
  • 440
  • 5
  • 24

1 Answers1

0

You could create a custom extension to look through every item in the cart and disable the payment method

MagePal/PaymentRestrictions/etc/events.xml

<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="mp_payment_restrictions" instance="MagePal\PaymentRestrictions\Observer\PaymentMethodActiveObserver" />
    </event>
</config>

MagePal/PaymentRestrictions/Observer/PaymentMethodActiveObserver.php

namespace MagePal\PaymentRestrictions\Observer;

use Magento\Framework\DataObject; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Payment\Helper\Data as paymentData; use Magento\Payment\Model\Method\AbstractMethod; use Magento\Quote\Api\Data\CartInterface;

class PaymentMethodActiveObserver implements ObserverInterface {

/**
 * @var Data
 */
private $helperData;
/**
 * @var paymentData
 */
private $paymentData;

/**
 * PaymentMethodActiveObserver constructor.
 * @param Data $helperData
 * @param paymentData $paymentData
 */
public function __construct(
    Data $helperData,
    paymentData $paymentData
) {
    $this-&gt;helperData = $helperData;
    $this-&gt;paymentData = $paymentData;
}

/**
 * @param Observer $observer
 * @throws LocalizedException
 */
public function execute(Observer $observer)
{

    /** @var DataObject $result */
    $result = $observer-&gt;getResult();
    /** @var AbstractMethod $methodInstance */
    $methodInstance = $observer-&gt;getMethodInstance();
    /** @var CartInterface $quote */
    $quote = $observer-&gt;getQuote();
    $paymentCode = $methodInstance-&gt;getCode();

    $storeId = $quote ? $quote-&gt;getStoreId() : null;

    if ($paymentCode == 'cod code here') {
        $notAllow = [] 
        foreach ($quote-&gt;getAllItems() as $item) {
            if ($item-&gt;getProduct()-&gt;getCodValue()) {
               $notAllow[] = $item-&gt;getProduct()-&gt;getCodValue();
            }
        }

        if (!empty($notAllow)) {
           $result-&gt;setIsAvailable(false);
        }
    }

}

}

MagePal Extensions
  • 13,911
  • 2
  • 33
  • 52