Magento – need to disable cash on delivery to particular cities(not country), using magento 2

cash-on-deliverycheckoutmagento2order-statepayment-methods

I am using magento 2. And I need to disable one payment method 'cash on delivery' to specific cities(not for countries).I found so many solutions but those are not meant for magento 2, I think those are for older versions.Because I couldn't find those files(or methods in the specified location) in my code. Can anyone help me ?
Any help will be appreciated.

Best Answer

You need to create a new module and use a 'plugin' to add some logic to the isAvailable method of Magento\OfflinePayments\Model\Cashondelivery.

Example plugin class:

<?php

namespace Your\Module\Plugin;


use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Model\Quote;

class CashondeliveryPlug
{
    public function aroundIsAvailable(AbstractMethod $subject, callable $proceed, Quote $quote)
    {
        $result = $proceed($quote);

        if ($result) {
            $city = $quote->getBillingAddress()->getCity();
            if (in_array(strtolower($city), self::$cities)) return false;
        }

        return $result;
    }

    static $cities = [ // the cities to be excluded
        'austin',
        'new york',
        'boston'
    ];
}

And you'd have this in {module_dir}/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="Your\Module\Plugin\CashondeliveryPlug" disabled="false" sortOrder="10"/>
    </type>
</config>
Related Topic