Redirecting to the Payment Provider
Redirect to a 3rd party site after the order is placed
Very often, after the shipping details are entered and the payment method is chosen on your website, the user needs to be redirected to a third-party site to complete the payment. You can easily do this in Scandi by writing a few plugins.
Note: In this example, we're implementing a specific payment method provider, Mollie. If you are making an extension for a different payment service, the steps outlined below might be slightly different. However, the general workflow of integrating a payment method will be similar: inspect the checkout source code and customize it through plugins.

Getting the Redirection URL

First, we need to get the URL that the user should be redirected to. For many payment extensions, this URL is included in the placeOrder GraphQL mutation response. Indeed, our example extension, Mollie, includes a mollie_redirect_url in the order field of the response.
However, as you may know, in GraphQL, only the fields that have been requested are found in the response. And of course, since mollie_redirect_url is an extension-specific field, it is not requested by default. Therefore, we need to write a plugin that will request this additional field as part of the placeOrder mutation.
After inspecting the Scandi source code, you'll find that the file responsible for creating the placeOrder mutation is scandipwa/src/query/Checkout.query.js.
All Scandi query creators live in the query folder. If you need to find the file responsible for a specific query, you can search for this query's name there.
First, let's take a look at the relevant parts of the originalCheckout.query file, to get an idea of what we're plugging in to:
scandipwa/src/query/Checkout.query.js
1
import { isSignedIn } from 'Util/Auth';
2
import { Field } from 'Util/Query';
3
​
4
/** @namespace Query/Checkout */
5
export class CheckoutQuery {
6
// ...
7
getPlaceOrderMutation(guestCartId) {
8
const mutation = new Field('s_placeOrder')
9
.setAlias('placeOrder')
10
.addField(this._getOrderField());
11
​
12
if (!isSignedIn()) {
13
mutation.addArgument('guestCartId', 'String', guestCartId);
14
}
15
​
16
return mutation;
17
}
18
// ...
19
​
20
_getOrderField() {
21
return new Field('order')
22
.addFieldList(['order_id']);
23
}
24
​
25
// ...
26
}
27
​
28
export default new CheckoutQuery();
Copied!
As you see, the _getOrderField function is responsible for creating the order field, and populating it with the order_id subfield. We want to plug into this function to add an additional subfield – mollie_redirect_url.
So let's create a new plugin file! In the plugin directory of your extension, create a new Javascript file that ends in .plugin.js. It's a good idea to name it after the query it plugs into, so we'll name ours Checkout.query.plugin.js.
In Scandi, plugins are functions that wrap around the original function (read the documentation for more details of how they work). In this case, it's really simple:
plugin/Checkout.query.plugin.js
1
const _getOrderField = (args, callback, instance) => {
2
// `callback` is the original function.
3
// By calling it, we get the original `order` field,
4
// which only contains 1 subfield, `order_id`, as seen above
5
return callback()
6
.addFieldList([
7
'mollie_redirect_url', // we add the redirect URL field
8
'mollie_payment_token' // and also this one (we'll need it later)
9
])
10
}
11
​
12
// This bit is the plugin configuration object.
13
export default {
14
// First, specify the namespace to plug in to.
15
"Query/Checkout": {
16
// There are different types of plugins, but since we're
17
// plugging into a member function (as opposed to static functions)
18
// we specify the "member-function" type
19
"member-function": {
20
// There's only 1 plugin we want to specify here
21
_getOrderField: _getOrderField
22
// (But we could plug into other functions too if we wanted!)
23
}
24
}
25
}
Copied!
If all goes smoothly, you should see a mollie_redirect_url value returned in the GraphQL response when completing an order with a Mollie payment method.
You can check the "Network" tab in your browser's developer tools to see the GraphQL responses. This can be useful for debugging requests!
Now, we have the redirect URL in the response, but we're not doing anything with it yet. The next step is to implement the actual redirection functionality.

Redirecting the User

