How to programmatically create invoice in magento2

If we need to programmatically create invoice for an order then you can create by following way.


// Load the order

 $order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->loadByAttribute('increment_id', '000000009');

// OR

$order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->load('1');


if ($order->canInvoice()) {
    // Create invoice for this order
    $invoice = $this->_objectManager->create('Magento\Sales\Model\Service\InvoiceService')->prepareInvoice($order);

    // Make sure there is a qty on the invoice
    if (!$invoice->getTotalQty()) {
        throw new \Magento\Framework\Exception\LocalizedException(
                    __('You can\'t create an invoice without products.')
                );
    }

    // Register as invoice item
    $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
    $invoice->register();

    // Save the invoice to the order
    $transaction = $this->_objectManager->create('Magento\Framework\DB\Transaction')
        ->addObject($invoice)
        ->addObject($invoice->getOrder());

    $transaction->save();

    // Magento\Sales\Model\Order\Email\Sender\InvoiceSender
    $this->invoiceSender->send($invoice);
    
    $order->addStatusHistoryComment(
        __('Notified customer about invoice #%1.', $invoice->getId())
    )
        ->setIsCustomerNotified(true)
        ->save();
}

2 thoughts on “How to programmatically create invoice in magento2

  1. Hey! Article is great, only one problem, the email is sent in english language even if it should send in Slovak. If I create/send invoice from the administration manually it’s sent in Slovak, but when created from code, it’s sent in english. Any idea?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.