3

In a custom Magento 2 module, I have some code that successfully creates an order from a quote and sets the status to "pending".

After payment, I would like to programmatically validate the order, generate the invoice and send the confirmation email to the client.

The code that sets the status to complete:

// Update the status
$order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);
$order->setStatus('complete');
$order->save(); 

Unfortunately, this doesn't generate an invoice and send the final email. How are we supposed to perform these action programmatically from an existing/pending order?

1

By default Magento, the Order will automatically change the status to completed when it has Invoice and Shippment.

We can create invoice programmatically with \Magento\Sales\Model\Service\InvoiceService::prepareInvoice();

vendor/magento/module-sales/Controller/Adminhtml/Order/Invoice/Save.php::save()

$invoice = $this->invoiceService->prepareInvoice($order, $invoiceItems);

$invoice->register();

And then, try to send email by using Magento\Sales\Api\InvoiceManagementInterface::notify()

For the shippment, you can google to find the way to create the shipment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.