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 🙂
31 comments
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..
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?
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,
Vicky
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.
“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.
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.
Hi please anyone suggest me how to make print of invoice without submitting order in magento my website name is http://www.wineonlineindia.in please help me how to do it
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.
Bu they’re pending only on the user interface (Customer Dashboard) in admin area they’re all invoiced.
Thanks again and congrats!
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!
Thank you, very informative article.
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:
Thanks & Regards,
Richard Campbell
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…
Good Job.
Thanks for your tutorial
Also one more question
How can I select the option of “Email Copy of Invoice” programatically?(like we do for capture).
thanks in advance
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?
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.
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
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
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!
Any tips on how to achieve this using Cron job?
What about doing a partial invoice from code :)?
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.
Very helpful. I found 3 different variants of creating invoice, but only this works. Perfect.
This is a very nice tip to create invoice quickly.
Cool!
This is a great start. We also used invoice templates until our business grew so much that we had to switch to an online service called oneclick statements
-Andy
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.
AWESOME :)) works perfectly in magento 1.5.1.0. Thank you!
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.
Thank you Domagoj. It’s clear a lot.
Good tips for magento users. I’ve 2-3 e-commerce sites that using magento.