In this tutorial we will learn step by step to create invoice programmatically in Magento 2. Invoice in Magento 2 is very comprehensive for merchants.
In Magento 2, invoice can be created from admin. When you place an order in Magento 2 e-commerce website then there is two scenarios of create invoice in Magento 2.
Create invoice in Magento 2
If the order is placed using Authorize and capture method then invoice will be created at the time of order created successfully.
If the order is placed using Authorize only payment option then, Admin or store manager has to create invoice for capturing the order grand total amount.
These above two methods are default method or we can inbuilt method to create invoice in Magento 2.
Requirement of create invoice programmatically in Magento 2
So the question is why we need to create invoice programmatically in Magento 2. If Magento 2 provides inbuilt functionality to create invoice.
Create invoice programmatically in Magento 2 is useful in cases like –
- When any third party is using your website for creating order.
- On successful callbacks of any event in order processing.
- When you have to create partial invoice for partial payment
Let’s start create invoice programmatically in Magento 2
class OrderInvoice extends Magento\Framework\App\Action\Action
* @var \Magento\Sales\Api\OrderRepositoryInterface
* @var \Magento\Sales\Model\Service\InvoiceService
* @var \Magento\Framework\DB\Transaction
public function __construct(
$this->_orderRepository = $orderRepository;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
* order invoice controller.
* @return \Magento\Framework\View\Result\Page
public function execute()
$orderId = 1; //get the order id for which you want to generate invoice
$order = $this->_orderRepository->get($orderId);
$invoice = $this->_invoiceService->prepareInvoice($order);
$transactionSave = $this->_transaction->addObject($invoice)->addObject($invoice->getOrder());
//send email notification code
__(‘Notified customer about invoice #%1.’, $invoice->getId())
Create invoice programmatically in Magento 2 after placing order