JavaScript SDK reference

SDKCurrentLast updated: June 13th 2022, @ 11:32:34 am


Overview

The PayPal JavaScript SDK dynamically exposes objects and methods, based on components you are using. These components are configured in the components query string parameter in the URL you have included in the <script>.

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

Allowed components are:

Buttons

The payment buttons automatically render all eligible buttons in a single location on your page. See the standard payments integration.

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

paypal.Buttons(options)

style

Customize your buttons by passing in the style option.

paypal.Buttons({
  style: {
    layout: 'vertical',
    color:  'blue',
    shape:  'rect',
    label:  'paypal'
  }
}).render('#paypal-button-container');

Layout

Set the style.layout option to determine the button layout when multiple buttons are available:

ValueDescriptionLayout
verticalDefault. Buttons are stacked vertically with a maximum of four buttons. Recommended when:
  • Presenting a dynamic list of payment options on checkout and shopping cart pages.
  • Leveraging Checkout as a full stack payments platform.
Mobile

Venmo is available on mobile in U.S. markets only.
Web
horizontalButtons are stacked horizontally with a maximum of two buttons. Recommended when:
  • Placing buttons on a product page, next to the product.
  • Space on the page is limited.
  • Alternative payment options are already provided.
Mobile

Venmo is available on mobile in U.S. markets only.
Web

Which buttons will I see?

The buttons that display are decided automatically, based on a range of factors, including:

  • Buyer country
  • Device type
  • Funding sources the buyer has opted to see

As a result, each buyer might see a unique combination of buttons. Pay Later offers differ by country and have different buttons. To prevent certain buttons from displaying, see Disable funding in the JavaScript SDK reference.

Color

Set the style.color option to one of these values:

ValueDescriptionButton
goldRecommended
People around the world know us for the color gold and research confirms it. Extensive testing determined just the right shade and shape that help increase conversion. Use it on your website to leverage PayPal’s recognition and preference.
blueFirst alternative
If gold doesn't work for your site, try the PayPal blue button. Research shows that people know it is our brand color, which provides a halo of trust and security to your experience.
silver white blackSecond alternatives
If gold or blue doesn't work for your site design or aesthetic, try the silver, white, or black buttons. Because these colors are less capable of drawing people’s attention, we recommend these button colors as a second alternative.

Shape

Set the style.shape option to one of these values:

ValueDescriptionButton
rectRecommended
The default button shape.
pillA secondary button shape option.

Size

By default, the button adapts to the size of its container element.

  • To customize the button height, set the style.height option to a value from 25 to 55.
  • The width of your button container element must be large enough to fit the payment buttons in your layout. This is necessary for a horizontal button layout.

Label

Set the style.label option to one of these values:

ValueDescriptionButton
paypalRecommended
The default option. Displays the PayPal logo.
checkoutDisplays the Checkout button.
buynowDisplays the PayPal Buy Now button and initializes the checkout flow.
payDisplays the Pay With PayPal button and initializes the checkout flow.
installmentDisplays the PayPal installment button and offers a specified number of payments during a payment installment period.
Note: The installment feature is available only in MX and BR.
Set style.period to set the number of payments during the installment period:
  • BR: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
  • en_MX, MX: 3, 6, 9, 12

Tagline

Set the style.tagline to false to disable the tagline text:

Note: Set the style.layout to horizontal for taglines.

ValueDescriptionButton
trueRecommended
Display tagline text
Default.
falseDisable tagline text.

createOrder

The createOrder parameter sets up the details of the transaction. It's called when the buyer clicks the PayPal button, which launches the PayPal Checkout window where the buyer logs in and approves the transaction on the paypal.com website.

Because this is a client-side call, PayPal calls the Orders API on your behalf, so you don't need to provide the headers and body.

Actions

  • order exposes the create action for creating the order.
  • payment Deprecated. Migrate to order and upgrade your integration if using checkout.js.
<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
      // Set up the transaction
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '0.01'
          }
        }]
      });
    }
  }).render('#paypal-button-container');
</script>

