How to create an order and update transaction to order - transaction response from a payment gateway?

As I have stated already, an order should be created BEFORE you redirect a customer to a payment gateway, so the order will exist on the customer’s return from the payment gateway.
Moreover, I recommend update the order not on a customer return, but on the notification from the payment gateway about the order has been successfully paid.
For example, PayPal uses the term Instant Payment Notification (IPN) for such notifications.