How to Create Invoice Programmatically in Magento 2 [2024]

In Magento 2, apart from creating product and customer programmatically, you can also create invoice programmatically with ease when following the given guides in the Magento 2 create invoice programmatically topic.

Why do Magento 2 stores need to set up the program for creating the invoice? As you know, each time an invoice is created, that means an order is placed successfully and at the same time, Magento will notify you have earned the amount of money from the customer. However, by such a normal way, you will get mass notifications from the Magento 2 system as well as create the equivalent number of the invoices if your customer implements partial payment within the order. Therefore, the great solution is to form the invoice while there is no dependency on the total payment of order.

This post is a helpful guide to help you use this solution at its best. You will only have to go through two simple steps to solve the problem right away. Let’s get started!

Mageplaza brings you a step-by-step tutorial for that and here you are!

How to create invoice programmatically in Magento 2:

Create the File: /app/code/Mageplaza/HelloWorld/Controller/CreateInvoice.php.

<?php

namespace Mageplaza\HelloWord\Controller\Invoice;

class CreateInvoice extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    protected $_orderRepository;

    /**
     * @var \Magento\Sales\Model\Service\InvoiceService
     */
    protected $_invoiceService;
    
    /**
     * @var \Magento\Framework\DB\Transaction
     */
    protected $_transaction;
    
    /**
     * @var \Magento\Sales\Model\Order\Email\Sender\InvoiceSender
     */
    protected $_invoiceSender;
    
    /**
     * CreateInvoice constructor.
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     * @param \Magento\Sales\Model\Service\InvoiceService $invoiceService
     * @param \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender
     * @param \Magento\Framework\DB\Transaction $transaction
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Model\Service\InvoiceService $invoiceService,
        \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender,
        \Magento\Framework\DB\Transaction $transaction
    ) {
        $this->_orderRepository = $orderRepository;
        $this->_invoiceService  = $invoiceService;
        $this->_invoiceSender   = $invoiceSender;
        $this->_transaction     = $transaction;
        parent::__construct($context);
    }
    
    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Exception
     */
    public function execute()
    {
        $orderId = $this->_request->getParam('order_id');
        $order   = $this->_orderRepository->get($orderId);
        if ($order->canInvoice()) {
            $invoice = $this->_invoiceService->prepareInvoice($order);
            $invoice->register();
            $invoice->save();
            $transactionSave = $this->_transaction->addObject(
                $invoice
            )->addObject(
                $invoice->getOrder()
            );
            $transactionSave->save();
            $this->_invoiceSender->send($invoice);
    
            //send notification code
            $order->addCommentToStatusHistory(
                __('Notified customer about invoice #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(true)
                ->save();
}
}

Related Topics

What Should You Choose: Magento 2 Create Invoice Programmatically or Automatically?

Handling a small number of orders programmatically is relatively easy. However, the challenges of creating and processing every Magento 2 orders’ invoices programmatically arise when there is an increasing number of orders, expanding sales channels, and the need to add more inventory to meet growing customer demands.

As the manual workload increases, human errors become more common, leading to a negative impact on customer satisfaction. Therefore, we strongly recommend automating invoice generation using Magento’s invoice extension. The extension that helps create Magento 2 invoices automatically will make your order management system a reliable assistant, eliminating bottlenecks when handling a high volume of orders and ensuring smoother business operations.

Mageplaza’s Magento 2 PDF Invoice is a feature-rich extension that automates invoice generation for your Magento 2 site, with the following highlighted features:

  • Automatically create invoices with necessary order details and payment methods.
  • Customize the designs of both invoices and credit memos to match their brand identity and preferences.
  • Attach PDF invoices to customer emails, ensuring smooth and efficient delivery.


FDF Invoice

PDF Invoice for Magento 2

Impress your customers with professional PDF invoices that match your store's branding

Check it out!


Conclusion

That’s all. The simple and easy-to-follow tutorial on creating invoices programmatically in Magento 2 is given to you. I hope that it actually works on your Magento 2 store. Invoices and creating accurate invoices are important in any online stores as it impacts on the customer trust and the order confirmation. Therefore, follow above-mentioned steps to create important invoices more easily and accurately.

Creating invoices in Magento 2 programmatically will automate the invoicing process, saving time and reducing manual effort. However, as the number of orders and channels grows, ensuring smooth delivery to customers without any issues becomes crucial. To maximize cost and time savings while ensuring that orders are fulfilled without any difficulties, it is wise to consider automated invoice generation instead of Magento 2 creating invoice programmatically.

Thanks for reading.

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.

People also searched for

  • magento 2 create invoice programmatically
  • create invoice programmatically magento 2
  • openerp create invoice programmatically magento 2
  • quickbooks create invoice programmatically magento 2
  • magento 2 create order invoice programmatically
  • magento 2 create invoice pdf programmatically
  • magento 2 create partial invoice programmatically
  • how to create invoice programmatically in magento 2
  • create invoice programmatically in magento 2
  • magento 2 create invoice for order programmatically
  • 2.3.x, 2.4.x
x