How to create Create Invoice Programmatically in Magento 2

In Magento 2, aside from producing a product and customer programmatically, you can also generate invoices programmatically easily.

Why do Magento 2 websites require setting up the program for producing the invoice? As you know, every time an invoice is produced, that indicates that an order is placed successfully and at a similar time, Magento will tell you that have received the amount of money from the buyer. Nonetheless, in such a common way, you will get mass information from Magento 2 system as make an equal number of the invoices if your customer performs partial payment in the order. 

Steps to creating invoice programmatically in Magento 2

There are only two steps for creating the invoice programmatically.

  • Declare event sales_order_invoice_pay
  • Setup the observer class

Step#1: Declare event sales_order_invoice_pay

Start the settings with the events.xml file in your custom module:

File path:

/app/code/VendorName/ModuleName/etc/events.xml

Code:

<?xml version="1.0"?>

    <event name="sales_order_invoice_pay">

      <observer name="webpos_sales_order_invoice_pay" instance="VendorName\ModuleName\Observer\SalesOrderInvoicePay" />

    </event>  

</config>

Step#2: Setup the observer class

File path:

/app/code/VendorName/ModuleName/Observer/SalesOrderInvoicePay.php

Code:

<?php

namespace VendorName\ModuleName\Observer\Sales;

use Magento\Framework\Event\Observer as EventObserver;

use Magento\Framework\Event\ObserverInterface;

class SalesOrderInvoicePay implements ObserverInterface

{   

/**

* @param EventObserver $observer

* @return $this

*/

public function execute(EventObserver $observer)

{

     $invoice = $observer->getEvent()->getInvoice();

     $order = $invoice->getOrder();

   

     /* reset total_paid & base_total_paid of order */

     $order->setTotalPaid($order->getTotalPaid() - $invoice->getGrandTotal());

     $order->setBaseTotalPaid($order->getBaseTotalPaid() - $invoice->getBaseGrandTotal());

}    

}

If you are looking for Magento 2 Developers, visit Magento 2 Services.