How to create Magento invoice from order

How to create Magento invoice from order

Maybe you want to create an invoice from some custom script or through cron script. Here is one very useful example of code.
First of all, we have to load some order over model “sales/order”, this is very easy.

$order = Mage::getModel("sales/order")->load($order_id)
// $order_id is entity_id of order from database
//also we can use method "loadByIncrementId" for loading data instead of load method but then we need to pass "increment_id" argument (example: 100000001).

Next step, when we have loaded model “sales/ored” with data, the next procedure is:

try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
 
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
 
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
 
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
 
}

You will notice that we have set option for capture online. This option depends on payment method. Some payment methods support capture online and some don’t. If you want to set capture offline, you can do that with next line code:

$invoice->setRequestedCaptureCase(
Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE
);

I hope that this is clear 🙂

You made it all the way down here so you must have enjoyed this post! You may also like:

Filter order grid by multiple ID’s Petar Sambolek
Petar Sambolek

Filter order grid by multiple ID’s

How to create a custom grid from scratch Vedran Sola
Vedran Sola

How to create a custom grid from scratch

Prepared filter for Magento admin grids Ivan Galambos
Ivan Galambos

Prepared filter for Magento admin grids

Tell us about your project

Drop us a line. We'd love to know more about your project.