Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Create Invoice Programmatically in Magento 2 [2024]

Vinh Jacker | 12-18-2024

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.

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.

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services