Napoleon's Penguin Mascot

    @primer-io/checkout-web
    TypeScript icon, indicating that this package has built-in type declarations

    2.2.1 • Public • Published

    Primer Web SDK

    Primer's Official Universal Checkout Web SDK




    💪 Features of the Web SDK

    💳   Create great payment experiences with our highly customizable Universal Checkout

    🧩   Connect and configure any new payment method without a single line of code

      Dynamically handle 3DS 2.0 across processors and be SCA ready

    ♻️   Store payment methods for one-click checkout, recurring and repeat payments

    📱   Proprietary Apple & Google Pay integrations that work with any PSP

    🔒   Always PCI compliant without redirecting customers


    📚 Documentation

    Consider looking at the following resources:


    💡 Support

    For any support or integration related queries, feel free to Contact Us.


    🚀 Quick start

    Take a look at our Quick Start Guide for accepting your first payment with Universal Checkout.


    📋 Prerequisites

    • 🔑 Generate a client token by creating a client session in your backend
    • 🧱 Prepare a container in which to render Universal Checkout
    • 🎉 That's it!

    🧱 Installation

    With npm (recommended)

    Our Web SDK is available on npm under the name @primer-io/checkout-web.

    This package includes TypeScript definitions.

    # With yarn
    yarn add @primer-io/checkout-web
    
    # With npm
    npm install --save @primer-io/checkout-web
    
    import { Primer } from '@primer-io/checkout-web';
    
    Primer.showUniversalCheckout(clientToken, {
      /* Options */
    });

    With our CDN

    Include the Primer.min.js script on the page where you want the checkout to be rendered.

    Ensure that you're providing the desired version in the script tag. In the case below, it's v2.0.0:

    <link rel="stylesheet" href="https://sdk.primer.io/web/v2.0.0/Checkout.css" />
    
    <script
      src="https://sdk.primer.io/web/v2.0.0/Primer.min.js"
      crossorigin="anonymous"
    ></script>

    Primer.min.js will add the Primer object to the global scope:

    const { Primer } = window;
    
    Primer.showUniversalCheckout(clientToken, {
      /* Options */
    });

    👩‍💻 Usage

    🔍  Rendering the checkout

    Availing Universal Checkout is as easy as implementing one line of code:

    import { Primer } from '@primer-io/checkout-web';
    
    const universalCheckout = await Primer.showUniversalCheckout(
      clientToken,
      options,
    );

    Below is an example of a basic implementation of Universal Checkout:

    const clientToken = '...'; // client token retrieved from your backend
    
    const options = {
      // Container element which will contain the checkout
      container: '#container',
    
      onCheckoutComplete({ payment }) {
        // Notifies you that a payment was created
        // Move on to next step in your checkout flow:
        // e.g. Show a success message, giving access to the service, fulfilling the order
      },
    };
    
    const universalCheckout = await Primer.showUniversalCheckout(
      clientToken,
      options,
    );

    Note that there are more options which can be passed to Universal Checkout. Please refer to the section below for more information.


    🧰  Checkout Options

    When calling showUniversalCheckout you can provide Universal Checkout with some configuration options.

    These options range from callbacks notifying you of the current payment's status, to styling options for certain UI elements.

    Below are some options to consider when integrating Universal Checkout:

    🚀 General Options

    ⚙️ Container and locale

    option Type Description
    container string or Element The container element in which the checkout should be rendered required
    locale string This option forces the locale. By default, the locale will be set to the browser's locale optional

    ⚙️ Payment Lifecycle Callbacks

    Callbacks can be provided to Universal Checkout which will notify you on certain checkout events such as payment creation.

    These callbacks can be used to inform you on the current state of the checkout.

    We strongly recommend you to implement onCheckoutComplete to redirect the user to an order confirmation page when the payment is successful:

    const options = {
      /* Other checkout options ... */
    
      onBeforePaymentCreate(data, handler) {
        // Notifies you that a payment will be created
        // Update your UI accordingly
        // e.g. Show custom loading UI, etc.
        // Abort or continue with payment creation
        // Primer will continue with payment creation if onBeforePaymentCreate is not implemented
    
        // ⚠️ You MUST call one of the functions of the `handler` if `onBeforePaymentCreate` is implemented
    
        // Choose to abort a payment
        return handler.abortPaymentCreation();
    
        // Choose to continue with payment creation
        return handler.continuePaymentCreation();
      },
    
      onCheckoutComplete({ payment }) {
        // Notifies you that a payment was created
        // Move on to next step in your checkout flow:
        // e.g. Show a success message, giving access to the service, fulfilling the order, ...
      },
    
      onCheckoutFail(error, { payment }, handler) {
        // Notifies you that the checkout flow has failed and a payment could not be created
        // This callback can also be used to display an error state within your own UI.
    
        // ⚠️ `handler` is undefined if the SDK does not expect anything from you
        if (!handler) {
          return;
        }
    
        // ⚠️ If `handler` exists, you MUST call one of the functions of the handler
    
        // Show a default error message
        return handler.showErrorMessage();
    
        // Show a custom error message
        return handler.showErrorMessage('This is my custom error message');
      },
    };

    ⚙️ Client Session Lifecycle Callbacks

    Callbacks can be provided to Universal Checkout which will notify you on client session update events.

    const options = {
      /* Other checkout options ... */
    
      onBeforeClientSessionUpdate() {
        // Notifies you that the client session is in the process of being updated
        // Use it to show a loading indicator on your UI
      },
    
      onClientSessionUpdate(clientSession) {
        // Notifies you when the client session has been updated by the checkout
        // Returns updated client session
        // Updated client session can be used to inform your UI
        // e.g. update tax, shipping or discount amounts displayed to your customers
      },
    };

    💳 Payment Methods Options

    Learn more about the payment method specific options.


    🎨 Customization Options

    Learn more about the customization options.

    ⚙️ Styling

    option Type Description Default
    style Object Custom style applied to the UI.
    Learn more about the capabilities in our Customization Guide
    Default style optional

    ⚙️ Form Options

    option Type Description Default
    form.inputLabelsVisible Boolean Choose whether to show the label above inputs true optional

    ⚙️ Submit Button Options & Callbacks

    Universal Checkout allows you to use your own submit button for submitting forms. By default, the built-in submit button will be favored:

    option Type Description Default
    submitButton.useBuiltInButton Boolean Set whether to use built-in submit button or to display your own custom button true optional

    Note that when disabling the built-in submit button and using your own custom submit button, it is required to implement the submit() function in order to notify Universal Checkout of form submissions.
    Read more about the submit() function in the Manual Form Submission section referenced below.


    When using your own custom submit button, it's important to use the following callbacks to ensure that your submit button is in the correct state and in sync with the checkout as your customers interact with it:

    const options = {
      /* Other options ... */
    
      submitButton: {
        useBuiltInButton: false, // Default to true
    
        // Callback for receiving the submit button's visible state in the current scene
        onVisible(isVisible, context: { currentSceneId }) {
          // Show or hide your custom submit button
        },
    
        // Callback for receiving the submit button's disabled state in the current scene
        onDisable(isDisabled, context: { currentSceneId }) {
          // Disable or enable your custom submit button
        },
    
        // Callback for receiving the submit button's loading state in the current scene
        onLoading(isLoading, context: { currentSceneId }) {
          // Show your submit button in a loading state
        },
    
        // Callback for receiving the submit button's content in the current scene
        onContentChange(content, context: { currentSceneId }) {
          // Set your submit button's content with either the content provided or your own custom content
        },
      },
    };

    ⚙️ Processing Indicator Options

    Show a processing indicator overlay on top of the checkout when submitting a form:

    option Type Description Default
    processingIndicator.visible Boolean Choose whether a processing indicator overlay should be shown on form submission true optional

    ⚙️ Error Message Options & Callbacks

    When Universal Checkout encounters errors processing payments, these errors will be shown to your users by default, below the submit button.

    If you want to show your own error messages, you have the option to disable the default, built-in error messages:

    option Type Description Default
    errorMessage.disabled Boolean Choose whether to allow Universal Checkout to show error messages false optional

    You can use the following callbacks to get notified when Universal Checkout intends to display an error message. By using these callbacks, you can respond with your own UI changes and avail a custom error message:

    const options = {
      /* Other options ... */
    
      errorMessage: {
        disabled: false, // Default to false
    
        // A callback for when the error message should be displayed
        onErrorMessageShow(message) {
          // Choose to use provided message for own purposes
        },
    
        // A callback for when the error message should be hidden
        onErrorMessageHide() {
          // Update own UI accordingly
        },
      },
    };

    ⚙️ Success Screen Options

    When the checkout is succefully complete, Universal Checkout displays a success scene with a default success message "Your payment was successful!".

    Set the option successScreen to modify the behavior of the success scene.

    const options = {
      /* Other options ... */
    
      // Remove the success screen
      successScreen: false,
    
      // Change the message of the default success screen
      successScreen: {
        type: 'CHECK',
        title: 'This is a custom success message!',
      },
    };

    🔨 Advanced Options

    ⚙️ Manual Payment Creation & Tokenization Lifecycle Callbacks

    By default, Universal Checkout will automatically create payments and manage their lifecycles on your behalf. The manual payment creation flow used in previous Web SDK versions is still supported.

    Check our Manual Payment Creation guide.

    ⚙️ Show the flow for a single payment method

    The payment methods featuring a dedicated screen allows you to directly display their flow. For that, make sure to:

    • Set uxFlow to SINGLE_PAYMENT_METHOD_CHECKOUT
    • Set paymentMethod to the payment method you want to display
    const options = {
      /* Other options ... */
    
      uxFlow: 'SINGLE_PAYMENT_METHOD_CHECKOUT',
      paymentMethod: 'PAYMENT_CARD',
    };

    Payment methods that supports this flow

    • Card: PAYMENT_CARD
    • Klarna: KLARNA
    • GoCardless: GOCARDLESS

    ⚙️ Customizable Payment Method Button options

    Some payment methods enables you to customize the payment method button.

    option Type Description Default
    logoSrc String Data URL representing the logo you want to display in the payment method button. required
    background String Color of the background of the payment method button. required
    logoAlt String Accessibility marker for the payment method button required
    text String Label to display to the right of logoSrc Only show logoSrc optional

    Payment methods that supports this flow

    • Gift Cards with Mollie: PAYMENT_CARD

    🔧   Checkout Methods

    Universal Checkout exposes some methods which can be called to perform some specific actions:

    Set Client Token

    When updating the client session, after the checkout has been initialized, you will receive a client token in the response returned from PATCH /client-session.

    In order for the checkout to know that you have updated the client session, you will need to pass this new client token back to the checkout:

    const universalCheckout = await Primer.showUniversalCheckout(
      clientToken,
      options,
    );
    
    // Pass the new client token to Universal Checkout by calling setClientToken
    // This will result in Universal Checkout having access to the latest changes made to the client session
    universalCheckout.setClientToken(clientToken);

    Manual Form Submission

    The checkout provides a method for manually calling submit. This is useful when using your own custom submit button.

    const universalCheckout = await Primer.showUniversalCheckout(
      clientToken,
      options,
    );
    
    const handleMySubmitButtonClick = () => {
      // Forward all submit button clicks to the SDK
      universalCheckout.submit();
    };

    Disabling Tokenization and Payment Creation

    The checkout provides setPaymentCreationEnabled and setTokenizationEnabled to enable or disable tokenization and payment creation. Use this if you would like to prevent users from paying because your side of the checkout is not valid.

    These two functions can be used interchangibly.

    const universalCheckout = await Primer.showUniversalCheckout(
      clientToken,
      options,
    );
    
    // Disable payment creation
    universalCheckout.setPaymentCreationEnabled(false);
    universalCheckout.setTokenizationEnabled(false);
    
    // Enable payment creation
    universalCheckout.setPaymentCreationEnabled(true);
    universalCheckout.setTokenizationEnabled(true);

    Keywords

    none

    Install

    npm i @primer-io/checkout-web

    DownloadsWeekly Downloads

    1,816

    Version

    2.2.1

    License

    MIT

    Unpacked Size

    203 kB

    Total Files

    6

    Last publish

    Collaborators

    • primer-developers
    • stickycube
    • aladin.taleb