How to programmatically create invoice in magento2

How to programmatically create invoice in magento2 – In Magento sometimes we need to generate the invoice of an order automatically when the order is placed or the payment status is successful for a particular order.

If you want to programmatically create the invoice for a particular order then please follow the below solution.

Here you can learn here how to create an invoice for a particular order or a part of a particular order using item ids.

Create invoice for a new order-

Step 1. Create a Controller CreateInvoice.php in your custom module at app / code / { vendorname } / { modulename } / Controller / { Action } /

Write the below code inside your controller file (CreateInvoice.php) :

/**
 * Copyright © https://armmage.com/ All rights reserved.
 * See COPYING.txt for license details.
 */

namespace ArmMage\InvoiceModule\Controller\Blogs;

use Magento\Framework\App\Action\Action;

use Magento\Framework\App\Action\Context;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Service\InvoiceService;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
use Magento\Framework\DB\Transaction;

class CreateInvoice extends Action
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var InvoiceService
     */
    private $invoiceService;

    /**
     * @var Transaction
     */
    private $transaction;


    /**
     * Constructor
     *
     * @param Context $context,
     * @param OrderRepositoryInterface $orderRepository,
     * @param InvoiceService $invoiceService,
     * @param InvoiceSender $invoiceSender,
     * @param Transaction $transaction
     */
    public function __construct(
        Context $context,
        OrderRepositoryInterface $orderRepository,
        InvoiceService $invoiceService,
        InvoiceSender $invoiceSender,
        Transaction $transaction
    ) {
        $this->orderRepository = $orderRepository;
        $this->invoiceService = $invoiceService;
        $this->invoiceSender = $invoiceSender;
        $this->transaction = $transaction;
        parent::__construct($context);
    }
    /**
     * Marketplace order invoice controller.
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $orderId = 9; //order id for which want to create invoice
        $order = $this->orderRepository->get($orderId);
        if ($order->canInvoice()) {
            $invoice = $this->invoiceService->prepareInvoice($order);
            $invoice->register();
            $invoice->save();
            $transactionSave = $this->transaction->addObject(
                $invoice
            )->addObject(
                $invoice->getOrder()
            );
            $transactionSave->save();
            $this->invoiceSender->send($invoice);
            //send notification code
            $order->addStatusHistoryComment(
                __('Notified customer about invoice #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(true)
                ->save();
        }
    }
}

The above example will let you generate order invoice for the complete order .

Now, If there are multiple items in your order and you want to and you want to generate invoice for a particular item in your order then please follow the below code to be able to do so.

Step 1. Create a Controller CreateInvoice.php in your custom module at app / code / { vendorname } / { modulename } / Controller / { Action } /

Create invoice for a particular item in your order

/**
 * Copyright © https://armmage.com/ All rights reserved.
 * See COPYING.txt for license details.
 */

 namespace ArmMage\InvoiceModule\Controller;

 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;
 use Magento\Sales\Api\OrderRepositoryInterface;
 use Magento\Sales\Model\Service\InvoiceService;
 use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
 use Magento\Framework\DB\Transaction;


class CreateInvoice extends Action
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var InvoiceService
     */
    private $invoiceService;

    /**
     * @var Transaction
     */
    private $transaction;

    /**
     * @var InvoiceSender
     */
    private $invoiceSender;


    public function __construct(
        Context $context,
        OrderRepositoryInterface $orderRepository,
        InvoiceSender         $invoiceSender,
        InvoiceService $invoiceService,
        Transaction $transaction
    ) {
        $this->orderRepository = $orderRepository;
        $this->invoiceService = $invoiceService;
        $this->invoiceSender = $invoiceSender;
        $this->transaction = $transaction;
        parent::__construct($context);
    }
    /**
     * Marketplace order invoice controller.
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $orderId = 1; //order id for which want to create invoice
        $order = $this->orderRepository->get($orderId);
        if($order->canInvoice()) {
            $itemsArray = ['80'=>2]; //here 80 is order item id and 2 is it's quantity to be invoice
            $shippingAmount = '10.00';
            $subTotal = '110.00';
            $baseSubtotal = '110.00';
            $grandTotal = '110.00';
            $baseGrandTotal = '110.00';
            $invoice = $this->invoiceService->prepareInvoice($order, $itemsArray);
            $invoice->setShippingAmount($shippingAmount);
            $invoice->setSubtotal($subTotal);
            $invoice->setBaseSubtotal($baseSubtotal);
            $invoice->setGrandTotal($grandTotal);
            $invoice->setBaseGrandTotal($baseGrandTotal);
            $invoice->register();
            $transactionSave = $this->transaction->addObject(
                $invoice
            )->addObject(
                $invoice->getOrder()
            );
            $transactionSave->save();
            $this->invoiceSender->send($invoice);  
            //send notification code
            $order->addStatusHistoryComment(
                __('Notified customer about invoice #%1.', $invoice->getId())
            )
            ->setIsCustomerNotified(true)
            ->save();
        }
    }
}



Ready to elevate your e-commerce business?

Discuss your business objectives with us. Get in touch today to explore ways we can assist in reaching them.

Copyright © 2021-present ArmMage Inc. All rights reserved.