Handling the Customer's Return
Handle the customer's return from a 3rd party site
After the customer has entered the payment details on the 3rd party page, they are returned to the e-commerce store. Often, there is additional logic required in this step. For example, you might have to fetch the transaction result to display it to the user.
In our case, we need to call the mollieProcessTransaction GraphQL mutation to make sure the transaction is processed, and to retrieve the order result (success/failure, etc.). Finally, we need to display this result to the user, in the form of a success or failure message.

Setting the Return URL

First, we need to ensure that the correct return URL is used. Since all Scandi checkout steps start with checkout, we're going to use checkout/mollie_result for the final order processing and displaying the result.
Mollie allows us to do this really easily by configuring some database values:
1
<?php
2
namespace ScandiTutorials\\MollieScandiConfig\\Setup;
3
​
4
use Magento\\Framework\\App\\Config\\ConfigResource\\ConfigInterface;
5
use Magento\\Framework\\Setup\\InstallDataInterface;
6
use Magento\\Framework\\Setup\\ModuleContextInterface;
7
use Magento\\Framework\\Setup\\ModuleDataSetupInterface;
8
use Mollie\\Payment\\Config;
9
​
10
class InstallData implements InstallDataInterface
11
{
12
/** @var ConfigInterface */
13
protected $config;
14
​
15
public function __construct(ConfigInterface $config) {
16
$this->config = $config;
17
}
18
​
19
public function install(
20
ModuleDataSetupInterface $setup, ModuleContextInterface $context
21
) {
22
$setup->startSetup();
23
$this->config->saveConfig(Config::GENERAL_USE_CUSTOM_REDIRECT_URL, true);
24
$this->config->saveConfig(
25
Config::GENERAL_CUSTOM_REDIRECT_URL,
26
'{{secure_base_url}}checkout/mollie_result?order_id={{increment_id}}&mollie_payment_token={{payment_token}}&mollie_order_hash={{order_hash}}'
27
);
28
$setup->endSetup();
29
}
30
}
Copied!
Now, we need to make sure that the correct business logic takes place after this redirect.

Processing the Order

