Magento

Programmatically create invoice of an order in magento

Programmatically create invoice of an order in magento and create partial invoice of an order

For some time need to create invoice of  an order.I have write code for  how to create invoice of an order pragmatically here.

  1. First of   load an order by order id/order increment id,
  2. Check which items of  that order are available for create invoice.
  3. if ,invoice is not created then create invoice of those items
#this code is suite if order does have any invoice
$order=Mage::getModel('sales/order')->load($orderID);
#checkout order capable to create invoice
if($order->canInvoice() and $order->getIncrementId())
{
$items = array();
 foreach ($order->getAllItems() as $item) {
    $items[$item->getId()] = $item->getQtyOrdered();
    }
 $invoiceId=Mage::getModel('sales/order_invoice_api')->create($order->getIncrementId(),$items,null,false,true);
 #capture the invoice
Mage::getModel('sales/order_invoice_api')->capture($invoiceId);

 


 

This code is create an invoice of an all items of an order.
If you want to create partial invoice  of an order then you can below code

 

$order = Mage::getModel('sales/order')->loadByIncrementId($increment_id);
$items = $order->getItemsCollection();
 
$qtys = array(); //this will be used for processing the invoice
 
foreach($items as $item){
    $qty_to_invoice = x; //where x is the amount you wish to invoice
   #please note that if you dont want to invoice this product, set this value to 0 
    $qtys[$item->getId()] = $qty_to_invoice;
    # Note that the ->getId() method gets the item_id on the order, not the product_id 
}
 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($qtys);
# The rest is only required when handling a partial invoice as in this example
$amount = $invoice->getGrandTotal();
$invoice->register()->pay();
$invoice->getOrder()->setIsInProcess(true);
 
$history = $invoice->getOrder()->addStatusHistoryComment(
    'Partial amount of $' . $amount . ' captured automatically.', false
);
 
$history->setIsCustomerNotified(true);
 
$order->save();
 
Mage::getModel('core/resource_transaction')
    ->addObject($invoice)
    ->addObject($invoice->getOrder())
    ->save();