Magento - How to get the Order ID and 2-letter state abbreviation of an order

2.6k views Asked by At

So I have to send variables to an affiliate website and they need the order id, price, 2-letter state abbriviation, and the country abbreviation. I have already got the price and country abbr. but I still need the order id and the 2-letter state abbreviation. The code I have right now is as follows:

$order = Mage::getSingleton('checkout/session')->getLastRealOrderId();//doesnt work
$amount = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();//works
$stateId = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData('region');//Gives full name of State
$countryId = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData('country_id');//works

echo " display: $order $amount $stateId $countryId";//prints out the variables

I have been looking on all the code on here for the order id but nothing has returned anything. So I'm wondering what I am doing wrong with that/why it is not printing out anything.

The second thing is that I am wondering if there is an easy way to get the 2-leter state abbreviation? I have also tried 'region_id" instead of 'region' but that just gives me the number code (not the letter code).

Answers to either of these problems would be greatly appreciated.

2

There are 2 answers

2
Claudiu Creanga On BEST ANSWER

The best way is to send this information through the success.phtml file as only in that file you will get that info and avoid sending order ids for uncompleted orders (failed paypal transactions etc.)

1) depending on your checkout method, you may or may not have the state code in your data.

So if you get the name of states by

$stateId = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData('region');

then add this code afterwards:

$states = Mage::getModel('directory/country')->load('US')->getRegions();//get list of states 
    foreach($states as $state){
        if($state[default_name] == $stateId){ //check if the names match
            echo $state[code]; //get code
        } 
    }   

2) On success page

$orderId = $this->getOrderId();

should work.

0
Kyle Bihler On

Once you have the order loaded you can call 'region_code' or getRegionCode(). I'm using magento 1.9. Not sure if it is available in previous versions.