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.