I have the same problem, but this only happens when I try to generate invoices in Loop. The first transaction creates an invoice & transaction in DB but when I attempt to capture payment ( ONLINE ) in the loop for second order, the system generates invoices correctly. Still, when I save the order to Generate a Capture Transaction in Db, the system gives me an error.
{"error":"Set order for existing transactions not allowed"}
Code
private function processNewInvoice(Order $order, array $items, $amount, $pendingInvoice, $id): Invoice|bool
{
try {
$this->_logger->info('Invoice Creation', ['invoice' => $pendingInvoice . '-' . $order->getEntityId()]);
$newInvoice = $order->prepareInvoice($items);
$newInvoice->setGrandTotal($amount);
$newInvoice->setData('ora_invoice_number', $pendingInvoice);
$newInvoice->setBaseGrandTotal($amount);
$this->_logger->info('Invoice to be processed', ['invoice' => $newInvoice->getData()]);
if (!$newInvoice->getTotalQty()) {
$this->_logger->debug('Cannot create an invoice without products for order ' . $order->getIncrementId());
throw new LocalizedException(__('Cannot create an invoice without products'));
}
$newInvoice->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
$newInvoice->register();
$newInvoice->getOrder()->setIsInProcess(true);
$newInvoice->save();
//Create Transaction
$transaction = $this->transactionFactory->create()
->addObject($newInvoice)
->addObject($order);
$transaction->save();
$comment = 'Amount of $' . number_format($newInvoice->getGrandTotal(), 2) . '. Transaction ID: "' . $newInvoice->getTransactionId() . '"';
$order->addCommentToStatusHistory($comment)->save();
} catch (Exception $exception) {
$this->_logger->critical('Cannot create invoice', ['error' => $exception->getMessage()]);
}
$this->_logger->info('Invoice Saved and captured', ['invoice' => $newInvoice->getId()]);
return $newInvoice;
}