Magento 1 – How to Use collectRates Method in Shipping Module

moduleshippingtable-rates

I am creating a shipping module that will use table rates for determining the amount to be charged for shipping. My question is, do I use the collectRates method in the shipping module to display the table rates, or what do I do in this scenario?

Any insight, ideas, and/or suggestions are greatly appreciated.

Thank you!

Best Answer

collectRates() is called for each shipping module.
It receives as parameter an object instance of Mage_Shipping_Model_Rate_Request. Let's call it $request.
Your collectRates() method should start like this:

if (!$this->getConfigFlag('active')) {
   return false;
} 

This means 'do nothing if the shipping method is disabled'.
Through the $request parameter you have access to all the products in the cart: $request->getAllItems().
You can get the total weight of the cart like this:

$request->getPackageWeight()

You can get the total number of products in the cart (qty):

$request->getPackageQty()

You can get the shipping address details as follows:

$request->getDestCountryId(); //for country code
$request->getDestRegionCode(); //for region id (if the country supports it
$request->getDestPostcode();//postal code
$request->getDestCity();//city
$request->getDestStreet();//street

These are the most important ones. For the additional info see the methods listed at the top of this class Mage_Shipping_Model_Rate_Request.
Based on this info you can calculate a price (or more prices) for delivery.
After you have the prices your collectRates method should return an instance of Mage_Shipping_Model_Rate_Result.
For this create an instance:

$result = Mage::getModel('shipping/rate_result');

Each result can support different methods for different prices. For each method you need to do the following:

$method = Mage::getModel('shipping/rate_result_method');//create a method instance
$method->setCarrier('some_code_here'); //set the carrier code (usually the code of your shipping method)
$method->setCarrierTitle($this->getConfigData('title'));//set the carrier title (usually rhe name of the shipping method)
$method->setMethod('some_method_code_here'); //a code for the shipping method. Example: 'express', 'fast_delivery'...It can also be the carrier code if you have only one method for the carrier
$method->setMethodTitle($this->getConfigData('name')); //the method title 
$method->setPrice(THE CALCULATED SHIPPING PRICE HERE);
$method->setCost(ADDITIONAL COST HERE); //if you don't have an additional cost (for handling for example) skip this line.
$result->append($method); //append the method to the result.

After finishing adding your methods simply return the result:

return $result;