Magento 2 – Redirect to 3rd Party Payment Gateway with Post Data

magento-2.1payment-gatewaypayment-methods

In Magento 1 we define the getOrderPlaceRedirectUrl in the model which extends Mage_Payment_Model_Method_Abstract and redirect to a particular controller after checkout submit. Then from the controller we call $this->getResponse()->setBody($this->getLayout()->createBlock('someblock')->toHtml()) and inside the block we create a form with post data and redirect to a 3rd party payment gateway.

In Magento 2 i heard that getOrderPlaceRedirectUrl is not available and i'm unable to understand how it is handled. Can someone please guide me to achieve the above scenario in Magento 2.1?

Best Answer

In Magento 2 you have to create custom JavaScript component responsible for redirect to a Payment Provider. So how it works in Magento 2.

Custom redirect.html template with "Place Order" button should be created This template is controlled by a redirect.js JavaScript component with afterPlaceOrder function inside which you can send HTTP GET request to your custom controller which will return parameters required for sending HTTP POST request to a payment gateway.

afterPlaceOrder: function () {
    var self = this;
    $.get(config.getDataUrl())
        .done(function (response) {
            customerData.invalidate(['cart']);
            formBuilder(response).submit();
        }).fail(function (response) {
            errorProcessor.process(response, self.messageContainer);
        }).always(function () {
            fullScreenLoader.stopLoader();
        });
}

The config.getDataUrl() is custom controller URL. Here you do implement 2 different ways of POST parameters preparation. URL can be prepared from backend side and provided to a frontend by implementing the \Magento\Checkout\Model\ConfigProviderInterface::getConfig() method.

Return key => value array of parameters as a response. The formBuilder(response).submit() will foreach parameters and prepare form which will be submitted to a payment provider as post.

var formTmpl =
    '<form action="<%= data.action %>" method="POST" hidden enctype="application/x-www-form-urlencoded">' +
    '<% _.each(data.fields, function(val, key){ %>' +
    '<input value="<%= val %>" name="<%= key %>" type="hidden">' +
    '<% }); %>' +
    '</form>';

return function (response) {
    var inputs = {};
    for (var index in response.fields) {
        inputs[response.fields[index]] = response.values[index]
    }
    var hiddenFormTmpl = mageTemplate(formTmpl);
    var tmpl = hiddenFormTmpl({
        data: {
            action: response.action,
            fields: inputs
        }
    });
    return $(tmpl).appendTo($('[data-container="body"]'));
};

Render form wrapped in a <html><body><form/></body></html> on backend side using Block and *.phtml file with inline JavaScript inside the response. Once retrieved, JavaScript will trigger redirect. It is less recommended way but might be less time consuming.