Magento 2 – How to Get Order Data After Placing Order in Checkout

checkoutmagento-2.1magento2payment-gateway

I want to implement custom payment gateway with redirect. I found a lot of questions about it here.

(Like Payment gateway with redirects in magento2. )

From which I think I have two options.

  1. After placing order, redirect customer to my custom controller, there have some logic and then redirect him to gw.
  2. Make AJAX req to my custom controller, that returns gw url, and redirect user there with JS.

But, in my custom controller, I somehow need to get the newly created order data, or at least id. Presumably, I should send them in my redirect/ajax req. But I don't know how.

Currently, my code in method-render looks like this:

return Component.extend({
    defaults: {
        template: 'Vendor_Module/payment/template',
        redirectAfterPlaceOrder: false
    },

    afterPlaceOrder: function () {
        $.mage.redirect(
            url.build('route/controller/action')
        );
    }

});

Is there a way I can add order data to the request? Or is there any other way I can retrieve order data in controller?


Note: In controller tried this

    /**
     * @var \Magento\Checkout\Model\Type\Onepage\Interceptor $onepage
     */
    $onepage = $this>_objectManager>get('Magento\Checkout\Model\Type\Onepage');
    $orderId = $onepage->getLastOrderId();

But I don't think it's transaction save. I get an id even when I do random get request on my controller. Also I don't know how this behave when two orders are placed at the same time.

Best Answer

magento\app\code\Custom\Module\etc\frontend\events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer name="custom_frontend_observer" instance="Custom\Module\Observer\OrderPlaceAfter" />
    </event>
</config>

magento\app\code\Custom\Module\Observer\OrderPlaceAfter.php

namespace Custom\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ObjectManager;

class OrderPlaceAfter implements ObserverInterface {

    public function execute(Observer $observer) {

        $orderId = $observer->getEvent()->getOrderIds();

        $order = $this->orderRepository->get($orderId[0]);

         if ($order->getEntityId()) { // Order Id
            $items = $order->getItemsCollection();
         }
    }
}   
Related Topic