Magento 2 Create Auto Invoice for the COD Order
Creating an auto invoice for Cash On Delivery (COD) orders in Magento 2 requires customisation or extensions, as the default behaviour does not enable automated invoice generating for COD purchases. So, in this article we'll let you now how to create auto invoice for the Cash On Delivery Order In Magento 2.
Let's do it
Before we start I assume, you have already a created custom module. If you don't have it or don't know how to create it then check out our other article How To Create a Magento 2 Module.
Step 1: Create events.xml file at Devhooks/ModuleName/etc/ and paste the below code.
saveCopyzoom_out_map<?xml version="1.0" encoding="utf-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_submit_all_after">
<observer name="checkout_submit_all_after_cod" instance="Devhooks\ModuleName\Observer\Sales\Order\CodOrderAutoInvoice" />
</event>
</config>
In above code you can see we've used the CodOrderAutoInvoice class in observer instance, you can change it as per your file path.
Step 2: Create CodOrderAutoInvoice.php file at Devhooks/ModuleName/Observer/Sales/Order/ and paste the below code.
saveCopyzoom_out_map<?php
namespace Devhooks\ModuleName\Observer\Sales\Order;
use Magento\Framework\DB\TransactionFactory;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\InvoiceRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\Sales\Model\Service\InvoiceService;
class CodOrderAutoInvoice implements ObserverInterface
{
private CollectionFactory $invoiceCollectionFactory;
private InvoiceService $invoiceService;
private TransactionFactory $transactionFactory;
private InvoiceRepositoryInterface $invoiceRepository;
private OrderRepositoryInterface $orderRepository;
/**
* @param CollectionFactory $invoiceCollectionFactory
* @param InvoiceService $invoiceService
* @param TransactionFactory $transactionFactory
* @param InvoiceRepositoryInterface $invoiceRepository
* @param OrderRepositoryInterface $orderRepository
*/
public function __construct(
CollectionFactory $invoiceCollectionFactory,
InvoiceService $invoiceService,
TransactionFactory $transactionFactory,
InvoiceRepositoryInterface $invoiceRepository,
OrderRepositoryInterface $orderRepository
) {
$this->invoiceCollectionFactory = $invoiceCollectionFactory;
$this->invoiceService = $invoiceService;
$this->transactionFactory = $transactionFactory;
$this->invoiceRepository = $invoiceRepository;
$this->orderRepository = $orderRepository;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$orderId = $order->getId();
$payment = $order->getPayment();
$method = $payment->getMethodInstance();
$paymentMethodCode = $method->getCode();
$allowPaymentMethod = ['cashondelivery']; /* You can add more payment methods code in array. */
if (in_array($paymentMethodCode, $allowPaymentMethod)) {
$this->createInvoice($orderId);
}
}
protected function createInvoice($orderId)
{
try {
$order = $this->orderRepository->get($orderId);
if ($order) {
$invoices = $this->invoiceCollectionFactory->create()
->addAttributeToFilter('order_id', array('eq' => $order->getId()));
$invoices->getSelect()->limit(1);
if ((int)$invoices->count() !== 0) {
$invoices = $invoices->getFirstItem();
$invoice = $this->invoiceRepository->get($invoices->getId());
return $invoice;
}
if (!$order->canInvoice()) {
return null;
}
$invoice = $this->invoiceService->prepareInvoice($order);
$invoice->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(false);
$invoice->getOrder()->setIsInProcess(true);
$transactionSave = $this->transactionFactory->create()->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
return $invoice;
}
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(
__($e->getMessage())
);
}
}
}
We just put cashondelivery within the above code, but if you need to make auto invoices for other offline payment methods, add them to the $allowPaymentMethod array.
Bingo!! We have completed the code.
Now, open Command line, navigate to the Magento root directory and run the below commands.
saveCopyzoom_out_mapphp bin/magento c:c;
That's it!
Confirm your changes by placing test order with the COD payment method.
We hope this Magento article helped you to know How to generate auto invoice for the cach on delivery order in Magento 2.
Bookmark it for your future reference. Do comment below if you have any other questions on that.
P.S. Do share this article with your team.
AI-Powered Recommended Articles
How to Create Custom Payment Method in Magento 2
Step-by-step guide to creating a custom payment method in Magento 2 for your e-commerce store.
How to Create Custom Shipping Method in Magento 2
Learn how to create and integrate a custom shipping method in Magento 2 for customized shipping options.
How To Add Custom Field At Checkout Address Form – Magento 2
Learn how to add custom fields to the checkout address form in Magento 2 for enhanced customer data collection.
How to Use Event in Magento 2
Learn how to use events in Magento 2 to trigger custom functionality and extend store operations.
How to Create Custom Cron Job in Magento 2
Step-by-step guide on creating custom cron jobs in Magento 2 to automate tasks and improve store performance.
How To Create a Magento 2 Module
Follow this guide to create a custom Magento 2 module from scratch for extended functionality.