Magento 2 How to Convert Order to Invoice Programmatically

In Magento2, we have the order object by using which we can convert the order to invoice programmatically using following code snippet.

<?php
namespace Magemeta\Invoice\Model;
 
use Magento\Sales\Model\Convert\Order;
 
class OrderToInvoice
{
    /**
     * @var Order
     */
    private $orderToInvoice;
 
    public function __construct(
        Order $orderToInvoice
    ) {
        $this->orderToInvoice = $orderToInvoice;
    }
 
    /**
     * convert order to invoice
     *
     * @param \Magento\Sales\Model\Order $order
     * @return Magento\Sales\Model\Order\Invoice
     */
    public function convertOrderToInvoice(\Magento\Sales\Model\Order $order)
    {
        // We used to convert order into invoice by using toInvoice() method
        $invoice = $this->orderToInvoice->toInvoice($order);
        return $invoice;
    }
}

Leave a Reply