Showing results for 
Search instead for 
Did you mean: 

Create transaction programmatically


Create transaction programmatically

Hello everyone,

How can we create a transaction programmatically for an existing order in Magento 2?

Thanks a lot for your answers.


Re: Create transaction programmatically

Hi @davidfiaty,


Can you explain a little bit more what do you mean by transaction? (because you said you got hte Order already)

If you've found one of my answers useful, please give "Kudos" or "Accept as Solution"

Re: Create transaction programmatically

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->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData]);

            // Formatted price
            $formatedPrice = $order->getBaseCurrency()->formatTxt($order->getGrandTotal());
            // Prepare transaction
            $transaction = $this->transactionBuilder->setPayment($payment)
            ->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $paymentData])

            // Add transaction to payment
            $payment->addTransactionCommentsToOrder($transaction, __('The authorized amount is %1.', $formatedPrice));

            // Save payment, transaction and order
            return  $transaction->getTransactionId();

        } catch (Exception $e) {
            $this->messageManager->addExceptionMessage($e, $e->getMessage());