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.