0

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 ?

  • Hey... Did you get output? – Rohan Hapani May 11 at 9:19
  • Checking that in a while, will comment if any query or concern, thanks by the way!! – Vicky Dev May 11 at 9:22
1

Update your plugin file using this below code. afterCollectRates function missing one arguement.

<?php

namespace MyLearning\CustomFlatrate\Plugin;

class Flatrate
{
    protected $_customerSession;
    protected $_rateMethodFactory;

    public function __construct(
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
    )
    {
        $this->_customerSession = $customerSession;
        $this->_rateMethodFactory = $rateMethodFactory;
    }   

    public function afterCollectRates(\Magento\OfflineShipping\Model\Carrier\Flatrate $flatRate, $result)
    {
        /** @var \Magento\Shipping\Model\Rate\Result $result */
        $updateResult = $result->getResult();

        if (!$this->_customerSession->isLoggedIn()) {
            /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
            $method = $this->_rateMethodFactory->create();

            $method->setCarrier('shipping');
            $method->setCarrierTitle('Title');
            $method->setMethod('shipping');
            $method->setMethodTitle('Method Title');
            $amount = 100; // Set your custom price
            $method->setPrice($amount);
            $method->setCost($amount);
            $updateResult->append($method);
            $this->myCustomLog("Your Text");
        }
        return $result;
    }

    private function myCustomLog($string)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        return $logger->info($string);
    }
}

Clean cache and check it.

| improve this answer | |
  • Actually now I am getting strangely different error than priorly. I am getting error Fatal Error: 'Uncaught Error: Call to undefined method Magento\\Shipping\\Model\\Rate\\Result::debug() but yesterday, I was able to debug the result variable in couple situations, I don't remember the situation exactly, but I saw result consisted of 3 to 4 array values when called with it's debug() method. Any thoughts ? – Vicky Dev May 11 at 9:52
  • Anyway I could print_r or var_dump the $result without getting Allowed memory ... error ? – Vicky Dev May 11 at 9:55
  • Just print simple log : $this->myCustomLog("Your Text"); and check it. – Rohan Hapani May 11 at 9:56
  • Yes that's working, but I am trying to set custom flatrate when a guest is checking out, and due to $result not being able to print fully I cannot change the per-order shipping price and rebuild the result. – Vicky Dev May 11 at 10:00
  • Not sure : But, try this one $result->setPrice(10);$result->setCost(10); inside condition – Rohan Hapani May 11 at 10:04

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.