Magento – How Redirect to 3rd party payment gateway in Magento2

magento-2.1payment-methodsredirect-url

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

You need to override the placeOrder function in your method-render JS function.

    'use strict';

    return Component.extend({
        defaults: {
            template: 'Yuansfer_Yuansfer/payment/form'
        },
        getCode: function () {
            return 'yuansfer_alipay';
        },
        isActive: function () {
            return true;
        },
        getMediaUrl: function () {
            return mediaUrl;
        },
        placeOrder: function (data, event) {
            if(event) {
              event.preventDefault();  
            }

            var self = this,
                placeOrder,
                emailValidationResult = customer.isLoggedIn(),
                loginFormSelector = 'form[data-role=email-with-possible-login]';

            if (!customer.isLoggedIn()) {
                $(loginFormSelector).validation();
                emailValidationResult = Boolean($(loginFormSelector + ' input[name=username]').valid());
            }

            if (emailValidationResult && this.validate() && additionalValidators.validate()) {
                this.isPlaceOrderActionAllowed(false);

                var setPaymentInfo = setPaymentInformationAction(this.messageContainer, self.getData());
                    $.when(setPaymentInfo).fail(function () {
                        self.isPlaceOrderActionAllowed(true);
                    }).done(
                            this.afterPlaceOrder.bind(this)
                        );
                    return true;
            }
            return false;
        },
        selectPaymentMethod: function () {
            selectPaymentMethodAction(this.getData());
            checkoutData.setSelectedPaymentMethod(this.item.method);
            return true;
        },
        afterPlaceOrder: function () {
            window.location.replace(url.build('module_name/controller/action/'));
        }
    });
}
);

The key is here afterPlaceOrder function. You should redirect to your save action here.