Hello everyone,
How can we create a transaction programmatically for an existing order in Magento 2?
Thanks a lot for your answers.
Solved! Go to Solution.
I meant create a transaction (auth, capture...) for an existing order that has no payment yet.
I found the answer, here it is:
public function addTransactionToOrder($order, $paymentData = array()) { try { // Prepare payment object $payment = $order->getPayment(); $payment->setMethod('my_payment_method'); $payment->setLastTransId($paymentData['id']); $payment->setTransactionId($paymentData['id']); $payment->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData]); // Formatted price $formatedPrice = $order->getBaseCurrency()->formatTxt($order->getGrandTotal()); // Prepare transaction $transaction = $this->transactionBuilder->setPayment($payment) ->setOrder($order) ->setTransactionId($paymentData['id']) ->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData]) ->setFailSafe(true) ->build(Transaction::TYPE_CAPTURE); // Add transaction to payment $payment->addTransactionCommentsToOrder($transaction, __('The authorized amount is %1.', $formatedPrice)); $payment->setParentTransactionId(null); // Save payment, transaction and order $payment->save(); $order->save(); $transaction->save(); return $transaction->getTransactionId(); } catch (Exception $e) { $this->messageManager->addExceptionMessage($e, $e->getMessage()); } }
Hi @davidfiaty,
Can you explain a little bit more what do you mean by transaction? (because you said you got hte Order already)
I meant create a transaction (auth, capture...) for an existing order that has no payment yet.
I found the answer, here it is:
public function addTransactionToOrder($order, $paymentData = array()) { try { // Prepare payment object $payment = $order->getPayment(); $payment->setMethod('my_payment_method'); $payment->setLastTransId($paymentData['id']); $payment->setTransactionId($paymentData['id']); $payment->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData]); // Formatted price $formatedPrice = $order->getBaseCurrency()->formatTxt($order->getGrandTotal()); // Prepare transaction $transaction = $this->transactionBuilder->setPayment($payment) ->setOrder($order) ->setTransactionId($paymentData['id']) ->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData]) ->setFailSafe(true) ->build(Transaction::TYPE_CAPTURE); // Add transaction to payment $payment->addTransactionCommentsToOrder($transaction, __('The authorized amount is %1.', $formatedPrice)); $payment->setParentTransactionId(null); // Save payment, transaction and order $payment->save(); $order->save(); $transaction->save(); return $transaction->getTransactionId(); } catch (Exception $e) { $this->messageManager->addExceptionMessage($e, $e->getMessage()); } }
How should be calling this method and which data should be pass in $paymentData?