First we need to find out which code is responsible for taking the user through the checkout steps. As the React Developer Tools extension will tell you, it's the Checkout route. We also know that the business logic (which is what we're interested in right now) most likely lives in the .container. So let's look at scandipwa/src/route/Checkout/Checkout.container.js , and the savePaymentMethodAndPlaceOrder function in particular:
scandipwa/src/route/Checkout/Checkout.container.js
1
// [imports...]
2
// [mapStateToProps and mapDispatchToProps]
3
​
4
/** @namespace Route/Checkout/Container */
5
export class CheckoutContainer extends PureComponent {
6
// [...]
7
​
8
async savePaymentMethodAndPlaceOrder(paymentInformation) {
9
const { paymentMethod: { code, additional_data } } = paymentInformation;
10
const guest_cart_id = !isSignedIn() ? getGuestQuoteId() : '';
11
​
12
try {
13
await fetchMutation(CheckoutQuery.getSetPaymentMethodOnCartMutation({
14
guest_cart_id,
15
payment_method: {
16
code,
17
[code]: additional_data
18
}
19
}));
20
​
21
const orderData = await fetchMutation(CheckoutQuery.getPlaceOrderMutation(guest_cart_id));
22
const { placeOrder: { order: { order_id } } } = orderData;
23
​
24
this.setDetailsStep(order_id);
25
} catch (e) {
26
this._handleError(e);
27
}
28
}
29
​
30
render() {...}
31
}
32
​
33
export default connect(mapStateToProps, mapDispatchToProps)(CheckoutContainer);
Copied!
The function sets the payment method for the order, and places the order. After the order is placed, it simply transitions to the order success step (also known as the "details step").
We want to change this functionality – instead of transitioning to the details step, we need to redirect the user to the final payment step, on the 3rd party website. We already made sure that CheckoutQuery.getPlaceOrderMutation will return the redirection URL in the response, so we just need to use that.
Let's write a plugin for savePaymentMethodAndPlaceOrder that will redirect the user if necessary. We can add it to our existing Checkout.container.plugin.js file:
plugin/Checkout.container.plugin.js
1
import { redirectToUrl } from '../util/Redirect';
2
import { getPaymentToken, setPaymentToken } from '../util/PaymentTokenPersistence';
3
​
4
const savePaymentMethodAndPlaceOrder = async (args, callback, instance) => {
5
const [paymentInformation] = args;
6
​
7
const { paymentMethod: { code, additional_data } } = paymentInformation;
8
const guest_cart_id = !isSignedIn() ? getGuestQuoteId() : '';
9
​
10
// It's important to check if the user has selected a Mollie payment method.
11
// We don't want to affect other methods, so we just use the callback directly in that case.
12
if (!MOLLIE_METHODS.includes(code)) {
13
return await callback(...args);
14
}
15
// Since this is a Mollie method, now we need some custom logic
16
​
17
try {
18
// Just like the original function, we set the payment method
19
await fetchMutation(CheckoutQuery.getSetPaymentMethodOnCartMutation({
20
guest_cart_id,
21
payment_method: {
22
code,
23
[code]: additional_data,
24
},
25
}));
26
​
27
// However, when placing the order, there is some additional data we need to consider
28
const orderData = await fetchMutation(CheckoutQuery.getPlaceOrderMutation(guest_cart_id));
29
const { placeOrder: { order: { mollie_redirect_url, mollie_payment_token } } } = orderData;
30
​
31
if (Boolean(mollie_payment_token)) {
32
// We'll need this token later, so let's save it to the browser's storage
33
setPaymentToken(mollie_payment_token);
34
} else {
35
// It is a good idea to "fail early" if some data you expect to be present
36
// is not there. Also, provide good error messages.
37
// That way, your code will be easier to debug if something goes wrong.
38
throw Error("Expected mollie_payment_token in order data, none found", orderData)
39
}
40
​
41
// We take the redirect URL we requested in the previous step and redirect to it
42
if (Boolean(mollie_redirect_url)) {
43
redirectToUrl(mollie_redirect_url)
44
} else {
45
throw Error("Expected mollie_redirect_url in order data, none found", orderData)
46
}
47
} catch (e) {
48
instance._handleError(e);
49
}
50
};
51
​
52
// Afain, we need to export the plugin configuration:
53
export default {
54
"Route/Checkout/Container": {
55
"member-function": {
56
savePaymentMethodAndPlaceOrder,
57
},
58
},
59
}
Copied!
As you might have noticed, we used a couple of custom utility functions, namely redirectToUrl and setPaymentToken. Of course we need to define them as well.
It's common for extensions to need new utility functions. They just need to implement them in the util directory, just like you would in a theme.
The redirectToUrl in Redirect.js is a really simple function that I found on StackOverflow (don't tell anyone). Still, it's nice to have it as a reusable function so the rest of the code is more readable.
util/Redirect.js
1
export const redirectToUrl = (url) => {
2
window.location.replace(url);
3
};
Copied!
The setPaymentToken and getPaymentToken functions (we haven't used the latter yet) are also very simple. They use the BrowserDatabase utility to save (and load) the payment token. This token will still be accessible after redirecting the user to the payment provider's page and back.
util/PaymentTokenPersistence.js
1
// Let's use Scandi's BrowserDatabase utility for persistence
2
import BrowserDatabase from 'Util/BrowserDatabase';
3
import { ONE_MONTH_IN_SECONDS } from 'Util/Request/QueryDispatcher';
4
​
5
const TOKEN_KEY = 'mollie_payment_token';
6
​
7
export const setPaymentToken = (token) => {
8
// Again, some error checking can help catch mistakes early.
9
if (!Boolean(token)) {
10
throw Error("Must specify token to set")
11
}
12
​
13
BrowserDatabase.setItem(token, TOKEN_KEY, ONE_MONTH_IN_SECONDS);
14
};
15
​
16
export const getPaymentToken = () => {
17
const token = BrowserDatabase.getItem(TOKEN_KEY);
18
​
19
if (!Boolean(token)) {
20
throw Error("No payment token found in browser database")
21
}
22
​
23
return token
24
};
Copied!
And with that, the redirection step is complete! If you wish, you can complete an order using Mollie's payment methods to verify that you are indeed redirected.
Last modified 2mo ago