How To

How to Programmatically Create Invoice using Root Script in Magento 2

Hello Magento Friends,

Hope all are doing well! Today’s subject matter is How to Programmatically Create Invoice using Root Script in Magento 2.

When an order is placed, Magento 2 order management system generates invoices. If you are accepting online payments via PayPal, Stripe, or other payment providers, an invoice is automatically generated.

But when an order is placed with cash on delivery or offline payments, the admin needs to create an invoice manually. Magento 2 Auto Invoice and Shipment extension can come as a savior for you to eliminate creating invoices manually. 

For now, follow the below steps to Programmatically Create Invoice using Root Script in Magento 2.

Steps to Programmatically Create Invoice using Root Script in Magento 2:

Step 1: Create invoicegenerate.php file in Magento root path and then add the below code

<?php
use Magento\Framework\AppInterface;
try
{
    require_once __DIR__ . '/app/bootstrap.php';
}
catch (\Exception $e)
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try
{
     $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
     $objectManager = $bootstrap->getObjectManager();
     $appState = $objectManager->get('\Magento\Framework\App\State');
     $appState->setAreaCode('frontend');

     $order_repository = $objectManager->get('Magento\Sales\Api\OrderRepositoryInterface');
     $invoice_service = $objectManager->get('Magento\Sales\Model\Service\InvoiceService');
     $transaction_factory = $objectManager->get('Magento\Framework\DB\TransactionFactory');

     $order_id = 1; // add your order id
     $order = $order_repository->get($order_id);
     
     if ($order->canInvoice())
     {
        $invoice = $invoice_service->prepareInvoice($order);
        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
        // two ways for CAPTURE_OFFLINE or CAPTURE_ONLINE
        $invoice->register();
        $invoice->getOrder()->setCustomerNoteNotify(false);
        $invoice->getOrder()->setIsInProcess(true);
        $order->addCommentToStatusHistory(__('Invoice Comment Part'), false);
        $transactionSave = $transaction_factory->create();
        $transactionSave->addObject($invoice)->addObject($invoice->getOrder());
        $transactionSave->save();
        print_r(' Your Invoice Generated Successfully for This Order ID :- '.$order_id);
     }
     else
     {
        print_r(' Your Invoice is not Generated for This order ID :- '.$order_id);
     }
}
catch(\Exception $e)
{
 print_r($e->getMessage());
}

Step 2: After adding the above code, run the below URL to check whether the invoice is created or not.

https://yourdomain/invoicegenerate.php/

Conclusion:

This way you can Programmatically Create Invoice using Root Script in Magento 2. In addition to this, you can also Add Order ID, Customer IP Address in Invoice in Magento 2.

In case of any doubts, share the details in the comment box. Also, share the article via your social media platforms and among your friend’s groups. Stay in the know for more solutions.

Happy Reading!

Click to rate this post!
[Total: 6 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 day ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

1 day ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

2 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

4 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We're thrilled to announce the release of Hyvä Themes 1.3.6 and 1.3.7! These latest updates…

4 days ago

How Modern E-Commerce Platforms Leverage Docker & Kubernetes for Scalability

Your e-commerce platform is surging - orders are rolling in, traffic spikes are becoming the…

5 days ago