Skip to main content
6 of 12
deleted 35 characters in body
Jackson
  • 10k
  • 31
  • 131
  • 217

Magento 2: How to show/hide payment method on basis of amount

I have 2 payment method Paypal Express Checkout & Bank Transfer.

When the amount is greater than X then Paypal should not be displayed only Bank Transfer.

I have configured that variable on admin side on system.xml for X amount.

By referring to Magento 2 : How do we add zipcode validation on COD payment method? as per @Ashish suggestion.

I have below code now

app\code\Custom\Module\etc\frontend\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Paypal\Model\Express">
        <plugin sortOrder="1" name="restrictByCustomer" type="Custom\Module\Plugin\Payment\Method\Paypal\Available"/>
</type>

app\code\Custom\Module\Plugin\Payment\Method\Paypal\Available.php

namespace Custom\Module\Plugin\Payment\Method\Paypal;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Backend\Model\Auth\Session as BackendSession;
use Magento\Paypal\Model\Express;

class Available {

    /**
     * @var CustomerSession
     */
    protected $customerSession;

    /**
     * @var BackendSession
     */
    protected $backendSession;

    /**
     * @param CustomerSession $customerSession
     * @param BackendSession $backendSession
     */
    public function __construct(
    CustomerSession $customerSession, BackendSession $backendSession
    ) {
        $this->customerSession = $customerSession;
        $this->backendSession = $backendSession;
    }

    /**
     *
     * @param Paypal Express $subject
     * @param $result
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterIsAvailable(Express $subject, $result) {
        // Do not remove payment method for admin
        if ($this->backendSession->isLoggedIn()) {
            return $result;
        }
        
        
        return false;
    }
}

So when i access http://localhost/magento2/checkout/#payment, It's not hiding my Paypal method when i return false & it's frontend so i have to use customerSession instead of backendSession?

Jackson
  • 10k
  • 31
  • 131
  • 217