9

How to, for example, enable cash on delivery payment only when customer selected flat rate shipping method?

I cannot find a way doing this in shipment/payment configuration or in cart rules.

9

I use an plugin in a custom module to set the isAvailable() function for Magento\OfflinePayments\Model\Cashondelivery to false when shipping method flatrate_flatrate is selected.

file: <magento-root>/app/code/MyCompany/MyModule/Plugin/CashondeliveryPlug.php

<?php
namespace MyCompany\MyModule\Plugin;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Model\Quote;

class CashondeliveryPlug
{
  /**
   * @var \Magento\Checkout\Model\Session
   */
   protected $_checkoutSession;

  /**
   * Constructor
   *
   * @param \Magento\Checkout\Model\Session $checkoutSession
   */
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->logger = $logger;
        $this->_checkoutSession = $checkoutSession;
    }

    public function aroundIsAvailable(
      \Magento\Payment\Model\Method\AbstractMethod $subject, callable $proceed)
    {
        $shippingMethod = $this->_checkoutSession->getQuote()->getShippingAddress()->getShippingMethod();
        // $this->logger->debug($shippingMethod);

        if ($shippingMethod == 'flatrate_flatrate')
            return false;

        return $proceed();
    }
}

file: <magento-root>/app/code/MyCompany/MyModule/etc/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\OfflinePayments\Model\Cashondelivery">
        <plugin name="cashondeliveryplug" 
            type="MyCompany\MyModule\Plugin\CashondeliveryPlug"
            disabled="false" sortOrder="10"/>
    </type>
</config>

Hope this helps you! Feel free to ask any questions.

| improve this answer | |
  • 1
    How to do this in backend – Mahi M Feb 20 '18 at 9:38
  • you have to make an custom module with an Plugin aroundIsAvailable function. You can't do this in the backend with stock-magento – juhanix Feb 20 '18 at 11:13
  • this is my condition ...how to do this in backend – Mahi M Feb 20 '18 at 11:56
  • maybe you should open a new question, where you can give further information – juhanix Feb 20 '18 at 13:55
  • Thank you so much @juhanix i spend more than 2 hours to find a flow. your solution help me lot. keep coding :) – divya sekar Nov 6 '19 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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