cancel
Showing results for 
Search instead for 
Did you mean: 

Create transaction programmatically

SOLVED

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.

2 REPLIES

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->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());
        }
    }