JavaScript SDK reference

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');

See the style reference for the payment buttons for all the ways you can customize them.

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.

Note: You might need to make API calls directly from your server, rather than using the client-side functions that the JavaScript SDK provides. Handle creating an order on your server.

Actions
  • order — exposes the create action for creating the order.

  • paymentDeprecated. 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:

    • CAPTUREDefault. 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_unitsRequired. 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 order_appication_context object definition for additional information.

createBillingAgreement

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

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons&vault=true"></script>
paypal.Buttons( {
  createBillingAgreement: function()  {
    var CREATE_BILLING_AGREEMENT_URL = 'https://mystore.com/api/paypal/create-billing-agreement';

    return fetch(CREATE_BILLING_AGREEMENT_URL,  {
      method: 'post',
      headers:  {
        'content-type': 'application/json'
       }
     }).then(function(res)  {
      return res.json();
     }).then(function(data)  {
      return data.billingToken;
     });
   }
 }).render('#paypal-button-container');

See Billing Agreement integrations and Subscriptions integration for detailed 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.

  <script>
    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.
  </script>

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, show an error page using the onError callback.

paypal.Buttons( {
  onError: function (err)  {
    // Show an error page here, when an error occurs
   }
 }).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 s 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 wheen 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');

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 PayPal buttons with 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>
  <img src="paypal-mark.jpg" alt="Pay with PayPal">
</label>

<label>
  <input type="radio" name="payment-option" value="alternate">
  <div id="paypal-marks-container"></div>
</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-button-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-button-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 reference.

<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, container )

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)

    Name Description
    number A field for card number.
    expirationDate A field for expiration date in MM/YYYY or MM/YY format. This should not be used with the expirationMonth and expirationYear properties.
    expirationMonth A field for expiration month in MM format. Use with the expirationYear property.
    expirationYear A field for expiration year in YYYY or YY format. Use with the expirationMonth property.
    cvv A 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.
    postalCode A 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:  {
          container: '#card-number'
         },
        cvv:  {
          container: '#cvv',
          placeholder: '•••'
         },
        expirationDate:  {
          container: '#expiration-date'
         }
       }
     }, '#paypal-field-container');
    

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 next transaction.

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 list 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 buttons guide.

Funding source Description
paypal.FUNDING.PAYPAL PayPal
paypal.FUNDING.CARD Credit or debit cards
paypal.FUNDING.CREDIT PayPal Credit
paypal.FUNDING.VENMO Venmo
paypal.FUNDING.SEPA SEPA-Lastschrift
paypal.FUNDING.BANCONTACT Bancontact
paypal.FUNDING.EPS eps
paypal.FUNDING.GIROPAY giropay
paypal.FUNDING.IDEAL iDEAL
paypal.FUNDING.MYBANK MyBank
paypal.FUNDING.P24 Przelewy24
paypal.FUNDING.SOFORT Sofort

Version

Current version of the JavaScript SDK.

paypal.version

See also