Creating an Invoice

Note: This article is based on the article Magento quick way to create order invoice published on 10 June 2010.
Update 13 June 2011: Please note that it is recommended that API version 2 is used. The article has been updated to reflect this recommendation. Also please note that the capture() method is not required if the create invoice method is passed the entire invoice items.

Creating invoices programmatically in Magento can be a little tedious as it involves a number of steps. However Magento provides an API class related to invoices that can simplify the development. Once the invoice is created, the invoice model class methods can be used similar to other classes.

To illustrate how the invoice API can be used through code, let’s consider that an order has been paid and an invoice needs to be issued. To create the invoice, first the API class needs to be initialised. To initialise the class the standard getModel() method is invoked with the class reference ‘sales/order_invoice_api’.

Using the returned class object the order can now be created. To create an invoice associated with an order the create() method needs to be called with the order Increment Id and the order items are passed. Some other parameters that the method can take are:

  • Comment – this will add the specified comment to the invoice.
  • Email – when this parameter is passed a value of TRUE the invoice will be sent to customer on creation.
  • Include Comment – when set to TRUE the comment specified in the $comment field will be sent in the email.

 

  1. function create($orderIncrementId, $itemsQty, $comment = null, 
  2.                 $email = false, $includeComment = false);

Once the invoice is created, the create() method returns the Invoice Id, therefore the actual invoice needs to be loaded before performing any invoice operations. To mark the invoice as paid, the actual invoice object needs to be loaded and on the object the capture() method is called. Note that the capture method will mark the entire invoice as Paid, for partial invoicing the appropriate capture method needs to be called. The capture method will mark the Invoice as paid but will not save it. So as a last step the save method is called.

The full code for the example above is:

  1. /**
  2.  * Step 1: Through the Invoice API create an invoice for the order
  3. */
  4. $invoiceId = Mage::getModel('sales/order_invoice_api_v2')
  5.                  ->create($order->getIncrementId(), $order->getAllItems(), 
  6.                           ‘Programmed Invoice Create’, true);
  7. /**
  8.  * Step 2: Load the Invoice object
  9. */					 
  10. $invoice = Mage::getModel('sales/order_invoice')->loadByIncrementId($invoiceId);
  11.  
  12. /**
  13.  * Step 3: Mark the invoice as Paid
  14.  * This step is no longer required as the invoice is passed all order items
  15. */
  16. //$invoice->capture()->save();

References:

Be Sociable, Share!