Advanced JavaScript options

Explore ways to configure your JavaScript SDK

SDKCurrentLast updated: April 12th 2022, @ 9:22:12 am


The messages component of the PayPal JavaScript SDK is flexible enough for you to integrate and utilize in a variety of ways. The following sections cover different methods for configuring and using the SDK.

On this page

Know before you code

  • This integration modifies an existing Pay Later integration.
  • If you haven't already, add Pay Later messaging to your site.

Configure using JavaScript

You can configure and render your messages using JavaScript as an alternative to HTML attributes. The PayPal JavaScript SDK messages component uses a JavaScript API that is similar to the API used by the buttons component.

Sample code

<head>
  <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=messages"></script>
</head>
<body>
  <div class="pp-message"></div>
  <script>
    paypal
      .Messages({
        amount: 500,
        placement: "product",
        style: {
          layout: "text",
          logo: {
            type: "inline",
          },
        },
      })
      .render('.pp-message');
  </script>
</body>

In the sample code, you create a message object by calling the paypal.Messages function. The paypal.Messages function takes a configuration object as its only argument and returns a message object. The message object has a render() function that accepts an argument that defines into which element(s) it should render messages. render() accepts a CSS selector string (such as .pp-message), an HTMLElement reference or an array of HTMLElement references. Invoking the render() function makes the SDK render messages on your page in the specified target elements.

In the code sample,

  • The amount is set to 500.
  • The message is added to a product detail, so placement: "product" is added to the configuration object.
  • The message uses a text layout with a primary logo on top of the message.
  • The SDK renders the message inside any element which contains an class attribute with the value pp-message.

The configuration object accepted by the Messages function mirrors the HTML attributes that are parsed and read from the elements targeted for messages. For example, data-pp-style-layout is equivalent to the configuration object path of style.layout. See the Reference table to view all the configuration settings and their associated attributes and object keys.

Note: Both inline attributes and the JavaScript configuration object can be used independently or combined to change the message configuration. If there are conflicting settings, the inline HTML attribute setting overrides the JavaScript configuration object setting.

Use event hooks

The messages component of the PayPal JavaScript API lets you to pass in your own callback functions, which is triggered on certain events. The available events to hook into are onRender, onClick, and onApply.

EventDescription
onRenderInvoked after each message has been successfully rendered into the DOM
onClickInvoked after a message has been selected
onApplyInvoked after user selects the Apply button or link in the pop-up modal

One common use case for using these event hooks is to send data to your own analytics platform. For example, you might have your own custom data-processing process, or you might use a third-party analytics provider. In either case, you can use these event hooks to send data to your analytics process.

To add some work or logic on these event hooks, add a function to the associated key of the configuration object you pass to paypal.Messages().

Example

<head>
  <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=messages"></script>
</head>
<body>
  <div class="pp-message"></div>
  <script>
    paypal
      .Messages({
        amount: 500,
        placement: "product",
        style: {
          layout: "text",
          logo: {
            type: "inline",
          },
        },
        onRender: () => {
          console.log("Callback called on render");
          // such as send a "render event" to your own analytics platform.
        },
        onClick: () => {
          console.log("Callback called on click");
          // such as send a "click event" to your own analytics platform.
        },
        onApply: () => {
          console.log("Callback called on apply");
          // such as send an "apply event" to your own analytics platform.
        },
      })
      .render('.pp-message');
  </script>
</body>

In this example, you create a message object by calling the paypal.Messages function like in the previous example. However, in this example, you add optional properties for onRender, onClick, and onApply. When any of these events happen, the associated callback function is invoked. For example, when the message is rendered, there is a log in the console "Callback called on render".

Use namespace attributes

If you're using a legacy integration for PayPal checkout, you might be using the data-namespace attribute when loading the PayPal JavaScript SDK messages component.

Example

<script
  data-namespace="PayPalSDK"
  src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=messages"
></script>

If you're configuring messages using JavaScript, the value you set for data-namespace (in this example "PayPalSDK") is the name of the global variable you use to configure and render messages.

Example

<head>
  <script
    data-namespace="PayPalSDK"
    src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=messages"
  ></script>
</head>
<body>
  <div class="pp-message"></div>
  <script>
    PayPalSDK.Messages({
      amount: 500,
      style: {
        layout: "text",
        logo: {
          type: "inline",
        },
      },
    }).render('.pp-message');
  </script>
</body>

You can find more information about namespaces and compatibility with checkout integrations in upgrade to existing integration.

Render multiple messages

The PayPal SDK renders a message into any element with a data-pp-message attribute or matches the target that you defined in the JavaScript configuration using the Messages() function. The SDK reconciles options from both inline HTML attributes and the JavaScript configuration, with inline attributes taking precedence over the JavaScript configuration in cases of conflicting settings. Using both inline attributes and JavaScript can be useful. For example, you can use the JavaScript configuration to declare shared or common settings, while you can use inline attributes to set specific to settings for a specific message.

Example

<head>
  <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=messages"></script>
</head>
<body>
  <!-- Example list of products -->
  <ul class="listings">
    <li class="listing">
      <div class="listing__content">
        <div class="listing__title">Product Name 1</div>
        <div class="listing__price">$50</div>
      </div>
      <div class="pp-message">
        <!-- Pay Later message will be inserted here -->
      </div>
    </li>
    <li class="listing">
      <div class="listing__content">
        <div class="listing__title">Product Name 2</div>
        <div class="listing__price">$100</div>
      </div>
      <div class="pp-message">
        <!-- Pay Later message will be inserted here -->
      </div>
    </li>
  </ul>

  <script>
    // Grab all product listings on the page
    const listings = Array.from(document.querySelectorAll(".listing"));

    // Loop through each product listing
    listings.forEach((listing) => {
      // Extract the price of the product by grabbing the text content of the
      // element which contains the price. Use `.slice(1)` to remove the leading
      // "$" sign
      const price = Number(
        listing.querySelector(".listing__price").textContent.slice(1)
      );

      // Grab child element of this .listing element that has the
      // "pp-message" classname
      const messageElement = listing.querySelector('.pp-message');

      // Set data-pp-amount on this element. The PayPal SDK continuously
      // monitors message elements for changes to it's attributes, so the
      // message is updated automatically to reflect this amount. This is
      // useful if you need to update the amount based on cart amount, sales,
      // coupon codes, etc.
      messageElement.setAttribute("data-pp-amount", price);
    });

    // Render all Pay Later messages
    paypal
      .Messages({
        style: {
          layout: "text",
          logo: {
            type: "primary",
            position: "top",
          },
        },
      })
      .render('.pp-message');
  </script>
</body>

Update messages without page reload

The SDK's messages component attaches observers to all attributes that start with data-pp on DOM elements targeted with a message. Changing an attribute, such as if a customer updates the item's quantity in their cart, can change data-pp-amount from 100 to 200. Don't call the render() function again because the SDK automatically detects this change and renders a new, more relevant message if necessary.

However, if new HTML content is dynamically injected to the document and you want to render a message inside this new HTML, call the render() function of paypal.Messages again.

Integrate into a single page app

The JavaScript SDK should only be loaded once. In many cases, you should add the <script/> tag into the <head/> of your main HTML document into which you inject your client-side app (this HTML is often called index.html). Make sure to not reload the SDK on state changes or router updates. If the state or routes in your SPA change enough to render new content and new messages, invoke paypal.Messages.render() again and specify the new targets for the messages.

See also

See the Reference tables to view all configuration settings.