When the user is redirected back, we need to use the mollieProcessTransaction GraphQL mutation to process the order and get the transaction result.
First, let's take a look at some relevant methods in the CheckoutContainer, which renders all checkout routes, and thus will be involved in checkout/mollie_result as well:
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
__construct(props) {plplu
9
super.__construct(props);
10
​
11
const {
12
toggleBreadcrumbs,
13
totals: {
14
is_virtual
15
}
16
} = props;
17
​
18
toggleBreadcrumbs(false);
19
​
20
this.state = {
21
isLoading: is_virtual,
22
isDeliveryOptionsLoading: false,
23
requestsSent: 0,
24
paymentMethods: [],
25
shippingMethods: [],
26
shippingAddress: {},
27
checkoutStep: is_virtual ? BILLING_STEP : SHIPPING_STEP,
28
orderID: '',
29
paymentTotals: BrowserDatabase.getItem(PAYMENT_TOTALS) || {},
30
email: '',
31
isGuestEmailSaved: false,
32
isCreateUser: false,
33
estimateAddress: {}
34
};
35
​
36
if (is_virtual) {
37
this._getPaymentMethods();
38
}
39
}
40
​
41
componentDidMount() {
42
const {
43
history,
44
showInfoNotification,
45
totals: {
46
items = []
47
}
48
} = this.props;
49
​
50
if (!items.length) {
51
showInfoNotification(__('Please add at least one product to cart!'));
52
history.push(appendWithStoreCode('/cart'));
53
}
54
}
55
​
56
// [...]
57
​
58
render() {...}
59
}
60
​
61
export default connect(mapStateToProps, mapDispatchToProps)(CheckoutContainer);
Copied!
We'll need to change the behavior of __construct, because otherwise it would cause problems by setting an incorrect initial state – such as BILLING_STEP or SHIPPING_STEP – but we actually want a custom MOLLIE_PROCESSING_STEP to be set.
For this, we can write a plugin. The function is very similar to the original one, but sets the correct initial step if applicable:
plugin/Checkout.component.plugin.js
1
// We'll define this later...
2
// MOLLIE_PROCESSING_STEP is a simple string that identifies the current checkout step
3
import { MOLLIE_PROCESSING_STEP } from './Checkout.component.plugin';
4
​
5
const __construct = (args, callback, instance) => {
6
const [props] = args;
7
const {
8
toggleBreadcrumbs,
9
} = props;
10
​
11
const { orderId, paymentToken, orderHash } = getParameters();
12
// This is how we determine that it's a Mollie return URL:
13
// The mollie_payment_token is specified
14
if (!paymentToken) {
15
// Not a return URL, just call the original function
16
return callback(...args)
17
}
18
// Otherwise, we make sure to *not* call the original function
19
// or else it would interfere with our logic
20
​
21
toggleBreadcrumbs(false);
22
​
23
instance.state = {
24
isLoading: false,
25
isDeliveryOptionsLoading: false,
26
requestsSent: 0,
27
paymentMethods: [],
28
shippingMethods: [],
29
shippingAddress: {},
30
checkoutStep: MOLLIE_PROCESSING_STEP, // Set a custom step
31
orderID: orderId,
32
paymentTotals: BrowserDatabase.getItem(PAYMENT_TOTALS) || {},
33
email: '',
34
isGuestEmailSaved: false,
35
isCreateUser: false,
36
estimateAddress: {},
37
mollieParameters: { orderId, paymentToken, orderHash },
38
mollie: { isLoading: true },
39
};
40
};
Copied!
We'll also plug into componentDidMount, since that's a good place to put business logic that needs to run once when the component is initialized. The original function has some logic that we want to suppress for the Mollie processing step, so we'll check before calling it.
plugin/Checkout.component.plugin.js
1
const componentDidMount = (args, callback, instance) => {
2
const { mollieParameters: { paymentToken: isMolliePayment } = {} } = instance.state;
3
​
4
// Check if it's a Mollie Payment return URL.
5
if (!isMolliePayment) {
6
// If not, just call the original function.
7
return callback(...args)
8
}
9
​
10
const paymentToken = getPaymentToken();
11
const processTransactionMutation = MollieQuery.getProcessTransactionMutation(paymentToken);
12
​
13
// Make the GraphQL mutation for processing the transaction
14
fetchMutation(processTransactionMutation).then(({ mollieProcessTransaction: { paymentStatus, cart } }) => {
15
instance.setState({
16
mollie: {
17
isLoading: false,
18
paymentStatus,
19
cart,
20
},
21
})
22
}).catch((e) => {
23
console.error(e);
24
instance.setState({
25
mollie: {
26
isLoading: false,
27
paymentStatus: ERROR,
28
cart: null,
29
},
30
})
31
})
32
};
Copied!
The above plugin makes use of the MollieQuery class. That's a query creator utility for mollieProcessTransaction which we also have to define:
query/Mollie.query.js
1
import { Field } from 'Util/Query';
2
​
3
/** @namespace Query/Mollie */
4
export class MollieQuery {
5
getProcessTransactionMutation(paymentToken) {
6
if (!paymentToken) {
7
throw Error("The payment_token is required")
8
}
9
​
10
return new Field('mollieProcessTransaction')
11
.addArgument('input', 'MollieProcessTransactionInput', { payment_token: paymentToken })
12
.addFieldList(['paymentStatus', this._getCartField()])
13
}
14
​
15
_getCartField() {
16
return new Field('cart').addField('id')
17
}
18
}
19
​
20
export default new MollieQuery()
Copied!
Finally, don't forget to update the .container plugin configuration:
1
export default {
2
"Route/Checkout/Container": {
3
"member-function": {
4
__construct,
5
componentDidMount,
6
savePaymentMethodAndPlaceOrder,
7
},
8
},
9
}
Copied!