actions.order.create options:

  • intent The intent to either capture the payment immediately or authorize a payment for an order after order creation. The values are:

    • CAPTURE Default. The merchant intends to capture payment immediately after the customer makes a payment.

    • AUTHORIZE The merchant intends to authorize a payment and place funds on hold after the customer makes a payment. Authorized payments are guaranteed for up to three days but are available to capture for up to 29 days. After the three-day honor period, the original authorized payment expires and you must re-authorize the payment. You must make a separate request to capture payments on demand. This intent is not supported when you have more than one purchase_unit within your order.

      See authorize a payment and capture funds later.

  • payer The customer who approves and pays for the order. The customer is also known as the payer and buyer. See payer object definition for additional information.

  • purchase_units Required. An array of purchase units. Each purchase unit establishes a contract between a payer and the payee. Each purchase unit represents either a full or partial order that the payer intends to purchase from the payee. See purchase unit request object definition for additional information.

  • application_context Customize the payer experience during the approval process for the payment with PayPal. See application_context object definition for additional information.

createSubscription

Provides a simplified and secure subscription experience. PayPal presents payment types to your buyers automatically, making it easier for them to complete their purchase using methods like Pay with Venmo, PayPal Credit, and credit card payments without reintegration as they are made available.

Pass vault=true and intent=subscription in the JavaScript SDK to set up a subscription, rather than a one-time transaction.

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons&vault=true&intent=subscription"></script>

Make sure you:

  • Add the <!DOCTYPE html> tag for optimal browser compatibility.
  • Add the <meta http-equiv="X-UA-Compatible" content="IE=edge" /> meta tag to the page for optimal Internet Explorer compatibility.
  • Add the <meta name="viewport" content="width=device-width, initial-scale=1"> tag to the page to ensure optimal rendering on mobile devices.

Finally, implement the createSubscription function that's called when the buyer clicks the PayPal button.

Actions

  • create Creates a subscription for your plan and includes the plan ID, subscriber details, shipping, and other details. The plan_id must belong to the client-id configured on the script.

actions.order.create options: See the create subscription endpoint for allowed options defined in the request body. Also see create a payment button for the subscription for more examples.

paypal.Buttons({
  createSubscription: function(data, actions) {
    return actions.subscription.create({
      'plan_id': 'P-2UF78835G6983425GLSM44MA'
    });
  },

  onApprove: function(data, actions) {
    alert('You have successfully created subscription ' + data.subscriptionID);
  }
}).render('#paypal-button-container');
paypal.Buttons({
  createSubscription: function(data, actions) {
    if (updatedSubscription && (status === 'ACTIVE' || status === 'SUSPENDED')) {
      return actions.subscription.revise(subscriptionId, {
        'shipping_amount': {
          'currency_code': 'USD',
          'value': '10.00'
        }
      });
    } else {
      return actions.subscription.create({
        'plan_id': 'P-2UF78835G6983425GLSM44MA'
      });
    }
  },

  onApprove: function(data, actions) {
    alert('You have successfully created subscription ' + data.subscriptionID);
  }
}).render('#paypal-button-container');

onApprove

Captures the funds from the transaction and shows a message to the buyer to let them know the transaction is successful. The method is called after the buyer approves the transaction on paypal.com.

Because this is a client-side call, PayPal calls the Orders API on your behalf, so you don't need to provide the headers and body.

Actions

capture() - Promise returning the order details.

paypal.Buttons({
  createOrder: function(data, actions) {
    // This function sets up the details of the transaction, including the amount and line item details.
    return actions.order.create({
      purchase_units: [{
        amount: {
          value: '0.01'
        }
      }]
    });
  },
  onApprove: function(data, actions) {
    // This function captures the funds from the transaction.
    return actions.order.capture().then(function(details) {
      // This function shows a transaction success message to your buyer.
      alert('Transaction completed by ' + details.payer.name.given_name);
    });
  }
}).render('#paypal-button-container');
//This function displays payment buttons on your web page.

For the list of order details you receive from actions.order.capture(), see capture payment for order in the Orders API reference.

Note: You can also call from your server to capture an order.

onCancel

When a buyer cancels a payment, they typically return to the parent page. You can instead use the onCancel function to show a cancellation page or return to the shopping cart.

Data attributes

orderId ID of the order.

