How to add Shipping Rate while creating Order programmatically
-
12-12-2019 - |
Question
Shipping Method addition is happening as it should be. But, Shipping Rate as per the Shipping method or, custom Shipping rate is not getting added to the order.
$address = $quoteObj->getShippingAddress ();
$address->setCollectShippingRates ( true )->collectShippingRates()
->setShippingMethod('flatrate_flatrate');
$quoteObj->collectTotals ()->save ();
Searching through some other questions I found a solution which adds Custom Shipping Rate to the order, but it doesn't add the shipping rates to Grand Total.
$shippingprice = 0.9;
$orderObj->setShippingAmount($shippingprice);
$orderObj->setBaseShippingAmount($shippingprice);
Solution
Try this:
$shippingprice = 0.9;
$orderObj->setShippingAmount($shippingprice);
$orderObj->setBaseShippingAmount($shippingprice);
$orderObj->setGrandTotal($orderObj->getGrandTotal() + $shippingprice); //adding shipping price to grand total
$orderObj->save();
OTHER TIPS
did you get this solved?
For anyone running into this, you need to set the shipping costs in 2 places. First of all you need to set the shipping method and WITHIN the shipping method you need to set your price. I made my own setShippingMethod function like below:
public function setMyShippingMethod($shippingPrice = 0)
{
$result = Mage::getModel('shipping/rate_result');
// Add carrier
$method = Mage::getModel('shipping/rate_result_method');
if ($shippingPrice > 0) {
// use my custom shipping method but you can use another shipment method here
$method->setCarrier('dpdelivery');
$method->setMethod('dpdelivery');
$method->setCarrierTitle('Shipping');
$method->setMethodTitle('outside the Netherlands');
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
} else {
$method->setCarrier('flatrate');
$method->setMethod('flatrate');
$method->setCarrierTitle('Freeshipping');
$method->setMethodTitle('within the Netherlands');
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
}
$result->append($method);
return $result;
}
Then within my createOrder function I add the shippingAddress and then call my method like this:
$shippingMethod = $this->setMyShippingMethod($shippingCost);
$this->_order->setShippingAddress($shippingAddress)
->setShippingMethod($shippingMethod);
$this->_order->setShippingDescription('My shipping description');
Then of course I still need to add the costs to the order as mentioned:
$this->order->setIsVirtual(0)
....
->setShippingAmount($shippingCost)
->setShippingTaxAmount($shippingCostTax)
I hope it helps anybody.
Try this
$order->setShippingAmount($shippingprice);
$order->setBaseShippingAmount($shippingprice);
$order->save();