Callbacks
In the Checkout SDK, callback functions play a vital role in providing real-time updates on the status of payment transactions. Callbacks enhance the user experience by enabling seamless and efficient handling of various payment scenarios, such as errors, successful payments, and cancellations.
Please note that due to technical constraints associated with off-site redirection during the payment process, the successCallback and cancelCallback functions are only called for on-site checkouts. However, the errorCallback function is called for any kind of payments. On-site checkouts include options such as Apple Pay, Google Pay, payments with saved cards, and on-site card form transactions, which support callback functionality for a seamless user experience.
The errorCallback is a callback function that is invoked when issues arise during a payment. It is important to handle errors appropriately to ensure a smooth user experience. The recommended best practice in case of an error is to restart the checkout process by creating a new session_id using the Checkout API.
To define the errorCallback function, you can use the data-error attribute on the Checkout script tag to specify a global function that will handle errors. If an error occurs during a payment, the errorCallback function will be invoked with a data object with a data.status value of error
Params Available in Data Object for errorCallback
messagerequiredform_of_paymentrequiredstatusrequiredchallenge_occurredsession_idorder_noreference_number
Here's an example of how errorCallback might be defined
window.errorCallback = function(data) {
// If the payment fails with the status "error," the SDK
// triggers the errorCallback. In errorCallback, we show an
// error popup by checking if form_of_payment in data is
// "token_pay" or "redirect".
const validFormsOfPayments = ['token_pay', 'redirect'];
if (validFormsOfPayments.includes(data.form_of_payment) ||
data.challenge_occurred) {
const message = "Oops, something went wrong. Refresh the page and try again.";
// Displays a popup with data.message if present; else, it displays a static message.
window.Checkout.showPopup("error", data.message || message);
}
console.log('Error callback', data);
}In this example, the errorCallback function is defined and passed as the value of the data-error attribute on the Checkout script tag. If an error occurs during a payment, the function will be invoked with a data object. This function will handle error as need and show error modal using Checkout.showPopup().
The cancelCallback in the Checkout SDK is a callback function that is invoked when a payment is canceled. To define the cancelCallback function, you can use the data-cancel attribute on the Checkout script tag to specify a global function that will handle cancellations. If a customer cancels a payment, the cancelCallback function will be invoked with a data object.with a data.status value of "canceled”
Params Available in Data Object for cancelCallback
messageform_of_paymentchallenge_occurredsession_idstatusorder_noreference_numberpayment_gateway_info
Here's an example of how cancelCallback might be defined
window.cancelCallback = function(data) {
// If the payment fails with the status "canceled," the SDK triggers the cancelCallback.
// In cancelCallback, we show an error popup by checking if pg_name in data.payment_gateway_info is "kpay"
// or if data.form_of_payment is "token_pay".
if (data.payment_gateway_info && data.payment_gateway_info.pg_name === "kpay") {
// Displays a popup with pg_response as key-value pairs.
window.Checkout.showPopup("error", " ", data.payment_gateway_info.pg_response);
} else if (data.form_of_payment === "token_pay" || data.challenge_occurred) {
const message = "Oops, something went wrong. Refresh the page and try again.";
// Displays a popup with data.message if present; else, it displays a static message.
window.Checkout.showPopup("error", data.message || message);
} else if (data.redirect_url && data.status.toLowerCase() === "canceled") {
// If the cancellation is successful and the status is 'canceled',
// the customer will be redirected to the transaction details page.
window.location.href = data.redirect_url;
}
console.log("Cancel callback", data);
};In this example, the cancelCallback function is defined and passed as the value of the data-cancel attribute on the Checkout script tag. If a customer cancels a payment, the function will be invoked with a data object containing information about the cancelled transaction. This function will handle cancellation as needed and show error modal using Checkout.showPopup(). or redirect user to transaction details page with status as cancelled.
In the Checkout SDK, the successCallback is a function triggered upon successful completion of the payment process. This callback receives a data object,with a data.status value of success
Params Available in Data Object for successCallback
messageform_of_paymentchallenge_occurredsession_idstatusorder_noreference_numberredirect_urlpayment_gateway_info
The successCallback function is defined and passed as the value of the data-success attribute on the Checkout script tag. If the payment process completes successfully, the function will be invoked with a data object containing information about the completed transaction. The function will then redirect the customer to the specified redirect_url using window.location.href.
Here's an example of how successCallback might be defined
window.successCallback = function(data) {
// If payment gets completed with status "success," SDK triggers the successCallback.
// In successCallback, we redirect the user to data.redirect_url.
window.location.href = data.redirect_url;
}To ensure the integrity of your transactions, the Checkout SDK provides a beforePayment hook that allows you to take necessary precautions before the payment process starts. It's crucial for e-commerce platforms to implement this feature, especially when considering multi-tab operations by users.
How to Implement
Initialize the Hook
When initializing the SDK, you can set up the
beforePaymenthook which will trigger when the payment process starts.. This hook should return a Promise. If the Promise is resolved, the user may continue with the payment process. However, if the Promise is rejected, the payment process will be halted, and an error message will appear in the browser console.For wallet payments such as
ApplePay,GooglePay, andSTCPay, the respective payment sheet will be presented. As soon as the payment process begins, the SDK will invoke thebeforePaymenthook.For other payment methods, including redirect,
ottuPG, andtokenPay, thebeforePaymenthook is triggered when thePaybutton is clicked
Params Available in Data Object for beforePayment
redirect_url
window.beforePayment = function(data) {
return new Promise(function(resolve, reject) {
fetch('https://api.yourdomain.com/basket/freeze', {
method: 'POST'
})
.then(function(response) {
if (response.ok) {
if (data && data.redirect_url) {
window.Checkout.showPopup(
'redirect',
data.message || 'Redirecting to the payment page',
null
);
}
resolve(true);
}
else reject(new Error('Failed to freeze the basket.'));
})
.catch(reject);
});
};
Update API URLs for Payment Flow
The URLs in the fetch calls for both the freeze (https://api.yourdomain.com/basket/freeze) and unfreeze (https://api.yourdomain.com/basket/unfreeze) actions must be updated to point to your specific API URL.
If these URLs are not updated, console errors will appear. To avoid any errors in the console, ensure that these URLs are correctly updated.
Handle Payment Outcomes
Success: Direct users to the payment success page.
Cancel/Error: It's essential to unfreeze the cart to allow the user to make changes and retry the payment. Use the
cancelCallbackanderrorCallbackprovided by the SDK to handle these cases.
Best Practices
Always freeze cart updates during ongoing payment processes. This ensures users can't manipulate cart contents in parallel with a transaction, preserving transaction integrity.
Ensure that the cart is unfrozen in cases of payment cancellations or errors. This improves user experience, allowing them to adjust their cart if needed.
The validatePayment hook is a pre-validation step in the Checkout SDK Web, ensuring that all required payer information (e.g., terms acceptance, additional user inputs) is collected and valid before proceeding with payment.
Key Features
Hook is called before payment initiation.
Runs before every payment method (Apple Pay, Google Pay, Redirects, Tokenization, etc.)
Prevents incomplete payments by validating payer-provided data.
Returns a Promise to control the flow:
Resolves → Payment proceeds.
Rejects → Payment submission is blocked.
No form of payment can proceed without passing validation.
Implementation
The validatePayment hook must be defined as a global function that returns a Promise.
Example: Validating Terms Acceptance
window.validatePayment = function() {
return new Promise((resolve, reject) => {
// Custom validations to ensure required fields are valid for payment to proceed.
const termsAccepted = document.getElementById("termsCheckbox").checked;
if (termsAccepted) {
resolve(true); // Proceed with payment
} else {
alert("Please accept the terms and conditions before proceeding.");
reject(new Error("Terms not accepted")); // Block payment
}
});
};How to Enable It in Checkout SDK
To enable validatePayment, include it in the SDK script tag:
<script
src="https://assets.ottu.net/checkout/v3/checkout.min.js"
data-validatepayment="validatePayment"
></script>How It Works
User initiates payment (clicks “Pay”).
validatePayment is triggered before any payment request.
If validation fails, the payment process stops, preventing submission.
If validation succeeds, the payment method proceeds normally.
Payment is completed or redirected.

Use Cases
Ensuring Terms & Conditions Acceptance Require users to accept terms before making a payment.
Verifying User Input Ensure additional fields (e.g., phone number, promo code) are correctly filled.
Checking Cart Consistency Verify that items in the cart haven’t changed before processing payment.
Blocking Suspicious Activity Prevent payments from going through if unusual behavior is detected.
Comparison with beforePayment Hook
Blocks incomplete payments
Yes
No
Allows verification that the required fields are valid
Yes
No
Runs before Apple Pay, Google Pay, Tokenization
Yes
Yes
Runs before Redirects
Yes
Yes
Best Practices for Implementation
Use clear error messages to guide users if validation fails.
Ensure the hook runs quickly to avoid checkout delays.
Combine with UI updates (e.g., disable the “Pay” button until valid).
Test across different payment methods to confirm expected behavior.
Full Example: Terms + Phone Number Validation
window.validatePayment = function() {
return new Promise((resolve, reject) => {
const termsAccepted = document.getElementById("termsCheckbox").checked;
const phoneNumber = document.getElementById("phoneInput").value;
if (!termsAccepted) {
alert("Please accept the terms and conditions.");
return reject(new Error("Terms not accepted"));
}
if (!phoneNumber || phoneNumber.length < 10) {
alert("Please enter a valid phone number.");
return reject(new Error("Invalid phone number"));
}
resolve(true); // Proceed with payment
});
};The data object received by the errorCallback, cancelCallback and successCallback contains information related to the payment transaction, such as the status of the payment process, the session_id generated for the transaction, any error message associated with the payment, and more. This information can be used to handle the payment process and take appropriate actions based on the status of the transaction.
Data Object Child Parameters
- message
stringIt is a string message that can be displayed to the customer. It provides a customer-friendly message regarding the status of the payment transaction.
- session_id
stringIt is a unique identifier generated when a payment transaction is created. It is used to associate a payment transaction with the checkout process. You can find the
session_idin the response of the Checkout API's session_id endpoint. This parameter is required to initialize the Checkout SDK. - status
stringIt is of the checkout process. Possible values are:
success: The customer was charged successfully, and they can be redirected to a success page or display a success message.canceled: The payment was either canceled by the customer or rejected by the payment gateway for some reason. When a payment is canceled, it's typically not necessary to create a new payment transaction, and the same session_id can be reused to initiate the Checkout SDK and allow the customer to try again. By reusing the same session_id, the customer can resume the checkout process without having to re-enter their payment information or start over from the beginning.error: An error occurred during the payment process, This can happen for a variety of reasons, such as a network failure or a problem with the payment gateway's system. The recommended action is to create a new payment transaction using the Checkout API and restart the checkout process.
- redirect_url
URLThe URL where the customer will be redirected after the payment stage only if the webhook URL returns a success status. order_no, reference_number and session_id will be appended to the redirect URL as query parameters. The developer implementing the SDK must ensure that the redirection process is smooth and secure, providing a seamless experience for the customer while maintaining the integrity of the payment process.
It's important to note that while the redirect_url option is typically present only in the successCallback, there are specific cases where it may exist in failure scenarios.
For example, in the event of an MPGS cancel or if the transaction includes a webhook URL alongside a redirect URL, users may be redirected after cancellation, which is communicated to the webhook. Therefore, the presence of redirect_url in such cases is possible.
- order_no
stringThe order number provided in the Checkout API. See Checkout API & order_no.
- reference_number
stringA unique identifier associated with the payment process. It is sent to the payment gateway as a unique reference and can be used for reconciliation purposes.
- form_of_payment
stringEnum:
apple_pay,google_pay,token_pay,stc_pay,redirectIndicates the form of payment used to process the transaction. This can be one of several options, including
apple_pay,google_pay,token_pay,stc_pay, orredirect. It's important to note that the redirect option is only present in theerrorCallback. In other scenarios, especially withcancelCallbackandsuccessCallback, it's absent. This is because, in the redirect flow, the customer is redirected to a different page where actions like payment cancellation or confirmation occur, not on the page where the SDK is displayed.apple_pay- Apple Paygoogle_pay- Google Paytoken_pay- Token Paystc_pay- stc payredirect- Redirect
- payment_gateway_info
objectInformation about the payment gateway, accompanied by the response received from the payment gateway
- pg_code
stringThe unique identifier, or
pg_code, for the payment gateway that was used to process the payment. This value corresponds to the specific payment method utilized by the customer, such ascredit-card. - pg_name
stringThe name of the payment gateway, represented in all lowercase letters, that was used to perform the payment. This could be one of several values, such as
kpay(for KNET),mpgs, orcybersource. These identifiers provide a human-readable way to understand the payment mechanism that was utilized. - pg_response
objectThe raw response data that was received directly from the payment gateway after the transaction attempt. This typically includes transaction status, transaction identifier, and potentially error messages or additional data provided by the gateway.
- challenge_occurred
boolDefault: false This flag indicates if an additional verification, such as 3DS, OTP, PIN, etc., was initiated during the payment process. Use this flag in
cancelCallbackanderrorCallbackto control the presentation of error messages, especially for on-site payments undergoing a challenge flow. For example, after a failed 3DS verification, it's useful to show a custom popup informing the user of the payment failure. However, it's crucial to note that not all on-site failed payments need custom error messaging. In cases likeGooglePayorApplePay, error messages are inherently handled by the Payment Sheet, which remains open for the user to retry, making this distinction vital.
Last updated