How to create Magento invoice from order

Featured Image

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 :-)

Interested in hiring us?

Have a chat with us. You would be surprised how small changes can make your business even more successful.


About Domagoj Potkoc

Backend Developer

Domagoj is Magento Certified Developer who enjoys playing tennis after long hours in front of computer screen.

Read more posts by Domagoj / Visit Domagoj's profile

28 comments

  1. 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

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

    But it did not work.

    Can you tell me what else I can do.

    Thanks in advance,
    Vicky

  2. Totally not clear.

    I try put both your code at cron.php after last line, and access the http://domain.com/cron.php , 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.

  3. 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.

  4. 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.

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

    Thanks again and congrats!

  6. Thanks for this code! Amazing!

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

    Thanks in advance!

  7. 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);
                        $order->save();
                    }
    
                    //START Handle Invoice
                    $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
    
                    $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
                    $invoice->register();
    
                    $invoice->getOrder()->setCustomerNoteNotify(false);
                    $invoice->getOrder()->setIsInProcess(true);
                    $order->addStatusHistoryComment('Automatically INVOICED by Cron Invoicer.', false);
    
                    $transactionSave = Mage::getModel('core/resource_transaction')
                        ->addObject($invoice)
                        ->addObject($invoice->getOrder())
                         ->save();
                    //END Handle Invoice
                    $order->save();
                    $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);      
                   } catch (Exception $e) {
                        $order->addStatusHistoryComment('Cron Invoicer1: Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
                        $order->save();
                    }
                }

    Thanks & Regards,
    Richard Campbell

  8. 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…

  9. Also one more question

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

    thanks in advance

  10. 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?

  11. 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.

  12. hello

    I am new in magento.I have used magento 1.6.1.0 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 .
    Thanks

  13. 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

    $order->setState(Mage_Sales_Model_Order::STATE_COMPLETE);

    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

  14. Works great. Thank you!

    Chintan:
    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!

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

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

  17. 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.

  18. 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> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.