Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5537

How to programmatically create invoice in magento2

$
0
0

If want to programmatically create invoice for an order then solution is here you can learn here how to create a invoice for an order or a part of your order.

Create invoice for a new order-

if($order->canInvoice()) {
    $invoice = $this->_objectManager->create('Magento\Sales\Model\Service\InvoiceService')->prepareInvoice($order);
    $invoice->register();
    $invoice->save();
    $transactionSave = $this->_objectManager->create(
        'Magento\Framework\DB\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();
}

Create invoice for a part of order

if($order->canInvoice()) {
    $itemsArray = array('80'=>2); //here 80 is order item id and 2 is it's quantity to be invoice
    $invoice = $this->_objectManager->create('Magento\Sales\Model\Service\InvoiceService')->prepareInvoice($order, $itemsArray);
    $invoice->setShippingAmount($shippingAmount);
    $invoice->setSubtotal($subTotal);
    $invoice->setBaseSubtotal($baseSubtotal);
    $invoice->setGrandTotal($grandTotal);
    $invoice->setBaseGrandTotal($baseGrandTotal);
    $invoice->register();
    $transactionSave = $this->_objectManager->create(
        'Magento\Framework\DB\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();
}

In this way you can create invoice for a particular product in a order or for a complete order. After creation of the invoice you can check it in admin panel sales order grid.


Viewing all articles
Browse latest Browse all 5537