Update Available Shipping Methods & Recalculate Tax in Magento 1.9

cartcheckoutmagento-1.9tax

In continuation of my post Add items to cart by link post the other day:
When posting the customer's zip code and getting back the available shipping options, the tax rate is not updated.

Code to update zip code in cart:

include_once 'app/Mage.php';
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));

$session = Mage::getSingleton('customer/session');


// Change to your postcode / country.
$zipcode = $_POST["ZIPCODENEW"];
$country = 'US';
$shipstate = $_POST["STATE"];


// Update the cart's quote.
$cart = Mage::getSingleton('checkout/cart');
$address = $cart->getQuote()->getShippingAddress();

$address->setCountryId($country)
        ->setPostcode($zipcode)
        ->setRegionId($shipstate)
        ->setCollectShippingRates(true);


$cart->save();

This works as intended, and can be verified with magento's cart page that shipping options were returned. These shipping methods are also available via the method described here.

What this does not do is recalculate tax. If I go to the magento shopping cart and put in a zip code to get the available shipping rates, and use a zip code that falls under a tax rule then tax is automatically recalculated.

Now here's the rub: If I update the totals of an item from my cart (after tax has been applied by the Magento checkout), then the tax total is correctly updated. Additionally, if I get tax from the magento shopping cart, then have my cart change the zip to a non-tax zone (using the above code), the tax is correctly removed.

Best Answer

We actually solved this, and I feel silly for missing it, and being the one that solved it.

Magento passes the sate as numbers, rather than 2-letter abbreviations. For some reason the system will accept, then discard the two letter abbreviations, but still give full/correct shipping quotes from the zip code. As soon as we passed the state variable correctly the taxes updated as expected.

You can see the state<->ID# relationship by examining the HTML form on the normal shopping cart.

You can also get this list directly from magento:

$states = Mage::getModel('directory/country')->load('US')->getRegions();

Then you can set your HTML form something like this:

<?php foreach ($states as $state): ?>
<option value="<?php echo $state->getId(); ?>"><?php echo $state->getName(); ?></option>
<?php endforeach; ?>
Related Topic