Magento 2 Tutorial: How To Create Invoice Programmatically

Invoice is a crucial element of Magento order processing. Store owners always have to make sure invoices are sent to customers on time to confirm their order information and allow customers to keep track of their purchases.

Usually, the invoice will be created automatically after the payment is authorized if the customer uses a payment method that has been integrated into the Magento 2 system.

However, if the customer uses a payment method such as check/money order, then the admin must create invoices manually.

So in this article, we will show you how to create Magento 2 Invoice programmatically!

What Is Magento Invoice?

Magento 2 Invoice is a record of payment for an order. 

From the business perspective, the invoice is a document that signifies a sales contract between a store and a customer and contains all of the order details. 

Invoices help online merchants in receiving payments more quickly.

How To Create Magento 2 Invoice Programmatically?

To create the Magento 2 Invoice programmatically, you need to create a new model in your module app/code/Vendor/Module/Model/CreateInvoice.php with the following code:

<?php

namespace [Vendor]\[Module]\Model;

use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Service\InvoiceService;
use Magento\Framework\DB\Transaction;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;

class CreateInvoice
{
    protected $orderRepository;
    protected $invoiceService;
    protected $transaction;
    protected $invoiceSender;

    public function __construct(
        OrderRepositoryInterface $orderRepository,
        InvoiceService $invoiceService,
        InvoiceSender $invoiceSender,
        Transaction $transaction
    ) {
        $this->orderRepository = $orderRepository;
        $this->invoiceService = $invoiceService;
        $this->transaction = $transaction;
        $this->invoiceSender = $invoiceSender;
    }

    public function execute($orderId)
    {
        $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);
           
            $order->addCommentToStatusHistory(
                __('Notified customer about invoice creation #%1.', $invoice->getId())
            )->setIsCustomerNotified(true)->save();
        }
    }
}

Then you can use ObjectManager to quickly test how it works:

\Magento\Framework\App\ObjectManager::getInstance()
    ->create(\Vendor\Module\Model\CreateInvoice::class)
    ->execute(4);

How To Create Magento 2 Invoice Automatically?

Even though creating invoices programmatically in Magento isn’t a difficult task, it still has many drawbacks.

  • It is very time-consuming to handle every orders’ invoices by hand
  • The increasing number of manual tasks will lead to more human errors, which negatively impact customer satisfaction.

Due to that, we highly recommend you create invoices automatically using a Magento invoice extension to make your business go more smoothly.

And hereby, we want to introduce you to the best invoice extension:

Magento 2 Auto Invoice by BSS

magento-2-auto-invoice

This extension helps to automatically generate invoices and shipment right after a customer finishes placing the order, which saves you a lot of time and effort.

Moreover, this module also sends invoice and shipment emails immediately to your customers. It will enhance customer satisfaction.

While most other modules require you to install another third-party PDF invoice extension, Magento 2 Auto Invoice by BSS already has a built-in PDF file to invoice/ shipment email.

Lastly, this extension supports many payment methods (COD, credit card, check/money order, PayPal, etc.)

Highlight features:

  • Automatically generate invoice and shipment based on payment methods for orders with a “new” order state
  • Automatically send invoice and shipment emails to customer
  • Apply automatic invoice and shipment for multiple payment methods

Conclusion

In this article, we have shown you how to create the Magento 2 invoice programmatically.

We also introduce you to the best solution to create the Magento 2 invoice automatically.

We hope this blog is helpful and good luck to you!

BSS Commerce is one of the leading Magento extension providers and web development services in the world. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize your business effectively. Furthermore, we offer FREE Installation – FREE 1-year Support and FREE Lifetime Update for every Magento extension.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Posts

Writing is a part of my life and I'm living for it.

Write A Comment

Name