Magento – How to setup Auto Invoice in Magento 2

gift-cardinvoicemagento-2.1payment-methods

I am using two payment methods

  1. Credit Card (Authorize.net CIM)
  2. Paypal (Standard)

And currently, I am invoicing new orders manually but I would like to set-up an auto invoice method because now we have some Gift Card products, so if it's possible to invoice automatically then purchasing GiftCard turn to active status during the place order and my users could use gift card codes right away otherwise my users should wait for me to invoice and to use Gift Codes.

For credit card, I am using Payment action as "Authorize and Capture".

For PayPal, I am using Payment action as "Sale".

Best Answer

I know the question is already 1year old tomorrow but this is MAGENTO, I have 2 pending questions that might get answered next year so I guess I'm sharing my solution to this question so maybe others who are waiting for years may benefit.

The best solution would be to use an observer like this

Unfortunately, I failed to make it work so I edited my vendor/magento/module-checkout/Block/Onepage/Success.php file and added the code inside protected function prepareBlockData()

$order = $this->_checkoutSession->getLastRealOrder();

$invoice = $objectManager-> create('Magento\Sales\Model\Service\InvoiceService')->prepareInvoice($order);

if (!$invoice->getTotalQty()) {
                throw new \Magento\Framework\Exception\LocalizedException(
                            __('You can\'t create an invoice without products.')
                        );
            }

$invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::STATE_PAID);
$invoice->register();

$transaction = $objectManager->create('Magento\Framework\DB\Transaction')
                ->addObject($invoice)
                ->addObject($invoice->getOrder());

            $transaction->save();

            $invoiceSender = $objectManager->get('Magento\Sales\Model\Order\Email\Sender\InvoiceSender');
            $invoiceSender->send($invoice);

$order->addStatusHistoryComment(
                __('Notified customer about invoice #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(true)
                ->save();

You don't have to follow what I did. You can do what the magento experts who are saying Don't edit, just override. I just don't care. As a programmer, I loathe magento because of so many things I don't wanna share. Someday, I will do something better than this shit.