Magento autoshipping according to lowest price

Recently one of my clients came up with a requirement to provide auto shipping on basis of price. He wanted to add shipping price automatically to customer cart as soon as customer adds a product to cart. So below is the code that I followed:-
Modules I know you all can create on your own, so we will be discuss about the Events on which I placed observer and observer functionality that adds shipping rates to our shopping cart so that lets go with config.xml first:-
Below are the events on which we have implemented our code.

<events>
            <checkout_cart_update_items_after>
                <observers>
                    <w3solver_autoshipping_observer>
                        <type>singleton</type>
                        <class>w3solver_autoshipping/observer</class>
                        <method>addShipping</method>
                    </w3solver_autoshipping_observer>
                </observers>
            </checkout_cart_update_items_after>
            <checkout_cart_product_add_after>
                <observers>
                    <w3solver_autoshipping_observer>
                        <type>singleton</type>
                        <class>w3solver_autoshipping/observer</class>
                        <method>addShipping</method>
                    </w3solver_autoshipping_observer>
                </observers>
            </checkout_cart_product_add_after>
            <sales_quote_remove_item>
                <observers>
                    <w3solver_autoshipping_observer>
                        <type>singleton</type>
                        <class>w3solver_autoshipping/observer</class>
                        <method>addShipping</method>
                    </w3solver_autoshipping_observer>
                </observers>
            </sales_quote_remove_item>
            <controller_action_postdispatch_checkout_cart_estimatePost>
                <observers>
                    <w3solver_autoshipping_observer>
                        <type>singleton</type>
                        <class>w3solver_autoshipping/observer</class>
                        <method>addShipping</method>
                    </w3solver_autoshipping_observer>
                </observers>
            </controller_action_postdispatch_checkout_cart_estimatePost>
            <customer_login>
                <observers>
                    <w3solver_autoshipping_observer>
                        <type>singleton</type>
                        <class>w3solver_autoshipping/observer</class>
                        <method>addShipping</method>
                    </w3solver_autoshipping_observer>
                </observers>
            </customer_login>      
        </events>

Another step is to have an observer file and write a functions that filter shipping rate according to price and auto add it to quote:-

<?php
class W3solver_AutoShipping_Model_Observer {

    public function addShipping($observer) {

        $checkout = Mage::getSingleton('checkout/session');
        $quote = $checkout->getQuote();
        $shippingAddress = $quote->getShippingAddress();

        //first use the default Country code
        $country = Mage::getStoreConfig('general/country/default');

        //check if the customer has logged in
        if (Mage::getSingleton('customer/session')->isLoggedIn()) {
            $customer = Mage::getSingleton('customer/session')->getCustomer();
            if ($customer->getPrimaryShippingAddress() && $customer->getPrimaryShippingAddress()->getCountry()) {

                //use customer's shipping address country if there's one
                $country = $customer->getPrimaryShippingAddress()->getCountry();
            }
        }

        //only set country if it does not exists already
        if (!$shippingAddress->getCountryId()) {
            $shippingAddress->setCountryId($country);
        }

        //allow shipping rates recalculation
        $shippingAddress->setCollectShippingRates(true);


        //rest qutoe item counts so that shipping calculation is based on the correct quantity
        $quote->collectTotals();

        $shippingAddress->collectShippingRates();

        if ($quote->getItemsCount()) {

            //get available rates
            $rates = $shippingAddress->getAllShippingRates();

            if (count($rates)) {

                /* sort rate by price */
                foreach ($rates as $i => $rate) {
		
                    $tmp[$i] = $rate->getPrice();
                }

                natsort($tmp);

                foreach ($tmp as $i => $price) {
                    $result[] = $rates[$i];
                }
                $rates = $result;

                //get the top positioned rate. It's based on the position set up in backend
                $topRate = reset($rates);
                $rateToApply = $topRate->getCode();

                try {

                    //apply shipping
                    $shippingAddress->setShippingMethod($rateToApply);
                    $quote->save();

                    //set checkoutstate to CHECKOUT_STATE_BEGIN
                    //prevent the address from being removed when init() in Mage_Checkout_Model_Cart is called 
                    $checkout->resetCheckout();
                } catch (Mage_Core_Exception $e) {
                    $checkout->addError($e->getMessage());
                } catch (Exception $e) {
                    $checkout->addException($e, Mage::helper('checkout')->__('Cannot set shipping method.'));
                    Mage::logException($e);
                }
            }
        }

        return $this;
    }

}

I hope that above code will help you, just drop in your comments if you find any issue or if you have any suggestion.

Leave a Comment.