paypal.Buttons({
  onCancel: function (data) {
    // Show a cancel page, or return to cart
  }
}).render('#paypal-button-container');

onError

If an error prevents buyer checkout, alert the user that an error has occurred with the buttons using the onError callback:

paypal.Buttons({
  onError: function (err) {
    // For example, redirect to a specific error page
    window.location.href = "/your-error-page-here";
  }
}).render('#paypal-button-container');

Note: This error handler is a catch-all. Errors at this point are not expected to be handled beyond showing a generic error message or page.

onInit/onClick

Called when the button first renders. You can use it for validations on your page if you are unable to do so prior to rendering. For example, enable buttons when form validation passes or disable if it fails.

Data attributes

fundingSource the funding source of the button that was clicked. See the funding sources in the standalone buttons guide.

<p id="error" class="hidden">Click the checkbox</p>
<label><input id="check" type="checkbox" required> Click here to continue</label>

<script>
  paypal.Buttons({

    // onInit is called when the button first renders
    onInit: function(data, actions)  {

      // Disable the buttons
      actions.disable();

      // Listen for changes to the checkbox
      document.querySelector('#check')
        .addEventListener('change', function(event) {

          // Enable or disable the button when it is checked or unchecked
          if (event.target.checked)  {
            actions.enable();
          } else  {
            actions.disable();
          }
      });
    },

    // onClick is called when the button is clicked
    onClick: function()  {

      // Show a validation error if the checkbox is not checked
      if (!document.querySelector('#check').checked) {
        document.querySelector('#error').classList.remove('hidden');
      }
    }

  }).render('#paypal-button-container');
</script>

For cases when you need asynchronous validation, see asynchronous validation.

paypal.Buttons().isEligible

Commonly used for standalone buttons when you need to check if the funding source is eligible.

// Loop over each funding source / payment method
paypal.getFundingSources().forEach(function(fundingSource) {

  // Initialize the buttons
  var button = paypal.Buttons({
    fundingSource: fundingSource
  });

  // Check if the button is eligible
  if (button.isEligible()) {

    // Render the standalone button for that funding source
    button.render('#paypal-button-container');
  }
});

paypal.Buttons().render( container )

Renders the buttons in the defined container selector.

paypal.Buttons().render('#paypal-buttons-container');

onShippingChange

While the buyer is on the PayPal site, you can update their shopping cart to reflect the shipping address they chose on PayPal. You can use the callback to:

  • Validate that you support the shipping address.
  • Update shipping costs.
  • Change the line items in the cart.
  • Inform the buyer that you do not support their shipping address.

Availability: The onShippingChange function is not compatible with Subscriptions.

Data attributes

data: An object containing the buyer’s shipping address. Consists of the following fields:

  • orderID (required): An ID that represents an order.
  • paymentID (optional): An ID that represents a payment.
  • paymentToken (required): An ID/token that represents the resource.
  • shipping_address (required): The buyer's selected city, state, country, and postal code.
    • city: Shipping address city.
    • state: Shipping address state or province.
    • country_code: Shipping address country.
    • postal_code: Shipping address ZIP code or postal code.
  • selected_shipping_option (optional): Shipping option selected by the buyer.
    • label: Custom shipping method label.
    • type: Shipping method type (SHIPPING or PICKUP).
    • amount: Additional cost for this method.
      • currency_code: ISO currency code (for example, USD).
      • value: String-formatted decimal format (for example, 1.00).

Actions

actions: An object containing methods to update the contents of the buyer’s cart and interact with PayPal Checkout. Consists of the following methods:

  • resolve: Indicates to PayPal that you do not need to make any changes to the buyer’s cart.
  • reject: Indicates to PayPal that you will not support the shipping address provided by the buyer.
  • order: Client-side order API method.
    • PATCH: To make the update, pass an array of change operations in the request, as described in the order update API reference. The response returns a promise.

