Back to Top

How to programmatically create transaction in Magento2

Updated 22 February 2024

In this article we learn how to create transactions in Magento2 . A transaction is proof that payment has been done. In Magento transactions are created when invoice is created, although magento creates transaction by itself you don’t need to worry about that but in case you want to create an online payment method that requires you to redirect to different website for payment, and when it redirects back to the merchant website with the payment data, you will have to create the transaction manually, here is the code snippet that will create a transaction :

public function createTransaction($order = null, $paymentData = array())
{
    try {
        //get payment object from order object
        $payment = $order->getPayment();
        $payment->setLastTransId($paymentData['id']);
        $payment->setTransactionId($paymentData['id']);
        $payment->setAdditionalInformation(
            [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $paymentData]
        );
        $formatedPrice = $order->getBaseCurrency()->formatTxt(
            $order->getGrandTotal()
        );

        $message = __('The authorized amount is %1.', $formatedPrice);
        //get the object of builder class
        $trans = $this->_transactionBuilder;
        $transaction = $trans->setPayment($payment)
        ->setOrder($order)
        ->setTransactionId($paymentData['id'])
        ->setAdditionalInformation(
            [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $paymentData]
        )
        ->setFailSafe(true)
        //build method creates the transaction and returns the object
        ->build(\Magento\Sales\Model\Order\Payment\Transaction::TYPE_CAPTURE);

        $payment->addTransactionCommentsToOrder(
            $transaction,
            $message
        );
        $payment->setParentTransactionId(null);
        $payment->save();
        $order->save();

        return  $transaction->save()->getTransactionId();
    } catch (Exception $e) {
        //log errors here
    }
}

In the above code, I have created a function that will accept two params,
the first parameter is $order which is of type Magento\Sales\Model\Order,
you need to load the order with order id, I suppose you know about this .

And the second param $paymentData is assumed to be an array that is returned by the
payment gateway after successful pament.

We assume that the $paymmentData[‘id’] holds the id of the successful payment.
$this->_transactionBuilder is of type :
Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface,
you don’t need to worry about the Interface magento2 already defines it in
sales-module di.xml, preference class for the interface.

When the build method is called on the builder class after setting the required
params, it automatically creates the transaction object and saves the transaction
within the order.

Searching for an experienced
Magento 2 Company ?
Find out More

Thats all in this, hope it will help you, try the above code and
if you have any issue just comment below 🙂 .

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


9 comments

  • Lucas (Brazil)
  • gaurav
  • Ömür Yanıkoğlu
    • Webkul Support
  • Shailendra Kumar
    • Ashutosh Srivastava
      • Shailendra Kumar
  • shivraj
    • Ashutosh Srivastava
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home