How to programmatically add shipment with a tracking number to any order : PART I

May 15, 2012 | In: How to do, Magento, php, web development, web services

We are assuming that we have an order incremented id. and we want to make shipment for this order.
Here also we are assuming that invoice has been generated for order already. so we are going to generate only shipment.

 $orderId = '1000001';
 $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);

Here we are checking the current status of order that it is processing or not.

Why we are checking?
Because we do not want to generate shipment for any order that has been completed or canceled.

if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING) {
	// Do something

Ok, now we have checked that order is in processing state and we can procced but still we can not generate shipment for order.


Because there may be some orders which can not ship to customer shipping address. For example: customer ordered for virtual gift card product or a coupon code.
That time we must to check that order can be ship or not?

if (!$order->canShip()) {
	$this->_getSession()->addError($this->__('Sorry! This order can not be ship.'));
	return false;

Now we have checked everything and we are going to generate shipment for order.

$shipment = $order->prepareShipment();
$order->addStatusHistoryComment('Programatically shipped by naveenos Group.', false);

That’s it…..

Now you can check in site admin panel, you will find a new entry exists in Shipment tab for that order.