Checkout Browser SDK
Checkout Browser SDK lets you integrate Checkout both on regular websites and JavaScript web applications, either implemented in libraries or frameworks like React, Vue, or Angular.
With the Checkout Browser SDK, you can integrate Checkout either as a browser script or as an npm module.
You can initialize Checkout in two ways depending on the Checkout mode you use:
- For the Complete Checkout mode, call the
checkoutFlow
method. - For the Payment Only mode, call the
paymentFlow
method.
Except for specific cases, the following code samples use the npm module and the checkoutFlow
method.
Versioning
The versioning of the Checkout Browser SDK is handled through npm and follows the principles of semantic versioning. For information about the available versions of the Checkout Browser SDK, see this page.
Configuration properties
Following are the configuration properties that you can provide with the checkoutFlow
or paymentFlow
methods.
In the documentation, we use placeholders for the property values (for example, {projectKey}
). Replace placeholders with actual values.
Property | Value | Required | Description |
---|---|---|---|
projectKey | {projectKey} | Yes | The identifier of your Checkout entity and the project_key of your Project. |
sessionId | {sessionId} | Yes | The identifier of the Checkout Session. |
region | {region} | Yes | The Region where your Checkout application is hosted. For example, europe-west1.gcp . |
locale | {locale} | No (default: en ) | Your customer’s locale. If the provided locale is not found, English will be used. |
onInfo | function | No | See onInfo, onWarn, and onError |
onWarn | function | No | See onInfo, onWarn, and onError |
onError | function | No | See onInfo, onWarn, and onError |
logInfo | true /false | No (default: false ) | See logInfo, logWarn, and logError |
logWarn | true /false | No (default: false ) | See logInfo, logWarn, and logError |
logError | true /false | No (default: false ) | See logInfo, logWarn, and logError |
styles | {styles} | No | An object containing CSS variables to customize the style of Checkout. |
languageOverrides | {languageOverrides} | No | An object containing properties to customize the texts and labels of Checkout. |
forms | {forms} | No | An object containing properties to customize the address form fields of Checkout. It only applies to the checkoutFlow method. |
showTaxes | {showTaxes} | No | If set to true , tax information from Composable Commerce is displayed in the price summary of your checkout page. It only applies to the checkoutFlow method. |
currencyLocale | {currencyLocale} | No | The locale to set the currency formatting for prices. When it is not set, locale determines the price formatting as a default. If set, the locale for price formatting is overridden. For example, if locale is set to fr , Swiss prices are displayed as 10,00 CHF. If currencyLocale is set to de-CH , prices are displayed as CHF 10.00. |
Browser script
To integrate Checkout as a browser script, add the following code between the opening and closing <head>
tags of each page on which you want to activate the start of the checkout process.
When integrating Checkout as a browser script, @latest
serves as an alias to load the latest version of the SDK.
<script>(function (w, d, s) {if (w.ctc) {return;}var js,fjs = d.getElementsByTagName(s)[0];var q = [];w.ctc =w.ctc ||function () {q.push(arguments);};w.ctc.q = q;js = d.createElement(s);js.type = 'text/javascript';js.async = true;js.src ='https://unpkg.com/@commercetools/checkout-browser-sdk@latest/browser/sdk.js';fjs.parentNode.insertBefore(js, fjs);})(window, document, 'script');ctc('checkoutFlow', {projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',logInfo: true, // Recommended for debugging during development.logWarn: true, // Recommended for debugging during development.logError: true, // Recommended for debugging during development.});</script>
We recommend subscribing to the info
, warn
, and error
Messages for debugging purposes during development. For further information, see Message subscription and logging.
npm module
Prerequisites
- Node v12.22.7 (or later)
- Either npm v6 (or later) or yarn v1.22.17 (or later)
Install the SDK package
To install the SDK package, run one of the following commands:
npm install @commercetools/checkout-browser-sdk
yarn add @commercetools/checkout-browser-sdk
npm script
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',logInfo: true, // Recommended for debugging during development.logWarn: true, // Recommended for debugging during development.logError: true, // Recommended for debugging during development.});
We recommend subscribing to the info
, warn
, and error
Messages for debugging purposes during development. For further information, see Message subscription and logging.
checkoutFlow method
When using the Complete Checkout mode, use the checkoutFlow
method to initialize the full checkout process with the related configuration.
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',locale: `{locale}`,logInfo: true,logWarn: true,logError: true,... // Other configuration properties.});
When calling the checkoutFlow
method, the Checkout UI component for the specified sessionId
opens. If the customer quits the checkout process before completing it but the Checkout Session is still valid, you can call the method again with the same sessionId
. If the session has expired, you can refresh it and open the component again by getting a new sessionId
.
By default, when calling the checkoutFlow
method, the component appears full screen in an absolutely positioned <div>
element that hides other content on your page. The component renders a header with your preconfigured logo, the input fields, and the Leave checkout button. By clicking the Leave checkout button, the component disappears and the content of your page becomes visible again.
Alternatively, you can display the component inline with your content by using a <div>
or <span>
element with the data-ctc
attribute in it (for example, <div data-ctc />
). By doing so, the header and the Leave checkout button do not appear, and you can render any other content around the component, such as a custom header or footer.
paymentFlow method BETA
When using the Payment Only mode, use the paymentFlow
method to initialize the payment process.
import { paymentFlow } from '@commercetools/checkout-browser-sdk';paymentFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',locale: `{locale}`,logInfo: true,logWarn: true,logError: true,... // Other configuration properties.});
When calling the paymentFlow
method, the Payment UI component for the specified sessionId
opens, displaying the cart amount at that point in time. If the amount changes after calling the method but the Checkout Session is still valid, you can update it by calling the method again with the same sessionId
. If the session has expired, you can refresh it and open the component again by getting a new sessionId
.
By default, when calling the paymentFlow
method, the component appears full screen in an absolutely positioned <div>
element that hides other content on your page. It is your responsibility to implement a way to close it and show the content on the page.
Alternatively, you can display the component inline with your content by using a <div>
or <span>
element with the data-ctc
attribute in it (for example, <div data-ctc />
). By doing so, you can render other content around the component, such as the shipping and billing address forms.
paymentFlow method in multi-step checkouts
If your checkout process consists of multiple steps that your customers must complete, you can use the paymentFlow
method to render the Payment UI component on a specific step of the process.
Payment as the last step
The easiest way to add the Payment UI component to your checkout process is to render it as the last step of the process.
You can call the paymentFlow
method after the customer has entered other checkout information. The Payment UI component will display the list of available payment methods and a payment button.
You can display a custom payment button or require the customer to accept the terms and conditions before proceeding with the payment.
Payment as intermediate step
You can render the Payment UI component as an intermediate step of your checkout process, for example, to display an order review step before the payment.
To do so, you must provide an HTML element with a data-ctc-selector="confirmMethod"
attribute in it, together with a custom payment button, which must be deactivated or hidden.
When the customer clicks the element to select the payment method, a Payment Method Selection Confirmation Message generates and the Payment UI component displays a summary of the payment and the selected payment method, but the payment process will not be triggered. Therefore, to let the customer proceed to the payment, you must react to the Message by activating or displaying the custom payment button.
At this stage, the customer can edit the information entered in the previous steps or proceed to the payment. If the user selects a different payment method or if the payment amount changes, you must call the paymentFlow
method again with the same sessionId
.
You can also require the customer to accept the terms and conditions before proceeding with the payment.
After calling the paymentFlow
method, it is not possible to navigate to a different page, except for single-page applications (SPAs) using React Router, Angular routing, Vue Router, or similar, which allow navigation without page reloading. In such case, do not unmount the Payment UI component when navigating to a different page, as this will interrupt the payment process.
Accept terms and conditions before payment
When using the paymentFlow
method, you can request the customer to accept terms and conditions before proceeding with the payment. To do so, you must provide an HTML element with a data-ctc-selector="termsAndConditionsPending"
attribute in it until the customer accepts the required terms and conditions.
An External Terms And Conditions Pending Message generates if the customer tries to proceed with the payment while the element is present.
{areTermsAndConditionsPending ? (<span data-ctc-selector="termsAndConditionsPending" />) : null;}
React to Messages
When using the paymentFlow
method, it is important to react to the Messages generated by Checkout to provide feedback to customers and handle different scenarios that may occur during the payment process.
Following is an example with some Messages that you should consider reacting to.
It is your responsibility to react to a payment_failed
Message and give feedback to the customer about the failure. To allow the customer to retry the payment, while also ensuring the cart has the latest version and correct total amount, call the paymentFlow
method with the same sessionId
again.
import { paymentFlow } from '@commercetools/checkout-browser-sdk';paymentFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',locale: `{locale}`,logInfo: true,logWarn: true,logError: true,onError: (error) => {switch (error.code) {case 'payment_method_loading_error':// Store the number of failed payment methods on the local state.// If the number of failed payment methods is equal to the total number of payment methods, display a generic error message.break;case 'payment_failed':// Show a payment failed message to the customer.// Call paymentFlow method again to restart the payment flow.break;}},onInfo: (message) => {switch (message.code) {case 'checkout_completed':const {order: { id },} = message.payload as {order: { id: string };};// Redirect to confirmation page with Order ID.break;case 'payment_method_selection_confirmation_failed':// Show message to customer and allow user to try again.break;case 'payment_method_selection_confirmation': {const {method: { hasVendorButton, type },} = message.payload as {method: { type: string; hasVendorButton: boolean };};// Hide custom payment button if hasVendorButton is 'true'.break;}case 'payment_methods_received': {const { paymentMethods } = message.payload as { paymentMethods: string[] };// Store total number of payment methods on local state.break;}case 'payment_method_loaded':// Increment loaded payment methods.break;case 'payment_started':// Show blocking overlay with spinner to avoid user interaction with the page.// Initialize local state errors to 'false'.break;case 'payment_completed':// Hide blocking overlay.break;case 'payment_method_selected':const {method: { hasVendorButton, type },} = message.payload as {method: { type: string; hasVendorButton: boolean };};// Store selected payment method on local state and remove local payment error state.break;case 'payment_cancelled':// Hide blocking overlay.break;case 'external_terms_and_conditions_pending':// Show message to the customer to accept terms and conditions.break;}},});
close method
Use the close
method to close the Checkout or the Payment UI component when it is not needed. Calling the close
method is recommended over unmounting the component, as it ensures that the necessary cleanup is performed.
An example of use is a single-page application (SPA) implementing a multi-step checkout process with the paymentFlow
method, where the customer decides to edit the information entered in a previous step. In such cases, you can use the close
method to close the payment UI component.
Once the customer moves the payment step again, you can call the paymentFlow
method with the same sessionId
to render the Payment UI component again.
Another example of a use case is to implement a custom button to leave the checkout when using the checkoutFlow
method.
import { close } from '@commercetools/checkout-browser-sdk';close();
Return URL
Some payment methods may require a redirection from your website to one of the payment service providers (PSPs) to get information about the customer. In such cases, when you install a payment Connector, you must set a return URL to take the customer back to your website after the information has been retrieved. We recommend using the same URL as the one where the checkout process started; however, this is not mandatory.
You can set only one return URL per payment Connector. If you want to use the same payment Connector with multiple domains, you must create different Applications in the Merchant Center and override the return URL.
When information has been retrieved, the paymentReference
parameter is added to the return URL with the id
of the Payment as its value, and the customer returns to your website. Now, you must call the checkoutFlow
or paymentFlow
method again by providing the same configuration parameters as before along with the paymentReference
.
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({region: '{region}',projectKey: '{projectKey}',sessionId: '{sessionId}',locale: '{locale}',logInfo: true,logWarn: true,logError: true,paymentReference: '{paymentReference}',});
When calling the checkoutFlow
or paymentFlow
method again, the UI component appears and displays a loading status while the payment is verified. If the payment is successful, the checkout process is complete. Otherwise, the customer is prompted to either quit the checkout process or try again by editing the entered information.
Checkout completion
Once the customer completes the checkout process successfully, the SDK closes the Checkout or the payment UI component and the Checkout Completed Message generates. After this happens, you can determine how the checkout process should continue by reacting to the Message, both when using the checkoutFlow
and the paymentFlow
method.
For example, you can react to the Message to display feedback for the customer on your website, such as a message or a dialog. Or, you can use the Message to redirect the customer to a different page, such as a Thank You page.
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',onInfo: (message) => {if (message.code === 'checkout_completed') {const {order: { id },} = message.payload as {order: { id: string };};window.location.href = '/thank-you?orderId=' + id;}},});
Message subscription and logging
The Messages from Checkout can be of three severity levels: info
, warn
, or error
.
You can handle Messages by using:
onInfo, onWarn, and onError
You can subscribe to the info
, warn
, or error
Messages by passing the optional onInfo
, onWarn
, or onError
message handlers with the checkoutFlow
or paymentFlow
methods. The handlers will receive the Message as a parameter.
In the following examples, we subscribe to all info
Messages and log a Received
note followed by the Message code on the browser's developer console.
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',onInfo: (message) => {console.error('Received: ' + message.code);},});
<script>(function (w, d, s) {if (w.ctc) {return;}var js,fjs = d.getElementsByTagName(s)[0];var q = [];w.ctc =w.ctc ||function () {q.push(arguments);};w.ctc.q = q;js = d.createElement(s);js.type = 'text/javascript';js.async = true;js.src ='https://unpkg.com/@commercetools/checkout-browser-sdk@latest/browser/sdk.js';fjs.parentNode.insertBefore(js, fjs);})(window, document, 'script');ctc('checkoutFlow', {projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',onInfo: function (message) {console.error('Received: ' + message.code);},});</script>
logInfo, logWarn, and logError
You can use the logInfo
, logWarn
, and logError
methods to log Messages in the console for debugging purposes. We recommend not activating them in production since, usually, these logs are not useful for end users.
In the following examples, we log all the info
and error
Messages, but not the warn
ones.
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';checkoutFlow({projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',logInfo: true,logWarn: false,logError: true,});
<script>(function (w, d, s) {if (w.ctc) {return;}var js,fjs = d.getElementsByTagName(s)[0];var q = [];w.ctc =w.ctc ||function () {q.push(arguments);};w.ctc.q = q;js = d.createElement(s);js.type = 'text/javascript';js.async = true;js.src ='https://unpkg.com/@commercetools/checkout-browser-sdk@latest/browser/sdk.js';fjs.parentNode.insertBefore(js, fjs);})(window, document, 'script');ctc('checkoutFlow', {projectKey: '{projectKey}',region: '{region}',sessionId: '{sessionId}',logInfo: true,logWarn: false,logError: true,});</script>