Magento – How to get shipping quote on product view page – Magento2

magento-2.1magento2

I would like to develop one add-on on my product detail page. I want to calculate estimated Shipping rates and Taxes.

Please review the following process which I am trying to achieve:

  1. On product detail page there is an button called "Estimate Shipping Rates".
  2. User clicks on the button and pop up will be opened with three fields Country, State and Zipcode.
  3. User fills those details and submit the form an AJAX request will be sent.
  4. Magento will calculate shipping rates send data in JSON format.

I am successful to achieve till third step. The problem is on 4th step. As per my findings I tried to replicate scenario as it is working on Cart page >> Estimate Shipping and Tax section:

  1. Magento's process will be initiated from vendor/magento/module-quote/etc/webapi.xml file.

    <route url="/V1/guest-carts/:cartId/estimate-shipping-methods" method="POST">
        <service class="Magento\Quote\Api\GuestShipmentEstimationInterface" method="estimateByExtendedAddress"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>
    
  2. It will traverse to couple of interfaces and classes.

  3. At the end it will retrieve from file – vendor/magento/module-quote/Model/GuestCart/GuestShippingMethodManagement.php, this file extends ShipmentEstimationInterface, ShipmentEstimationInterface call function estimateByExtendedAddress($cartId, AddressInterface $address). Which locate in this path vendor/magento/module-quote/Model/GuestCart/GuestShippingMethodManagement.php

I am sure how to call or integrate this process in my custom module.I found an example for magento 1 here. Please suggest way to achieve this task.

Best Answer

  • You need to develop a custom module to calculate shipping rate on product(or any other) page.
  • With default magento all shipping methods and shipping rates are retrieved from module: "module-shipping"
  • In "module-shipping" there are shipping calculation functions which calculate shipping rates and retrieve shipping methods as is handled in cart/checkout and also any additional conditions if required.
  • Ex. There is a function "getResult()" in file shipping.php at module-shipping/Model which returns all shipping methods and shipping rates in default magento.
  • You need to call that function in your custom module as per your requirements or build a custom function extending that class's current functionality.
Related Topic