Examples

  1. This example shows not supporting international transactions:

    paypal.Buttons({
      onShippingChange: function(data, actions) {
        if (data.shipping_address.country_code !== 'US') {
          return actions.reject();
        }
    
        return actions.resolve();
      }
    }).render('#paypal-button-container');
    
  2. This example shows a more complex situation in which California has free shipping, but flat-rate shipping is the standard for the rest of the US:

    const baseOrderAmount = '15.00';
    
    paypal.Buttons({
      onShippingChange: function(data, actions) {
        // Reject non-US addresses
        if (data.shipping_address.country_code !== 'US') {
          return actions.reject();
        }
    
        // Patch the shipping amount
        const shippingAmount = data.shipping_address.state === 'CA' ? '0.00' : '5.00';
        return actions.order.patch([
          {
            op: 'replace',
            path: '/purchase_units/@reference_id==\'default\'/amount',
            value: {
              currency_code: 'USD',
              value: (parseFloat(baseOrderAmount) + parseFloat(shippingAmount)).toFixed(2),
              breakdown: {
                item_total: {
                  currency_code: 'USD',
                  value: baseOrderAmount
                },
                shipping: {
                  currency_code: 'USD',
                  value: shippingAmount
                }
              }
            }
          }
        ]);
      }
    }).render('#paypal-button-container');
    

Marks

Use marks when the PayPal buttons are presented alongside other funding sources on the page and the PayPal buttons are shown when the buyer clicks a radio button. See Display other payment methods.

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons,marks"></script>

paypal.Marks(options)

paypal.Marks().isEligible

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons,funding-eligibility,marks"></script>

Commonly used for standalone buttons when you need to check if the funding source is eligible.

// Loop over each funding source / payment method
paypal.getFundingSources().forEach(function(fundingSource) {

  // Initialize the marks
  var mark = paypal.Marks({
    fundingSource: fundingSource
  });

  // Check if the mark is eligible
  if (mark.isEligible()) {

    // Render the standalone mark for that funding source
    mark.render('#paypal-mark-container');
  }
});

paypal.Marks().render( container )

Renders the radio buttons that are passed in container selector.

paypal.Marks().render('#paypal-marks-container');
<!-- Render the radio buttons and marks -->
<label>
  <input type="radio" name="payment-option" value="paypal" checked>
  <div id="paypal-marks-container"></div>
</label>

<label>
  <input type="radio" name="payment-option" value="alternate">
</label>

<div id="paypal-buttons-container"></div>
<div id="alternate-button-container">
  <button>Pay with a different method</button>
</div>

<script>
  // Render the PayPal marks
  paypal.Marks().render('#paypal-marks-container');

  // Render the PayPal buttons
  paypal.Buttons().render('#paypal-buttons-container');

  // Listen for changes to the radio buttons
  document.querySelectorAll('input[name=payment-option]')
    .forEach(function (el) {
      el.addEventListener('change', function (event) {

        // If PayPal is selected, show the PayPal button
        if (event.target.value === 'paypal') {
          document.body.querySelector('#alternate-button-container')
            .style.display = 'none';
          document.body.querySelector('#paypal-buttons-container')
            .style.display = 'block';
        }

        // If alternate funding is selected, show a different button
        if (event.target.value === 'alternate') {
          document.body.querySelector('#alternate-button-container')
            .style.display = 'block';
          document.body.querySelector('#paypal-buttons-container')
            .style.display = 'none';
        }
      });
    });

  // Hide non-PayPal button by default
  document.body.querySelector('#alternate-button-container')
    .style.display = 'none';
</script>

Hosted fields

Use when you want to host your own card fields. See advanced credit and debit card payments for integration guidance.

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons,hosted-fields,funding-eligibility"></script>

paypal.HostedFields

paypal.HostedFields.isEligible

Renders the card fields if there are eligible funding sources.

paypal.HostedFields.isEligible();

paypal.HostedFields().render( options )

Renders the card fields in the provided container selector with the specified options.

