I have created a plugin to customize the Flatrate shipping(per order) when a guest checks out any product.
Below are my relevant module-plugin files which I supposedly wrote as per Magento 2.x's coding standard(Magento 2.3.4 installed in Windows 10 with some minor path related tweaks):
app/code/MyLearning/CustomFlatrate/registration.php:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'MyLearning_CustomFlatrate', __DIR__
);
app/code/MyLearning/CustomFlatrate/Plugin/Flatrate.php:
<?php
namespace MyLearning\CustomFlatrate\Plugin;
class Flatrate
{
protected $_customerSession;
public function __construct(\Magento\Customer\Model\Session $customerSession)
{
$this->_customerSession = $customerSession;
}
/**
* Returns shipping price
* @param string $shippingPrice
* @return string
*/
public function afterCollectRates($result)
{
if (!$this->_customerSession->isLoggedIn()) {
$this->debugLog($result->debug());
}
return $result;
}
public function debugLog($string)
{
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
return $logger->info($string);
}
}
app/code/MyLearning/CustomFlatrate/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\OfflineShipping\Model\Carrier\Flatrate">
<plugin name="customFlatrate" type="MyLearning\CustomFlatrate\Plugin\Flatrate"/>
</type>
</config>
app/code/MyLearning/CustomFlatrate/etc/module.xml:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="MyLearning_CustomFlatrate" setup_version="1.1.0">
<sequence>
<module name="Magento_OfflineShipping"/>
</sequence>
</module>
</config>
It has been quite sometime, I restarted working in Magento 2, so I can't get my head around, what's going on when I enable my plugin and add product to cart and apply the necessary param-values like state, zipcode, country for getting flatrate shipping rates, but if my plugin is not disabled, then it doesn't load flatrates and asa(as soon as) I disable my plugin, it loads the flatrate.
Can anyone help out understanding where the $result's value is going wrong, such that it doesn't bring the flatrates at all ?