Recently we had a task that client wants to show the estimated sipping price displayed at the product page. Unfortunately magento dosent have a function to calculate does prices for a single product so we had to implement our own one for example in a helper class.

    /**
     * @param $product
     * @param $address
     * @return array
     */
    public function calculateEstimateShippingPrice($product,$address){
        $country = $address['countrId'];
        $zipCode = $address['origZipCode'];
        $qty = 1;
        $store = $this->_store;
        $website = $this->_website;

        $item = $this->_quoteItem->setProduct($product)->setQty($qty);

        $request = $this->_rateRequest
            ->setAllItems([$item])
            ->setDestCountryId($country)
            ->setPackageValue($product->getFinalPrice())
            ->setOrigPostcode($zipCode)
            ->setPackageValueWithDiscount($product->getFinalPrice())
            ->setPackageQty($qty)
            ->setPackagePhysicalValue($product->getFinalPrice())
            ->setStoreId($store->getId())
            ->setWebsiteId($website->getId());

        $rates = $this->_shipping->collectRates($request);

        $costs = [];

        foreach ($rates->getResult()->getAllRates() as $rate) {
            $costs[$rate->getCarrier()] = [
                'title'=>$rate->getCarrierTitle(),
                'price'=>$rate->getPrice()
            ];
        }

        return $costs;
    }

Of course those are not the all setters we can use.
In the

 $costs 

array will be holded calculated rates for each carrier
Also remember to include in your constructor references to those 3 objects:


    /** @var \Magento\Quote\Model\Quote\Item  */
    protected $_quoteItem;

    /** @var \Magento\Quote\Model\Quote\Address\RateRequest  */
    protected $_rateRequest;

    /** @var \Magento\Shipping\Model\Shipping  */
    protected $_shipping;

Leave a Reply

Your email address will not be published. Required fields are marked *

Fork us on GitHub