Skip to content

Magento 2 – Event – Observer – Shipping amount is correct on checkout page refresh

I am trying to calculate tax on the total of subtotal+shipping-discount.
I have created an event/observer for this.

<event name="sales_quote_save_after">
    <observer instance="SKPOrderGstObserverCheckoutSalesQuoteSaveAfter" name="skp_ordergst_observer_sales_quote_save_after"/>
</event>

 

After entering the shipping address on the checkout page first time the getShippingAmount returns 0, but after refreshing the page it returns the desired amount. What could be the problem?

    public function execute(
    MagentoFrameworkEventObserver $observer
) {
    
    $quoteData = $observer->getEvent()->getQuote();
    $shippingAmount = $quoteData->getShippingAddress()->getShippingAmount(); //returns 0 first time


    $items = $quoteData->getAllItems();

    $discountAmt = 0;
    foreach ($items as $item) {
        $discountAmt += $item->getDiscountAmount(); //$item(get all information)
    }
    $subTotal = $quoteData->getSubtotal();
    $orderGst = (($subTotal + $shippingAmount) - $discountAmt) * 0.2;

    $gst  = round($orderGst, 2);
$quoteData->setOrderGst($gst)->save();

}