Sometime we need to have a condition to enable or disable COD (cash on delivery payment). In my case my client asked me COD should be enable just for some regions.
Now i want to share my code and my solution .
Create this file or if it exist just add the code app/code/Darvishani/COD/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="cashondeliveryplugforregion"
type="Darvishani\COD\Plugin\CashondeliveryPlug"
disabled="false" sortOrder="10"/>
</type>
</config>
Now you need to add a class app/code/Darvishani/COD/Plugin/CashondeliveryPlug.php
<?php
namespace Darvishani\COD\Plugin;
use Magento\Checkout\Model\Session;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Model\Quote;
use Psr\Log\LoggerInterface;
class CashondeliveryPlug
{
/**
* @var Session
*/
protected $_checkoutSession;
/**
* Constructor
*
* @param Session $checkoutSession
*/
public function __construct(
LoggerInterface $logger,
Session $checkoutSession
) {
$this->logger = $logger;
$this->_checkoutSession = $checkoutSession;
}
public function aroundIsAvailable(
\Magento\Payment\Model\Method\AbstractMethod $subject, callable $proceed)
{
$shippingAddress = $this->_checkoutSession->getQuote()->getShippingAddress();
$currentRegionCode=$shippingAddress->getRegionId();
$enableRegion=['7','25'];
if(is_array($enableRegion) && in_array($currentRegionCode,$enableRegion)){
return true;
}else{
return false;
}
return $proceed();
}
}
You need to compile your code and clear Magento cache