Search code examples
magentomagento2

Enable payment gateway for Particular products - Magento 2


I want to enable the payment gateway for some products Only. On my website, I have cash on delivery & other payment gateways. Cash on delivery should be enabled for every product.

For that i created a attribute called payment gateway in product section . It is drop down attribute with yes & No as value . So this attribute now visible in product side . When we adding or editing a product we can see this attribute .

Please help on the following .

Now in checkout page i have to check the product in checkout have enabled the payment gateway . If yes then only i need to show the payment gateway , other wise it should be cash on delivery . How can i do this ?

Please help.


Solution

  • If you want to either enable or disable certain payment methods based on some criteria you can use the payment_method_is_active event.

    In the payment_method_is_active event you have access to 3 parameters:

    • $observer->getEvent()->getData('method_instance), the payment method
    • $observer->getEvent()->getData('quote'), the quote being processed
    • $observer->getEvent()->getData('result'), a data object containing the result

    In the result is_available is defined which is either true if the payment method should be enabled ("available") or false if it should be disabled.

    With these 3 objects you can

    • Determine whether the payment method is the method you want to disable based on some criteria
    • Get the products in the quote and their attributes
    • Result to say whether the payment method should be enabled or not.
    class DisablePaymentMethodBasedOnSomething implements ObserverInterface {
        public function execute($observer) {
            $event = $observer->getEvent();
            $method = $event->getData('method_instance');
            $quote = $event->getData('quote');
            $result = $event->getData('result');
    
            if (payment method is not cash on delivery) {
                return;
            }
    
            if (quote does not contain products with gateway attribute) {
                return;
            }
    
            $result->setData('...', false);
        }
    }
    

    As you see I didn't fill in all the blanks, I hope the example will guide you in the right direction.