Displaying the Result

After the order has been processed, we need to inform the user of the order status.
util/PaymentStatus.js
1
// This list was found in Mollie's backend code.
2
// We define the possible statuses so we can reuse them.
3
export const CREATED = 'CREATED';
4
export const PAID = 'PAID';
5
export const AUTHORIZED = 'AUTHORIZED';
6
export const CANCELED = 'CANCELED';
7
export const ERROR = 'ERROR';
8
​
9
export const ALL_SUCCESS = [CREATED, PAID, AUTHORIZED]
10
​
11
// Provides a human-readable, translated string describing the order status.
12
export const getStatusMessage = (status) => {
13
switch (status) {
14
case CREATED:
15
return __('Your order has been created.');
16
case PAID:
17
return __('Your order has been paid.');
18
case AUTHORIZED:
19
return __('Your order has been authorized.');
20
case CANCELED:
21
return __('Your order has been canceled.');
22
case ERROR:
23
return __('There was an error processing your order.')
24
}
25
};
Copied!
Now, we can add plugins for the Checkout .component, which is responsible for the presentation logic of the checkout flow.
1
import { ALL_SUCCESS, getStatusMessage } from '../util/PaymentStatus';
2
import CheckoutSuccess from 'Component/CheckoutSuccess';
3
import Loader from 'Component/Loader';
4
​
5
// A string representing the Mollie Processing Step
6
export const MOLLIE_PROCESSING_STEP = 'MOLLIE_PROCESSING_STEP';
7
​
8
function renderMollieStep() {
9
const { mollie: { isLoading, paymentStatus } = {}, orderID } = this.props;
10
​
11
// Display a loader while the order is processing
12
if (isLoading) {
13
return <Loader isLoading/>
14
}
15
​
16
// If the order was a success, render the CheckoutSuccess component
17
// It renders a "continue shopping" button and the order ID
18
if (ALL_SUCCESS.includes(paymentStatus)) {
19
return (
20
<CheckoutSuccess
21
orderID={ orderID }
22
/>
23
);
24
}
25
​
26
return false;
27
}
28
​
29
// We need to plug into the `stepMap` so we can configure it to handle our custom step
30
const stepMap = (member, instance) => ({
31
...member,
32
[MOLLIE_PROCESSING_STEP]: {
33
title: __('Loading'),
34
url: '/mollie_result',
35
render: renderMollieStep.bind(instance),
36
areTotalsVisible: false,
37
},
38
});
39
​
40
// We also customize the title
41
const renderTitle = (args, callback, instance) => {
42
const { checkoutStep, mollie: { isLoading, paymentStatus } = {} } = instance.props;
43
​
44
// Only handle our custom step; use the original function for everything else
45
if (checkoutStep !== MOLLIE_PROCESSING_STEP) {
46
return callback(...args);
47
}
48
​
49
if (isLoading) {
50
return (
51
<h2 block="Checkout" elem="Title">
52
{ __("Loading, please wait") }
53
</h2>
54
);
55
}
56
​
57
const message = getStatusMessage(paymentStatus);
58
​
59
return (
60
<h2 block="Checkout" elem="Title">
61
{ message }
62
</h2>
63
);
64
};
65
​
66
// Plugin configuration as always.
67
export default {
68
'Route/Checkout/Component': {
69
'member-property': {
70
stepMap,
71
},
72
'member-function': {
73
renderTitle,
74
},
75
},
76
}
Copied!

Conclusion

At this point, we've covered the main steps in integrating a payment method extension in Scandi. Usually, you need to do some debugging to make sure everything is working properly – payment integration can be tricky! You should be able to test your extension using the test mode of the payment provider.
When you're done with the extension, consider publishing it on the ScandiPWA Marketplace so others can benefit from your creation!
Last modified 2mo ago