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

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

7 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago