I tried with DRAJIs code, \Magento\Quote\Api\Data\ShippingMethodInterface
this api always return NULL for shipping method.
We cant use \Magento\Checkout\Model\Cart
, This is deprecated.
We can use \Magento\Checkout\Model\Session
for getting the current shipping method but Model does not update on shipping method change. For updating session we need to reload the page. So This will also not Serve Our Purpose.
The below Approach will solve the problem.
In order to dynamically disable any given payment method based on selected shipping method we need to use Magentos plugin functionality
Create these files in a custom module.
etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Payment\Model\MethodList">
<plugin name="override_method" type="Bp\HidePaymentMethod\Plugin\Model\MethodList" sortOrder="10" disabled="false" />
</type>
</config>
Plugin/Model/MethodList.php
<?php
namespace Bp\HidePaymentMethod\Plugin\Model;
class MethodList
{
protected $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
public function afterGetAvailableMethods(
\Magento\Payment\Model\MethodList $subject,
$availableMethods,
\Magento\Quote\Api\Data\CartInterface $quote = null
) {
$shippingMethod = $this->getShippingMethodFromQuote($quote);
// you can check your shipping method from log
$this->logger->info("Shipping Code From Plugin=>". $shippingMethod);
if($shippingMethod == "matrixrate_matrixrate_13" || $shippingMethod == "matrixrate_matrixrate_14") {
foreach ($availableMethods as $key => $method) {
// Here we will hide Cash method while customer select any of the 2 of above shipping method
if(($method->getCode() == 'cash')) {
unset($availableMethods[$key]);
}
}
}
return $availableMethods;
}
/**
* @param \Magento\Quote\Api\Data\CartInterface $quote
* @return string
*/
private function getShippingMethodFromQuote($quote)
{
if($quote) {
return $quote->getShippingAddress()->getShippingMethod();
}
return '';
}
}
Note: Replace Bp/HidePaymentMethod with your Vendor/Module