v6 JavaScript Web SDK: Integrate

SDKLimited Release

Last updated: Aug 7th, 12:41pm

Understanding Authorization with clientToken

To initialize the SDK securely, a clientToken must be generated server-side and passed to your front-end. This token ensures that all API requests made by the SDK on your behalf are authenticated and protected.

The SDK clientToken is a publicly available universal access token (UAT) to use for the buyer's SDK session. This token is browser safe and is a short-lived token with a TTL of 15 minutes. There is no refresh token, after it expires you must make a new token.


Security Model

We’ve designed the clientToken to prioritize security by leveraging the following safeguards:

  1. Domain Binding: The token is bound to your domain to prevent unauthorized usage elsewhere, minimizing the risk of impersonation attacks.

  2. Cryptographic Security: The payload is cryptographically secured with a digital signature to ensure its integrity.

Example API call using curl

    1curl --request POST 'https://api-m.sandbox.paypal.com/v1/oauth2/token' \
    2--user '<CLIENT_ID>:<CLIENT_SECRET>' \
    3--header 'Content-Type: application/x-www-form-urlencoded' \
    4--header 'PayPal-Auth-Assertion: <GENERATED_AUTH_ASSERTION>' \
    5--data-urlencode 'response_type=client_token' \
    6--data-urlencode 'domains[]=<URL1_FOR_THE_SESSION>,<URL2_FOR_THE_SESSION>' \
    7--data-urlencode 'grant_type=client_credentials'
    Parameter Required Description
    response_type Yes

    Value of client_token. *It is critical to set this value correctly to generate a browser-safe token.

    domains[] Yes

    Comma-separated list of merchant domains using the SDK.

    Provide the root domain name only. No subdomains such as sub.example.com. No wildcard characters such as *.example.com. No protocols such as http or https.

    grant_type Yes

    Value of client_credentials.

    paypal-auth-assertion No

    Used by partners to identify the merchant.

    Installing the SDK

    You can include our SDK in your project by adding a standard <script> tag to your HTML. We’ve designed the SDK to be lightweight and modular, giving you flexibility in how you integrate it.

      1<script src="https://www.sandbox.paypal.com/web-sdk/v6/core"></script>

      Instantiating the SDK

      To instantiate the SDK, use the createInstance function, which is an asynchronous method added to the window.paypal namespace. Below is an example of how merchants can use this function.

        1const clientToken = "<%= clientToken %>"; // Your client token passed from your server
        2try {
        3 const sdkInstance = await window.paypal.createInstance({
        4 clientToken,
        5 components: ["paypal-payments"], // Specify the components you need
        6 locale: "en-US",
        7 pageType: "checkout",
        8 });
        9 console.log("SDK initialized successfully:", sdkInstance);
        10} catch (error) {
        11 console.error("Error initializing SDK:", error);
        12}
        Parameter Required Description
        clientToken Yes

        Fetched from your server using a clientId and secret.

        components Yes

        Specify additional components to load without needing to add additional script tags. paypal-payments is required for one-time payment integrations.

        locale No

        Specify the locale using a BCP-47 code. If you do not define a locale, the SDK will determine the user's locale based on their browser settings.  

        pageType No

        Inform the SDK what type of page the SDK is being rendered.

        The components Array

        The components array is a key part of the createInstance method, allowing you to define which SDK features you want to include in your integration. By specifying components such as "paypal-payments", you can load only the functionality you need, keeping the SDK lightweight and optimized for your use case.

        Component Name Required Description
        paypal-payments No

        This will give you the functionality to create a PayPal payment session for a user who clicks on the PayPal button.

        venmo-payments No

        This will give you the functionality to create a Venmo payment session for a user who clicks on the Venmo button.

        paypal-legacy-billing-agreements No

        To be determined.

        Using the Eligibility Client Side Helper

        To ensure a smooth checkout experience for your buyers, it’s required to verify eligibility for specific payment methods.The SDK provides an eligibility helper that checks for buyer and merchant eligibility, and interacts with PayPal’s public API to then determine whether a payment method, such as PayPal, can be used. This allows you to conditionally render the appropriate payment buttons on your site.

          1const clientToken = "<%= clientToken %>"; // Your generated client token
          2try {
          3 // Initialize the SDK instance
          4 const sdkInstance = await window.paypal.createInstance({
          5 clientToken,
          6 components: ["paypal-payments"], // Load the necessary SDK component
          7 });
          8 // Check funding eligibility
          9 const paymentMethods = await sdkInstance.findEligibleMethods();
          10 const isPayPalEligible = paymentMethods.isEligible("paypal");
          11 // Conditionally render the PayPal button
          12 if (isPayPalEligible) {
          13 const paypalButton = document.createElement("paypal-button");
          14 document.querySelector("#buttons-container").append(paypalButton);
          15 }
          16} catch (error) {
          17 console.error(
          18 "Error checking funding eligibility or rendering button:",
          19 error,
          20 );
          21}

          Create a checkout session

          After initializing the SDK using the createInstance method, the returned instance provides the functionality to start a checkout session. The createPayPalOneTimePaymentSession method allows you to define event handlers (callback functions) to manage different stages of the checkout process, such as address changes, payment approval and errors.

            1const clientToken = "<%= clientToken %>"; // Your secure client token
            2try {
            3 // Initialize the SDK instance
            4 const sdkInstance = await window.paypal.createInstance({
            5 clientToken,
            6 pageType: "checkout", // Specify the page type
            7 });
            8
            9 // Check funding eligibility
            10 const paymentMethods = await sdkInstance.findEligibleMethods();
            11 const isPayPalEligible = paymentMethods.isEligible("paypal");
            12
            13 if (isPayPalEligible) {
            14 // Create a PayPal checkout session with event handlers
            15 const paypalOneTimePaymentSession =
            16 sdkInstance.createPayPalOneTimePaymentSession({
            17 onApprove: (data) => {
            18 // Handle successful payment approval
            19 console.log("Payment approved:", data);
            20 },
            21 onShippingAddressChange: (data) => {
            22 // Handle shipping address changes
            23 console.log("Shipping address changed:", data);
            24 },
            25 onShippingOptionsChange: (data) => {
            26 // Handle updates to shipping options
            27 console.log("Shipping options updated:", data);
            28 },
            29 onCancel: (data) => {
            30 // Handle payment cancellation
            31 console.warn("Payment canceled:", data);
            32 },
            33 onError: (error) => {
            34 // Handle errors during the checkout process
            35 console.error("Error during checkout:", error);
            36 },
            37 });
            38 console.log(
            39 "Payment session created successfully:",
            40 paypalOneTimePaymentSession
            41 );
            42 }
            43} catch (error) {
            44 console.error("Error initializing SDK or creating payment session:", error);
            45}
            Parameter Required Description
            onApprove Yes

            Callback for capturing or authorizing the order.

            onShippingAddressChange No

            Callback for reacting to the selected customer shipping address.

            onShippingOptionsChange No

            Callback for reacting to the selected customer shipping option.

            onError No

            Callback for receiving errors that happen after the flow successfully started.

            onCancel No

            Callback for knowing when the customer canceled the flow.

            orderId No

            Option for passing in the order ID directly to support eager order creation on page load.

            commit No

            possible values are true/false

            true = ‘Pay Now’

            false = ‘Continue’

            Starting the PayPal Checkout Flow

            Merchants can control which checkout flow to use for launching the PayPal experience, as well as define fallback logic for unsupported flows. For example, in environments like webviews, where popups are not supported, merchants can choose to fall back to a modal or redirect flow.

            Below is an example that demonstrates how to start the PayPal checkout flow and handle fallbacks.

              1const clientToken = "<%= clientToken %>"; // Your secure client token
              2try {
              3 // Initialize the SDK instance
              4 const sdkInstance = await window.paypal.createInstance({
              5 clientToken,
              6 pageType: "checkout", // Specify the page type
              7 });
              8
              9 // Check funding eligibility
              10 const paymentMethods = await sdkInstance.findEligibleMethods();
              11 const isPayPalEligible = paymentMethods.isEligible("paypal");
              12
              13 if (isPayPalEligible) {
              14 // Create a PayPal checkout session with event handlers
              15 const paypalOneTimePaymentSession =
              16 sdkInstance.createPayPalOneTimePaymentSession({
              17 onApprove: (data) => {
              18 // Handle successful payment approval
              19 console.log("Payment approved:", data);
              20 },
              21 onShippingAddressChange: (data) => {
              22 // Handle shipping address changes
              23 console.log("Shipping address changed:", data);
              24 },
              25 onShippingOptionsChange: (data) => {
              26 // Handle updates to shipping options
              27 console.log("Shipping options updated:", data);
              28 },
              29 onCancel: (data) => {
              30 // Handle payment cancellation
              31 console.warn("Payment canceled:", data);
              32 },
              33 onError: (error) => {
              34 // Handle errors during the checkout process
              35 console.error("Error during checkout:", error);
              36 },
              37 });
              38
              39 // Handle checkout flow on button click
              40 async function onClick() {
              41 try {
              42 // Attempt to start the checkout flow using a popup
              43 await paypalOneTimePaymentSession.start(
              44 { presentationMode: "popup" },
              45 orderIdPromise
              46 );
              47 } catch (error) {
              48 console.error("Error starting checkout flow:", error);
              49 await paypalOneTimePaymentSession.start(
              50 { presentationMode: "modal" },
              51 orderIdPromise
              52 );
              53 }
              54 }
              55 // Bind the click handler to your button (example ID: "paypal-button")
              56 document
              57 .getElementById("paypal-button")
              58 ?.addEventListener("click", onClick);
              59 }
              60} catch (error) {
              61 console.error("Error initializing SDK or creating payment session:", error);
              62}

              Connecting Your Business Logic to the PayPal Button

              The final step in the integration is connecting your business logic to the PayPal button. In this example, we define the onClick function separately and attach it to the button using addEventListener. This approach ensures better error handling, as a standalone onClick function can utilize its own try/catch block, which avoids potential issues where nested try/catch blocks inside callbacks may fail to handle errors properly.

                1const clientToken = "<%= clientToken %>";
                2try {
                3 const sdkInstance = await window.paypal.createInstance({
                4 clientToken,
                5 components: ["paypal-payments"],
                6 });
                7 const eligibility = await sdkInstance.findEligibleMethods();
                8 const isPayPalEligible = eligibility.isEligible("paypal");
                9 if (isPayPalEligible) {
                10 const paypalButton = document.createElement("paypal-button");
                11 document.querySelector("#buttons-container").append(paypalButton);
                12 const paypalOneTimePaymentSession =
                13 sdkInstance.createPayPalOneTimePaymentSession({
                14 onApprove,
                15 onShippingAddressChange,
                16 onShippingOptionsChange,
                17 onCancel,
                18 onError,
                19 });
                20 async function onClick() {
                21 try {
                22 await paypalOneTimePaymentSession.start(
                23 { presentationMode: "auto" },
                24 orderIdPromise,
                25 );
                26 } catch (error) {
                27 console.error(e);
                28 }
                29 }
                30 paypalButton.addEventListener("click", onClick);
                31 }
                32} catch (error) {
                33 console.error(error);
                34}


                Available PayPal Payment Flows

                Value Description
                auto

                SDK chooses the flow.

                popup

                Launch the traditional popup experience.

                modal

                Create an iframe on the page that acts as a modal to checkout.

                redirect

                Leverage the redirect URLs provided to the orders API for a full-page redirect.

                Styling the Button

                Button styling is achieved using a combination of CSS classes and CSS variables.

                • CSS Classes: Used to apply predefined styles, such as background colors.

                • CSS Variables: Allow merchants to set custom values, such as border radius, for additional flexibility.


                Available Classes

                Value Description
                paypal-gold

                Insert screenshot.

                paypal-white

                Insert screenshot

                paypal-blue

                insert screenshot


                CSS Class example

                  1<!-- merchant is using a preset from our provideed values -->
                  2<paypal-button class="paypal-gold" type="pay"></paypal-button>

                  Available Variables

                  Custom Properties Value
                  --paypal-button-border-radius Any valid CSS value for border-radius
                  --paypal-mark-border-radius Any valid CSS value for border-radius


                  CSS Variable example
                    1<style>
                    2 /* a selector must be used to target the custom element */
                    3 paypal-button {
                    4 /* Merchant wants an explicit border radius, so they use CSS vars */
                    5 --paypal-button-border-radius: 55px;
                    6 }
                    7</style>
                    8<paypal-button class="paypal-gold" type="pay"></paypal-button>

                    Adding a Label to the Button

                    The type property controls the button text. Pass an enum value to the type attribute to specify the text.

                      1<paypal-button type="pay"></paypal-button>


                      Button Type Text
                      buynow PayPal Buy Now
                      checkout PayPal Checkout
                      pay Pay with PayPal
                      subscribe PayPal Subscribe

                      Browser Compatibility

                      Browser (web/mobile web) Minimum Supported Version
                      Chrome 69
                      Safari 12
                      Firefox 63
                      Samsung Internet 10
                      Edge 79

                      PayPal start() method options

                      Each checkout session has a start method which begins your buyers payment experience. Below are the options you can pass to this function. 

                      ParamRequiredTypeOptions Description
                      presentationModeNoStringauto, modal, redirect, payment-handler This controls the payment experience your buyer sees.
                      autoRedirectNoObjectenabled (boolean) This can be used alongside the `redirect` presentationMode to return the `redirectUrl`. Only recommended if wrapping our SDK in an iframe
                      fullPageOverlayNoObjectenabled (boolean) This controls the overlay that displays in the window when a mini-browser popup is launched. Setting this to `false` disables the popup. Only recommended if wrapping our SDK in an iframe.
                      loadingScreenNoObjectlabel (string) This controls the loading text in the popup as PayPal checkout is being loaded. The only value `label` accepts is `connecting` &nbsp;