Build with the Checkout SDK

Learn how to initialize and customize Checkout.

Ask about this Page
Copy for LLM
View as Markdown

After completing this page, you should be able to:

  • Identify customization possibilities by referring to the Checkout documentation.

The Checkout Browser SDK provides the tools to integrate the Checkout functionality into regular websites and JavaScript web applications. You can implement either a complete checkout flow or a payment-only mode, depending on your requirements.

Prerequisites

Before integrating the Checkout Browser SDK, make sure that you have set up the following items:

Create a Checkout Session

A Checkout Session securely stores the permissions and configuration that are required to initialize Checkout. This separation between frontend and backend ensures security by keeping sensitive session creation logic on your server.

Create the Checkout Session from your BFF by calling the Sessions API with the Cart id and the Checkout Application id or key. Use the API Client with the manage_sessions scope for this operation.
Create a Checkout Session from your BFFts
import fetch from "node-fetch";

async function createSession(
   region: string,
   projectKey: string,
   token: string,
   cartId: string,
   applicationKey: string,
   futureOrderNumber?: string
) {
  const url = `https://session.${region}.commercetools.com/${projectKey}/sessions`;

  const body = {
    cart: {
      cartRef: {
        id: cartId,
      },
    },
    metadata: {
      applicationKey: applicationKey,
      ...(futureOrderNumber && { futureOrderNumber }), // Optional: Set a custom Order number in your Checkout Session to let you track and manage your Orders across all platforms and payment service providers. This number is then stored as the `orderNumber` in the Composable Commerce `Order` entity.
    },
  };

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      throw new Error(`Request failed: ${response.status} ${response.statusText}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error creating session:", error);
    throw error;
  }
}

// Example usage
try {
  const checkoutSession = await createSession("eu-west-1", "my-project", "my-token", "cart-123", "app-456");
} catch (e) {
  // TODO
}

Verify Cart ownership before creating a Checkout Session to prevent Insecure Direct Object Reference (IDOR) vulnerabilities. Fetch the Cart, and then compare its customerId or anonymousId to the authenticated user making the request.

Your BFF or backend must always verify that the Cart belongs to the user who triggered the action.

A successful response returns a Checkout Session object:

Checkout Session responsejson
{
  "id": "537ec3b7-01f5-47b6-8a5c-3974a8bc4812",
  "expiryAt": "2024-03-13T10:20:45.661Z",
  "lastModifiedAt": "2024-03-13T09:20:45.661Z",
  "createdAt": "2024-03-13T09:20:45.661Z",
  "metadata": {
    "applicationKey": "{applicationKey}",
  },
  "activeCart": {
    "cartRef": {
      "id": "{cartId}"
    }
  },
  "state": "ACTIVE"
}

You must use the id property (that's returned in the response) as the value of the sessionId property in the checkoutFlow and paymentFlow methods. You need to call these methods from your frontend by using the Checkout Browser SDK.

Initialize the Checkout Browser SDK

You can integrate the Checkout Browser SDK either as a browser script or as an npm module. Choose the integration method that best fits your application architecture.

Choose your checkout mode

Select the initialization method based on your checkout requirements:

  • Complete Checkout mode: call the checkoutFlow method to handle the entire checkout process including shipping and payment.
  • Payment Only mode: call the paymentFlow method when you manage shipping and customer details separately.
Both methods accept configuration properties for customization including log levels, event handlers (onInfo, onWarn, onError), CSS styling, text labels, and address form fields.
When initializing Checkout, you can manage checkout events by passing onInfo, onWarn, or onError message handlers. The SDK sends Messages about errors, completion, and other checkout events.
Use these messages to manage user experience and create analytics events for your tracking tools. Review all available Message types to understand the full range of events.

Integrate as a browser script

Add the following code between the <head> tags on each page where you want to enable checkout:
Browser script integrationjavascript

<!DOCTYPE html>
<html>
 <head>
   <title>Checkout Example</title>
    <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');
     </script>
 </head>
 <body>
    <h1>Checkout Example</h1>
    <!-- Optional: If not specified, the Checkout UI will appear full screen in an absolute positioned <div> element that hides other content on the page. This element can also be a <span> -->
    <div data-ctc></div>
 </body>
</html>

Call the checkoutFlow or paymentFlow method to initialize checkout with your configuration.
Initialize Complete Checkout modejavascript
<script>
  ctc('checkoutFlow', {
    projectKey: '{projectKey}',
    region: '{region}',
    sessionId: '{sessionId}',
    locale: 'en',
    logInfo: true, // Recommended for debugging during development.
    logWarn: true, // Recommended for debugging during development.
    logError: true, // Recommended for debugging during development.
  });
</script>

Initialize Payment Only modejavascript
<script>
  ctc('paymentFlow', {
    projectKey: '{projectKey}',
    region: '{region}',
    sessionId: '{sessionId}',
    locale: 'en',
    logInfo: true, // Recommended for debugging during development.
    logWarn: true, // Recommended for debugging during development.
    logError: true, // Recommended for debugging during development.
  });
</script>

Integrate as an npm module

Make sure that your development environment meets the following requirements:

  • Node v12.22.7 or later
  • npm v6 or later or yarn v1.22.17 or later

To install the SDK, run the following command:

Install the Checkout Browser SDKbash
npm install @commercetools/checkout-browser-sdk
To initialize checkout with your configuration, call either the checkoutFlow or paymentFlow method:
Initialize Complete Checkout mode with npmts
import { checkoutFlow } from '@commercetools/checkout-browser-sdk';

checkoutFlow({
  projectKey: '{projectKey}',
  region: '{region}',
  sessionId: '{sessionId}',
  locale: '{locale}',
  logInfo: true, // Recommended for debugging during development.
  logWarn: true, // Recommended for debugging during development.
  logError: true, // Recommended for debugging during development.
  // Other configuration properties.
});

Initialize Payment Only mode with npmts
import { paymentFlow } from '@commercetools/checkout-browser-sdk';

paymentFlow({
  projectKey: '{projectKey}',
  region: '{region}',
  sessionId: '{sessionId}',
  locale: '{locale}',
  logInfo: true, // Recommended for debugging during development.
  logWarn: true, // Recommended for debugging during development.
  logError: true, // Recommended for debugging during development.
  // Other configuration properties.
});

The Checkout SDK must be loaded from a domain with HTTPS enabled to support cross-origin resource sharing (CORS). Add your public HTTPS URL to the origin URLs in your Checkout Application configuration.

Development options:

You can use any of the following approaches during development/testing:

  • Add http://localhost with a port number (for example, http://localhost:3000) to the origin URLs for faster iteration. Remove this URL before copying your Checkout configuration to production.
  • Use tunneling tools like Ngrok or Pinggy to create a public HTTPS URL that forwards to your localhost.
  • Use publicly accessible services like JSFiddle by adding https://jsfiddle.net and https://fiddle.jshell.net to your allowed origin URLs.

Display the Checkout UI

After you call either the checkoutFlow or paymentFlow method, the Checkout UI renders on your page. Choose any one of the following two display modes:
Inline mode: add a <div> or <span> element with the data-ctc Attribute to embed Checkout within your content. This mode doesn't display either the header or Leave checkout button, letting you render custom headers or footers around the component.
Full-screen mode: when no element with the data-ctc Attribute exists, Checkout displays in an absolute positioned <div> that overlays your page content. This mode includes a header with your configured logo and a Leave checkout button.
Complete Checkout mode UI
Checkout UI displaying the shipping address form with fields for customer information including name, email, country selector, street address, ZIP code, city, and phone number. A summary panel on the right shows the cart item and total.
Payment Only mode UI
Payment Only UI displaying the payment method selection embedded within a custom checkout flow.

Use Payment Only mode only as the final step in your checkout process. This mode creates the Payment and Order, so all other checkout information must be collected beforehand.

Key takeaways

  • The Checkout Browser SDK requires only a valid Checkout Session ID, which your BFF obtains using an API Client with the manage_sessions scope.
  • Create Checkout Sessions from your BFF by using the Sessions API to maintain security and prevent unauthorized access to Carts.
  • Initialize Checkout by using either checkoutFlow() for complete checkout or paymentFlow() for payment-only mode, depending on your requirements.
  • Integrate the SDK as either a browser script or npm module based on your application architecture.
  • Configure message handlers (onInfo, onWarn, onError) to receive checkout events for user experience management and analytics tracking.
  • Display Checkout either inline with the data-ctc Attribute or in full-screen mode by omitting this element from your page.
  • Payment Only mode creates the Payment and Order, so use it only as the final step after collecting shipping and customer details.

Test your knowledge