Options

  • createOrder (required) Sets up the details of the order. See createOrder.

  • onApprove (required) Approves the order. See onApprove.

  • fields (required)

    NameDescription
    numberA field for card number. Required.
    expirationDateA field for expiration date in MM/YYYY or MM/YY format. This should not be used with the expirationMonth and expirationYear properties. Required.
    expirationMonthA field for expiration month in MM format. Use with the expirationYear property.
    expirationYearA field for expiration year in YYYY or YY format. Use with the expirationMonth property.
    cvvA field for 3- or 4-digit card verification code (like CVV or CID). If you'd like to create a CVV-only payment method nonce to verify a card already stored in your vault, omit all other fields to collect CVV only.
    postalCodeA field for postal or region code.
  • styles (optional)

    An object that represents CSS that is applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts such as font-family or color.

    You can also pass the name of a class on your site that contains the styles you'd like to apply. The style properties are automatically pulled off the class and applied to the card fields inputs. This is recommended for input elements only. If using a select for the expiration date, unexpected styling can occur.

    Here are the CSS properties that the card fields support. Specify any other CSS on your page and outside of any PayPal configuration. Unsupported properties will fail and put a warning in the console.

    • appearance

    • color

    • direction

    • font-family

    • font-size-adjust

    • font-size

    • font-stretch

    • font-style

    • font-variant-alternates

    • font-variant-caps

    • font-variant-east-asian

    • font-variant-ligatures

    • font-variant-numeric

    • font-variant

    • font-weight

    • font

    • letter-spacing

    • line-height

    • opacity

    • outline

    • margin

    • padding

    • text-shadow

    • transition

    • -moz-appearance

    • -moz-osx-font-smoothing

    • -moz-tap-highlight-color

    • -moz-transition

    • -webkit-appearance

    • -webkit-font-smoothing

    • -webkit-tap-highlight-color

    • -webkit-transition

      Sample code:

      paypal.HostedFields.render({
        styles: {
          'input': {
            'font-size': '16pt',
            'color': '#3A3A3A'
          },
          '.number': {
            'font-family': 'monospace'
          },
          '.valid':  {
            'color': 'green'
          }
        },
        fields: {
          number: {
            selector: '#card-number'
          },
          cvv: {
            selector: '#cvv',
            placeholder: '•••'
          },
          expirationDate: {
            selector: '#expiration-date'
          }
        }
      });
      

Funding eligibility

By default, the payment buttons automatically render all eligible buttons in a single location on your page.

If your use-case permits, you can render individual, standalone buttons for each supported payment method. For example, render the PayPal, Venmo, PayPal Credit, and alternative payment method buttons on different parts of the checkout page, alongside different radio buttons, or on entirely different pages.

Even with standalone buttons, your integrations take advantage of the eligibility logic the PayPal JavaScript SDK provides, meaning only the appropriate buttons for the current buyer automatically display.

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=funding-eligibility"></script>

paypal.rememberFunding( fundingSources )

If a prior funding source was chosen to be remembered by the customer, it is stored for retrieval for future transactions.

paypal.rememberFunding([ paypal.FUNDING.VENMO ]);

paypal.getFundingSources

Loop over funding sources and payment methods.

paypal.getFundingSources().forEach(function(fundingSource) {
  // ...
});

paypal.isFundingEligible( fundingSource )

Check for funding eligibility from current funding sources.

paypal.isFundingEligible(fundingSource);

Funding

This table includes the available funding sources. By default, the payment buttons automatically render all eligible buttons in a single location on your page. If you need to override this, you can specify the buttons you'd like to show by following the Standalone payment buttons guide.

Funding sourcePayment button
paypal.FUNDING.PAYPALPayPal
paypal.FUNDING.CARDCredit or debit cards
paypal.FUNDING.CREDITPayPal Credit
paypal.FUNDING.VENMOVenmo
paypal.FUNDING.SEPASEPA-Lastschrift
paypal.FUNDING.BANCONTACTBancontact
paypal.FUNDING.EPSeps
paypal.FUNDING.GIROPAYgiropay
paypal.FUNDING.IDEALiDEAL
paypal.FUNDING.MERCADOPAGOMercado Pago
paypal.FUNDING.MYBANKMyBank
paypal.FUNDING.P24Przelewy24
paypal.FUNDING.SOFORTSofort

Messages

Use when you want to display Pay Later messages on your site. Because Pay Later offers differ by country, certain options for the messages component render differently depending on country. For complete details, as well as country-specific examples, see Pay Later Reference.

Version

Current version of the JavaScript SDK.

paypal.version

See also