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.
Review other articles maybe it'll help you too.
- How to Add Image Uploader on Store Configuration in Magento 2
- How to Add Custom Select/MultiSelect Options on Store Configuration in Magento 2
- How to Add Dynamic Row on Store Configuration in Magento 2
- How to Add Date & time Picker on Store Configuration in Magento 2
- How to Add Link on Store Configuration Fields Comment in Magento 2
- How to Use Javascript Mixins in Magento 2
- How to Add Custom Validation Rule in Magento 2
- How to Get Product Collection
- How to Setup Magento 2 PWA Studio
- How to Get Current Category
- How to Get Current Product
- Get Product Collection with Filters
- How to Create And Use Plugin In Magento 2
- How to Create/Use Message Queue in Magento 2
- How to Run Direct SQL Query in Magento 2
- How to create JSON controller in Magento 2
- How to Perform 3rd party API operations in your Magento 2 using GuzzleHttp