Magento 2 Create Invoice Programmatically

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 normal way, you will get mass notifications from Magento 2 system as well as create the equivalent number of the invoices if your customer implements partial payment within the order. Therefore, this topic is the great solution to form the invoice while there is no dependency on the total paid of order.

Mageplaza brings you two simple steps for that and here you are!

Overview of creating invoice programmatically in Magento 2

Step 1: Declare event sales_order_invoice_pay

Start the settings with events.xml file in your custom module: /app/code/Mageplaza/HelloWorld/etc/events.xml

<?xml version="1.0"?>
    <event name="sales_order_invoice_pay">
        <observer name="webpos_sales_order_invoice_pay" instance="Mageplaza\HelloWorld\Observer\SalesOrderInvoicePay" />

Step 2: Setup the observer class


namespace Mageplaza\HelloWorld\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());

Magento 2 PDF Invoice: Invoice customers with ease

Related Topics

Enjoyed the tutorial? Spread it to your friends!


Sam Thomas
Sam Thomas

CEO and Founder of Mageplaza. Pursueing a simple and healthy lifestyle. A friend, a husband and a dad of two children, a trainer and an influencer wannabe. He is a big fan of sports and travel, also.

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.2.x, 2.3.x, 2.4.x