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 {
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.'));
$transactionSave = Mage::getModel('core/resource_transaction')
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:


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, | 14

Filter order grid by multiple ID’s

How to create a custom grid from scratch Vedran Sola
Vedran Sola, | 93

How to create a custom grid from scratch

Prepared filter for Magento admin grids Ivan Galambos
Ivan Galambos, | 7

Prepared filter for Magento admin grids


  1. Hi I executed this script in observer..
    but it shows error..
    please find log
    [TIMESTAMP] => 2016-06-01T14:48:55Z
    [CORRELATIONID] => (value here)
    [ACK] => Failure
    [VERSION] => 72.0
    [BUILD] => 000000
    [L_ERRORCODE0] => 10525
    [L_ERRORCODE1] => 10413
    [L_SHORTMESSAGE0] => Invalid Data
    [L_SHORTMESSAGE1] => Transaction refused because of an invalid argument. See additional error messages for details.
    [L_LONGMESSAGE0] => This transaction cannot be processed. The amount to be charged is zero.
    [L_LONGMESSAGE1] => The totals of the cart item amounts do not match order amounts.
    [L_SEVERITYCODE0] => Error
    [L_SEVERITYCODE1] => Error

    I want to capture Payment once order placed..

  2. Hi,
    I know that it’s an old post but I will try anyway. Everything works fine except that I cannot see the transaction in the “Transactions” tab related to the order, it says “No records found”.

    Any hints?

  3. Hi Domagoj,

    Excellent post. Just got one doubt hope you could help me out.

    I have created an observer for auto invoice generation.
    But What I want is to set invoice status as “Pending”.

    I have tried


    But it did not work.

    Can you tell me what else I can do.

    Thanks in advance,

  4. Totally not clear.

    I try put both your code at cron.php after last line, and access the , nothing happen.

    I try google about cron script, most of them telling about edit xml, and schedule task thing.

    Can add more specific step, at least mention put the script at what file, and how it will be executed.

    TQVM & Appreciated.

    1. Where to put the code“?! He’s showing you how to do it so you can do it anywhere you like! He never mentioned a specific case. It sounds like you don’t know what you’re doing.

      In your case, it sounds like you’re not instatiating Magento; you can’t just place magento code anywhere and expect it to work. Google how to write Magento scripts, put all your code in a file and call it from the cron this way.

      By the way, adding “TQVM & Appreciated” does NOT make up for your previous rudeness. Before writing “Totally not clear” make sure you actually know what you’re saying because the article IS clear. Don’t be a jerk.

  5. We are using Cybersource payment method with Payment action set to ‘Authorize Only’.

    But when I tried to create and capture invoice using this code snippet, it will authorize the amount twice.

    Please anyone suggest me how to resolve this.

  6. Beware that if invoicing fails (throws exception) and you save something on the order object, the order items will still show up as invoiced on the order and the invoice button will have disappeared.

  7. Bu they’re pending only on the user interface (Customer Dashboard) in admin area they’re all invoiced.

    Thanks again and congrats!

  8. Thanks for this code! Amazing!

    Why even after all that the products keep on status Pending? They’re Downloadable Products. Store is

    Thanks in advance!

  9. Hi Domagoj,

    Thank you give good code.
    But I have an issue to generate invoice from cron.

    When I trying to generate an invoice for an order from my cron script then it giving a Fatal Error.

    PHP Fatal error: Uncaught exception ‘Exception’ with message ‘Warning: strpos() [function.strpos]: Empty delimiter in /magentorootpath/lib/Zend/Controller/Request/Http.php on line 504′ in /magentorootpath/app/code/core/Mage/Core/functions.php:243

    Payment method is “Check / Money order ” for this order.

    My cron code is:

    if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW)
                  try {
                    if(!$order->canInvoice()) {
                        $order->addStatusHistoryComment('Cron Invoicer0: Order cannot be invoiced.', false);
                    //START Handle Invoice
                    $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
                    $order->addStatusHistoryComment('Automatically INVOICED by Cron Invoicer.', false);
                    $transactionSave = Mage::getModel('core/resource_transaction')
                    //END Handle Invoice
                    $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);      
                   } catch (Exception $e) {
                        $order->addStatusHistoryComment('Cron Invoicer1: Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);

    Thanks & Regards,
    Richard Campbell

  10. Thanks it’s work perfectly.

    But how can I create many invoices for one order please ?
    (For a month subscription per example)

    I incremented the “quantity ordered” of items.
    This create invoices, but 0 as price…

  11. Also one more question

    How can I select the option of “Email Copy of Invoice” programatically?(like we do for capture).

    thanks in advance

  12. I tried the code and I get this fatal error

    “Fatal error: Call to a member function getModelInstance() on a non-object in /var/www/vhosts/******/httpdocs/app/Mage.php on line 432”.

    What could have gone wrong?

  13. Thanks for you tutorial. Anyone, please feel free to respond to my postl

    I am new to magento, can you please tell me what file to make this change.

    Does this code automatically create the invoice? The reason I ask is that am using ShipRush and it will not process shipping unless invoice was created. It is much task to manually go into each order and create the invoice.

    Thanks for your attention.

  14. hello

    I am new in magento.I have used magento version.I upload new template grayscale but in this time i face big problem in admin area system-transactional email because when i create a new order email template then show all template perview in html coding and not show text perview. Please help me v v v v v urgent .

  15. Great article, worked immediately.

    Just one question:
    Is there a way to then set the order status to complete after the invoice has been created? I tried


    but it told me I wasn’t allowed to set the order status to complete from there. What does the system normally do when an order has been completed and the payment transferred?

    Thanks in advance

  16. Works great. Thank you!

    For Cron job you need a cPanel access and there you can set manually and add the file path
    e.g. php -f/home/yourdomain/public_html/folder_path/to_your_file/invoice_from_order.php

    Hope that helps!

  17. Thank you very much ! Your tip helps me a lot to solve a bug between paypal and Magento who doesn’t create an invoice where the payment is done.

  18. Very helpful. I found 3 different variants of creating invoice, but only this works. Perfect.

  19. Buddy,

    We need to know that we are getting message “Unable to Save Invoice” while we are trying to save invoice by going in orders.

    Plesae let us know which thing needs to be fix. Please help us! Thanks in advance.

  20. Thanks for this information, but is it possible we can provide a customer to take print out of invoice so that they can use in banking.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

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