I want to display Current product shipping rate on the product detail page.
I have tried below code,
$qty = 1;
$countryId='IN';
$storeId = 1;
$zipcode = 360002;
$product = $this->_catalogProduct->load($id);
$item = $objectManager->create('Magento\Quote\Model\Quote\Item')->setProduct($product)->setQty(1);
$store = $objectManager->create('Magento\Store\Model\Store')->load($storeId);
$request = $objectManager->create('Magento\Quote\Model\Quote\Address\RateRequest')->setAllItems(array($item))
->setDestCountryId($country)
->setPackageValue($product->getFinalPrice())
->setOrigPostcode($zipcode)
->setPackageValueWithDiscount($product->getFinalPrice())
->setPackageWeight($product->getWeight())
->setPackageQty(1)
->setPackagePhysicalValue($product->getFinalPrice())
->setFreeMethodWeight(0)
->setStoreId($store->getId())
->setWebsiteId($store->getWebsiteId())
->setFreeShipping(0)
->setBaseCurrency($store->getBaseCurrency())
->setBaseSubtotalInclTax($product->getFinalPrice());
$result = $this->_rateCollector->create()->collectRates($request)->getResult();
I want to display more than one enabled shipping methods rates in product display page. I have tried this code but i am getting this kind of error.
Uncaught Error: Call to a member function getItemsQty() on null
in/vendor/magento/module-quote/Model/Quote/Item.php:275
Please help me on this.
Best Answer
Although Manish's answer does show how to create a block on the product page to obtain the available shipping rates, the REST API used in the tutorial (rest/default/V1/carts/mine/estimate-shipping-methods) only fetches this for the items that are already in the cart, and not just for the currently viewed product. This is because Magento relies on items that are added to the active quote to obtain the available methods and costs, of which was fetched from the database and utilised. Despite this, we can create a blank quote in memory without saving it into the database, fill in the required data, and then apply this to the shipping calculator.
The best approach to this is to create a new API endpoint, which you can then swap out the endpoint defined in the tutorial with yours.
Interface
Model
di.xml
webapi.xml
If you are familiar with API endpoints, you will recognise that this can be called via /rest/default/V1/shipping/estimate/:sku, where :sku is the product SKU you would like to check the shipping methods for. The POST object and return JSON will be exactly the same as that of carts/mine/estimate-shipping-methods, so they are interchangeable.
If the rates displayed are different from when you add the item into the active cart, then that suggests the shipping rate fetches the item and/or address data from the session rather than the Magento\Quote\Model\Quote\Address\RateRequest object - if this is the case, then you may need to alter those shipping classes, or contact the developer to have this looked into.