JavaScript SDK reference

SDKCurrentLast updated: March 5th 2024, @ 12:27:35 pm


Important: This is version 2 of the JavaScript SDK reference guide. Version 1 is a legacy integration.

Overview

The PayPal JavaScript SDK dynamically exposes objects and methods based on the components you select. Add components to your <script> by passing them in the src URL using the components query string parameter.

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

The JavaScript SDK supports the following components:

Buttons

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

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

paypal.Buttons(options)

style

Customize your buttons using the style option.

1paypal.Buttons({
2 style: {
3 layout: 'vertical',
4 color: 'blue',
5 shape: 'rect',
6 label: 'paypal'
7 }
8}).render('#paypal-button-container');

Layout

Set the style.layout option to determine how the buttons show up when multiple buttons are available:

ValueDescriptionLayout
verticalDefault. Buttons are stacked vertically with a maximum of 6 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 US markets only.
Web
horizontalButtons are stacked horizontally with a maximum of 2 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 US markets only.
Web

Which buttons will I see?

The buttons that show up 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 sees a unique combination of buttons. Pay Later offers differ by country and have different buttons. To prevent certain buttons from showing up, see Disable funding in the JavaScript SDK reference.

Color

Set the style.color option to 1 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 1 of these values:

ValueDescriptionButton
rectRecommended
The default button shape.
pillRounds the sides of the button.
sharpGives the button sharp corners.

Border radius

style.borderRadius is used to define a custom border radius of the buttons.

To define the border radius of the buttons, set the style.borderRadius option to a number that is greater than or equal to 0.

Note: If style.borderRadius and style.shape are both defined, style.borderRadius will take priority.

paypal.Buttons({
  style: {
    borderRadius: 10,
  }
}).render('#paypal-button-container');
</script>

Size

The button adapts to the size of its container element by default.

  • To customize the button height, set the style.height option to a value from 25 to 55.
  • Your button container element needs to be wide enough for your horizontal payment buttons.

Width

The button has a default maximum width of 750px, but you can make the button larger:

  1. Set style.disableMaxWidth to true.
  2. Change the max-width value at the container level.
1<div id="paypal-button-container" style="max-width:1000px;"></div>
2
3<script>
4 paypal.Buttons({
5 style: {
6 disableMaxWidth: true
7 },
8}).render('#paypal-button-container');
9</script>

Label

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

ValueDescriptionButton
paypalRecommended
The default option. Shows the PayPal logo.
checkoutShows the Checkout button.
buynowShows the PayPal Buy Now button and initializes the checkout flow.
payShows the Pay With PayPal button and initializes the checkout flow.
installmentShows 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
Show tagline text
Default.
falseDisable tagline text.

displayOnly

The displayOnly parameter determines the payment methods your customers see. By default, buyers see all eligible payment methods. Options passed to displayOnly are applied in order from left to right.

We have the following options available:

ValueDescription
vaultableDisplay only the payment methods that support save. Your integration, merchant settings, and customer location determine which payment methods can be saved.
paypal.Buttons({
  displayOnly: ["vaultable"]
}).render('#paypal-button-container');

createOrder

The createOrder function sets up the details of the transaction. Pass createOrder as a parameter in paypal.Buttons. When the buyer selects the PayPal button, createOrder launches the PayPal Checkout window. The buyer logs in and approves the transaction on the paypal.com website.

Actions

  1. Frontend (HTML)
  2. Backend (Node.js example)
1<!DOCTYPE html>
2<html>
3 <head>
4 <meta name="viewport" content="width=device-width, initial-scale=1">
5 </head>
6 <body>
7 <!-- Replace "test" with your own sandbox Business account app client ID -->
8 <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
9 <!-- Set up a container element for the button -->
10 <div id="paypal-button-container"></div>
11 <script>
12 paypal.Buttons({
13 createOrder() {
14 return fetch("/my-server/create-paypal-order", {
15 method: "POST",
16 headers: {
17 "Content-Type": "application/json",
18 },
19 body: JSON.stringify({
20 cart: [
21 {
22 sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
23 quantity: "YOUR_PRODUCT_QUANTITY",
24 },
25 ]
26 })
27 })
28 .then((response) => response.json())
29 .then((order) => order.id);
30 }
31 }).render('#paypal-button-container');
32 </script>
33 </body>
34</html>

Orders v2 API 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 3 days but are available to capture for up to 29 days. After the 3-day honor period, the original authorized payment expires and you need to re-authorize the payment. You need to make a separate request to capture payments on demand. This intent isn't supported when you have more than 1 purchase_unit within your order.

      See authorize a payment and capture funds later.

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

  • payment_source: Optionally define the payment_source when creating the order. This payment source can be paypal, a vault token, card information for PCI-compliant merchants, or alternative payment methods such as blik and apple_pay. For more information, see Orders v2 API and payment_source.

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 such as 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.

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

Finally, implement the createSubscription function that's called when the buyer selects 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 needs to belong to the client-id configured on the script.

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

1paypal.Buttons({
2 createSubscription(data, actions) {
3 return actions.subscription.create({
4 'plan_id': 'P-2UF78835G6983425GLSM44MA'
5 });
6 },
7
8 onApprove(data) {
9 alert('You have successfully created subscription ' + data.subscriptionID);
10 }
11}).render('#paypal-button-container');
1paypal.Buttons({
2 createSubscription(data, actions) {
3 // updatedSubscription, status, and subscriptionId are defined by your code
4 if (updatedSubscription && (status === 'ACTIVE' || status === 'SUSPENDED')) {
5 // if subscription exists, revise it by chaning the plan id
6 return actions.subscription.revise(subscriptionId, {
7 "plan_id": "NEW_SUBSCRIPTION_PLAN_ID"
8 });
9 } else {
10 return actions.subscription.create({
11 'plan_id': 'P-2UF78835G6983425GLSM44MA'
12 });
13 }
14 },
15
16 onApprove(data) {
17 alert('You have successfully created subscription ' + data.subscriptionID);
18 }
19}).render('#paypal-button-container');

onApprove

Captures the funds from the transaction and shows a message that tells the buyer the payment was successful. The method is called after the buyer approves the transaction on the paypal.com website.

Actions

capture(): A promise returning the order details.

1paypal.Buttons({
2 createOrder() {
3 // This function sets up the details of the transaction, including the amount and line item details.
4 return fetch("/my-server/create-paypal-order", {
5 method: "POST",
6 headers: {
7 "Content-Type": "application/json",
8 },
9 body: JSON.stringify({
10 cart: [
11 {
12 sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
13 quantity: "YOUR_PRODUCT_QUANTITY"
14 }
15 ]
16 })
17 });
18 },
19 onApprove(data) {
20 // This function captures the funds from the transaction.
21 return fetch("/my-server/capture-paypal-order", {
22 method: "POST",
23 body: JSON.stringify({
24 orderID: data.orderID
25 })
26 })
27 .then((response) => response.json())
28 .then((details) => {
29 // This function shows a transaction success message to your buyer.
30 alert('Transaction completed by ' + details.payer.name.given_name);
31 });
32 }
33}).render('#paypal-button-container');
34//This function shows payment buttons on your web page.

For the list of order details you receive from /my-server/capture-paypal-order, see capture payment for order in the Orders API reference.

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: The ID of the order.

1paypal.Buttons({
2 onCancel(data) {
3 // Show a cancel page, or return to cart
4 }
5}).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:

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

Note: This error handler is a catch-all. Errors at this point aren't 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 selected. See the funding sources in the standalone buttons guide.

1<p id="error" class="hidden">Click the checkbox</p>
2<label><input id="check" type="checkbox" required> Click here to continue</label>
3
4<script>
5 paypal.Buttons({
6
7 // onInit is called when the button first renders
8 onInit(data, actions) {
9
10 // Disable the buttons
11 actions.disable();
12
13 // Listen for changes to the checkbox
14 document.querySelector('#check')
15 .addEventListener('change', function(event) {
16
17 // Enable or disable the button when it is checked or unchecked
18 if (event.target.checked) {
19 actions.enable();
20 } else {
21 actions.disable();
22 }
23 });
24 },
25
26 // onClick is called when the button is selected
27 onClick() {
28
29 // Show a validation error if the checkbox isn't checked
30 if (!document.querySelector('#check').checked) {
31 document.querySelector('#error').classList.remove('hidden');
32 }
33 }
34
35 }).render('#paypal-button-container');
36</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.

1// Loop over each funding source / payment method
2paypal.getFundingSources().forEach(function(fundingSource) {
3
4 // Initialize the buttons
5 var button = paypal.Buttons({
6 fundingSource: fundingSource
7 });
8
9 // Check if the button is eligible
10 if (button.isEligible()) {
11
12 // Render the standalone button for that funding source
13 button.render('#paypal-button-container');
14 }
15});

paypal.Buttons().render( container )

Renders the buttons in the defined container selector.

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

onShippingChange

Deprecated. See onShippingAddressChange and onShippingOptionsChange.

While the buyer is on the PayPal site, you can update their shopping cart to reflect the shipping address they selected 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 don't support their shipping address.

Availability: The onShippingChange function isn't 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 or 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, such as USD.
      • value: String-formatted decimal format, such as 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 don't need to make any changes to the buyer’s cart.
  • reject: Indicates to PayPal that you won't 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:
1paypal.Buttons({
2 onShippingChange(data, actions) {
3 if (data.shipping_address.country_code !== 'US') {
4 return actions.reject();
5 }
6
7 return actions.resolve();
8 }
9}).render('#paypal-button-container');
  1. This example shows a more complex situation in which a state has free shipping, but flat-rate shipping is the standard for the rest of the US:
1paypal.Buttons({
2 onShippingChange(data, actions) {
3 // Reject non-US addresses
4 if (data.shipping_address.country_code !== 'US') {
5 return actions.reject();
6 }
7
8 // Patch the shipping amount
9 return fetch("/my-server/patch-paypal-order", {
10 method: "PATCH",
11 body: JSON.stringify(
12 {
13 shippingAddress: data.shipping_address
14 })
15 })
16 .then((response) => response.json());
17 }
18}).render('#paypal-button-container');

onShippingAddressChange

While the buyer is on the PayPal site, you can update their shopping cart to reflect the shipping address they selected 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 don't support their shipping address.

Availability: The onShippingAddressChange function isn't compatible with Subscriptions.

Data attributes

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

  • errors: Errors to show to the user.
    • ADDRESS_ERROR: "Your order can't be shipped to this address."
    • COUNTRY_ERROR: "Your order can't be shipped to this country."
    • STATE_ERROR: "Your order can't be shipped to this state."
    • ZIP_ERROR: "Your order can't be shipped to this zip."
  • orderID: An ID that represents an order.
  • paymentID: An ID that represents a payment.
  • paymentToken: An ID or token that represents a resource.
  • shippingAddress: The buyer's selected city, state, country, and postal code.
    • city: Shipping address city.
    • countryCode: Shipping address country.
    • postalCode: Shipping address ZIP code or postal code.
    • state: Shipping address state or province.

Actions

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

  • buildOrderPatchPayload: Returns a payload for patching an order using the Orders V2 API. Accepts the following parameters:
    • discount: A discount amount to subtract from the final total.
    • handling: A handling amount to add to the final total.
    • insurance: An insurance amount to add to the final total.
    • itemTotal: An item total to add to the final total.
    • shippingOptions: An array of shipping options with the selected option amount to add to the final total.
    • shippingDiscount: A shipping discount amount to subtract from the final total.
    • taxTotal: A tax total amount to add to the final total.
  • reject: Indicates to PayPal that you won't support the shipping address provided by the buyer.

Examples

  1. This example shows how to reject international transactions using actions.reject():
1paypal.Buttons({
2 onShippingAddressChange(data, actions) {
3 if (data.shippingAddress.countryCode !== 'US') {
4 return actions.reject(data.errors.COUNTRY_ERROR);
5 }
6 }
7}).render('#paypal-button-container');
  1. This example shows how to build an order patch payload using actions.buildOrderPatchPayload():
  1. Frontend (HTML)
  2. Backend (Node.js example)
1<!DOCTYPE html>
2<html>
3 <head>
4 <meta name="viewport" content="width=device-width, initial-scale=1">
5 </head>
6 <body>
7 <!-- Replace "test" with your own sandbox Business account app client ID -->
8 <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
9 <!-- Set up a container element for the button -->
10 <div id="paypal-button-container"></div>
11 <script>
12 paypal.Buttons({
13 async onShippingAddressChange(data, actions) {
14 const body = await actions.buildOrderPatchPayload({
15 discount: "5.00",
16 handling: "7.00",
17 insurance: "9.00",
18 itemTotal: "135.00",
19 shippingOptions: [
20 {
21 amount: {
22 currencyCode: "USD",
23 value: "10.47",
24 },
25 label: "3 Day Shipping",
26 selected: true,
27 type: "SHIPPING",
28 },
29 {
30 amount: {
31 currencyCode: "USD",
32 value: "110.89",
33 },
34 label: "Overnight Shipping",
35 selected: false,
36 type: "SHIPPING",
37 },
38 ],
39 shippingDiscount: "1.50",
40 taxTotal: "10.00",
41 });
42 const options = {
43 method: "POST",
44 headers: {
45 "Content-Type": "application/json"
46 },
47 body: JSON.stringify(body)
48 };
49 // send the order patch payload to the server (HOSTNAME) endpoint responsible for patching the order using the Orders V2 API
50 return fetch(
51 '${HOSTNAME}/api/order/${data.orderID}/addressChange',
52 options
53 );
54 }
55 }).render('#paypal-button-container');
56 </script>
57 </body>
58</html>

onShippingOptionsChange

This callback is triggered any time the user selects a new shipping option. You can use the callback to:

  • Validate that you support the shipping method.
  • Update shipping costs.
  • Change the line items in the cart.
  • Inform the buyer that you don't support their shipping method.

Availability: The onShippingOptionsChange function isn't compatible with Subscriptions.

Data attributes

data: An object containing the payer’s selected shipping option. Consists of the following properties:

  • errors: Errors to show to the payer.
    • METHOD_UNAVAILABLE: "The shipping method you selected is unavailable. To continue, choose another way to get your order."
    • STORE_UNAVAILABLE: "Part of your order isn't available at this store."
  • orderID: An ID that represents an order.
  • paymentID: An ID that represents a payment.
  • paymentToken: An ID or token that represents a resource.
  • selectedShippingOption: Shipping option selected by the payer.
    • id: Custom shipping method ID.
    • label: Custom shipping method label.
    • selected: Set to true by PayPal when selected by the buyer.
    • type: Shipping method type (SHIPPING or PICKUP).
    • amount: Additional cost for this method.
      • currencyCode: ISO currency code, such as USD.
      • value: String-formatted decimal format, such as 1.00.

Actions

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

  • buildOrderPatchPayload: Returns a payload for patching an order using the Orders V2 API. Accepts the following parameters:
    • discount: A discount amount to subtract from the final total.
    • handling: A handling amount to add to the final total.
    • insurance: An insurance amount to add to the final total.
    • itemTotal: An item total to add to the final total.
    • shippingOption: The selected shipping option with the amount to add to the final total.
    • shippingDiscount: A shipping discount amount to subtract from the final total.
    • taxTotal: A tax total amount to add to the final total.
  • reject: Indicates to PayPal that you won't support the shipping method selected by the buyer.

Customize shipping options

Add support for multiple shipping options when buyers make changes to their shipping information.

Examples

  1. This example shows how to disable store pickup using actions.reject():
1paypal.Buttons({
2 onShippingOptionsChange(data, actions) {
3 if (data.selectedShippingOption.type === 'PICKUP') {
4 return actions.reject(data.errors.STORE_UNAVAILABLE);
5 }
6 }
7}).render('#paypal-button-container');
  1. This example shows how to build an order patch payload using actions.buildOrderPatchPayload():
  1. Frontend (HTML)
  2. Backend (Node.js example)
1<!DOCTYPE html>
2<html>
3 <head>
4 <meta name="viewport" content="width=device-width, initial-scale=1">
5 </head>
6 <body>
7 <!-- Replace "test" with your own sandbox Business account app client ID -->
8 <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
9 <!-- Set up a container element for the button -->
10 <div id="paypal-button-container"></div>
11 <script>
12 paypal.Buttons({
13 async onShippingOptionsChange(data, actions) {
14 const body = await actions.buildOrderPatchPayload({
15 discount: "1.00",
16 handling: "6.50",
17 insurance: "14.00",
18 itemTotal: "145.00",
19 shippingOption: data.selectedShippingOption,
20 shippingDiscount: "5.00",
21 taxTotal: "37.00",
22 });
23 const options = {
24 method: "POST",
25 headers: {
26 "Content-Type": "application/json"
27 },
28 body: JSON.stringify(body)
29 };
30 // send the order patch payload to the server (HOSTNAME) endpoint responsible for patching the order using the Orders V2 API
31 return fetch(
32 '${HOSTNAME}/api/order/${data.orderID}/optionsChange',
33 options
34 );
35 }
36 }).render('#paypal-button-container');
37 </script>
38 </body>
39</html>

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 selects a radio button. See Display other payment methods.

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

paypal.Marks(options)

paypal.Marks().isEligible

1<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.

1// Loop over each funding source / payment method
2paypal.getFundingSources().forEach(function(fundingSource) {
3
4 // Initialize the marks
5 var mark = paypal.Marks({
6 fundingSource: fundingSource
7 });
8
9 // Check if the mark is eligible
10 if (mark.isEligible()) {
11
12 // Render the standalone mark for that funding source
13 mark.render('#paypal-mark-container');
14 }
15});

paypal.Marks().render( container )

Renders the radio buttons that are passed in container selector.

1paypal.Marks().render('#paypal-marks-container');
1<!-- Render the radio buttons and marks -->
2<label>
3 <input type="radio" name="payment-option" value="paypal" checked>
4 <div id="paypal-marks-container"></div>
5</label>
6
7<label>
8 <input type="radio" name="payment-option" value="alternate">
9</label>
10
11<div id="paypal-buttons-container"></div>
12<div id="alternate-button-container">
13 <button>Pay with a different method</button>
14</div>
15
16<script>
17 // Render the PayPal marks
18 paypal.Marks().render('#paypal-marks-container');
19
20 // Render the PayPal buttons
21 paypal.Buttons().render('#paypal-buttons-container');
22
23 // Listen for changes to the radio buttons
24 document.querySelectorAll('input[name=payment-option]')
25 .forEach(function (el) {
26 el.addEventListener('change', function (event) {
27
28 // If PayPal is selected, show the PayPal button
29 if (event.target.value === 'paypal') {
30 document.body.querySelector('#alternate-button-container')
31 .style.display = 'none';
32 document.body.querySelector('#paypal-buttons-container')
33 .style.display = 'block';
34 }
35
36 // If alternate funding is selected, show a different button
37 if (event.target.value === 'alternate') {
38 document.body.querySelector('#alternate-button-container')
39 .style.display = 'block';
40 document.body.querySelector('#paypal-buttons-container')
41 .style.display = 'none';
42 }
43 });
44 });
45
46 // Hide non-PayPal button by default
47 document.body.querySelector('#alternate-button-container')
48 .style.display = 'none';
49</script>

Card fields

Use PayPal-hosted card fields to accept and save credit and debit cards without handling card information. PayPal handles all security and compliance issues associated with processing cards.

Request: Initialize cardFields

Initialize the card fields component by creating an instance of paypal.CardFields:

1const cardFields = paypal.CardFields({
2 style,
3 createOrder,
4 onApprove
5});

Options

You can pass the following options when instantiating the card fields component:

OptionDescriptionRequired
createOrderThe callback to create the order on your server.Yes
onApproveThe callback to capture the order on your server.Yes
onErrorThe callback to catch errors during checkout.Yes
inputEventsAn object containing callbacks for an input event.No
styleA custom style object.No

createOrder

Creates an order ID for any case involving a purchase. This callback is called whenever the payer submits card fields.

Request: Create order from server

1const createOrder = (data, actions) => {
2 return fetch('/api/paypal/order', {
3 method: 'POST'
4 }).then(res => {
5 return res.json();
6 }).then(json => {
7 return json.orderID;
8 });
9};

Set up your server to call the Create Order API. The button pressed on the client side determines the payment source sent. In the following sample, the payer opted to send their card as a payment source.

Request: Create order with a card as the payment source

1curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders \n -H "Content-Type: application/json" \n -H "Authorization: Bearer ACCESS-TOKEN" \n -d '{
2 "intent": "CAPTURE",
3 "purchase_units": [
4 {
5 "amount": {
6 "currency_code": "USD",
7 "value": "100.00"
8 }
9 }
10 ],
11}

Response

Pass the order.id to the JavaScript SDK to update the order with the number, CVV, and expiration date entered.

1{
2 "id": "5O190127TN364715T",
3 "status": "CREATED",
4 "intent": "CAPTURE",
5 "purchase_units": [
6 {
7 "reference_id": "d9f80740-38f0-11e8-b467-0ed5f89f718b",
8 "amount": {
9 "currency_code": "USD",
10 "value": "100.00"
11 }
12 }
13 ],
14 "create_time": "2022-10-03T11:18:49Z",
15 "links": [
16 {
17 "href": "https://api-m.paypal.com/v2/checkout/orders/5O190127TN364715T",
18 "rel": "self",
19 "method": "GET"
20 },
21 {
22 "href": "https://www.paypal.com/checkoutnow?token=5O190127TN364715T",
23 "rel": "approve",
24 "method": "GET"
25 },
26 {
27 "href": "https://api-m.paypal.com/v2/checkout/orders/5O190127TN364715T",
28 "rel": "update",
29 "method": "PATCH"
30 },
31 {
32 "href": "https://api-m.paypal.com/v2/checkout/orders/5O190127TN364715T/capture",
33 "rel": "capture",
34 "method": "POST"
35 }
36 ]
37 }

onApprove

Signals that a payer approved a purchase by submitting a card or selecting a button.

Request: Capture order from server

Set up your server to call the Capture Order API, then run the following script to capture an order from your server:

1const onApprove = (data, actions) => {
2 return fetch('/api/paypal/order/capture', {
3 method: 'POST',
4 body: JSON.stringify({
5 orderID: data.orderID
6 })
7 }).then(res => {
8 return res.json();
9 }).then(json => {
10 // Show a success page
11 });
12};

Request

1curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders/<order_id>/capture
2 -H "Content-Type: application/json"
3 -H "Authorization: Bearer ACCESS-TOKEN"

Response

1{
2 "id": "some_id",
3 "status": "COMPLETED",
4 "payment_source": {
5 "card": {
6 "brand": "VISA",
7 "last_digits": "1111",
8 "type": "CREDIT"
9 }
10 },
11 "purchase_units": [
12 {
13 "reference_id": "reference_id",
14 "payments": {
15 "authorizations": [
16 {
17 "id": "id",
18 "status": "CREATED",
19 "amount": {
20 "currency_code": "USD",
21 "value": "100.00"
22 },
23 "seller_protection": {
24 "status": "ELIGIBLE",
25 "dispute_categories": [
26 "ITEM_NOT_RECEIVED",
27 "UNAUTHORIZED_TRANSACTION"
28 ]
29 },
30 "expiration_time": "2022-10-04T14:37:39Z",
31 "links": [
32 {
33 "href": "https://api-m.paypal.com/v2/payments/authorizations/5O190127TN364715T",
34 "rel": "self",
35 "method": "GET"
36 },
37 {
38 "href": "https://api-m.paypal.com/v2/payments/authorizations/5O190127TN364715T/capture",
39 "rel": "capture",
40 "method": "POST"
41 },
42 {
43 "href": "https://api-m.paypal.com/v2/payments/authorizations/5O190127TN364715T/void",
44 "rel": "void",
45 "method": "POST"
46 },
47 {
48 "href": "https://api-m.paypal.com/v2/checkout/orders/5O190127TN364715T",
49 "rel": "up",
50 "method": "GET"
51 }
52 ]
53 }
54 ]
55 }
56 }
57 ],
58 "payer": {
59 "name": {
60 "given_name": "Firstname",
61 "surname": "Lastname"
62 },
63 "email_address": "payer@example.com",
64 "payer_id": "QYR5Z8XDVJNXQ"
65 },
66 "links": [
67 {
68 "href": "https://api-m.paypal.com/v2/checkout/orders/5O190127TN364715T",
69 "rel": "self",
70 "method": "GET"
71 }
72 ]
73}

onError

Handles any errors that occur while the payer submits the form.

1const cardFields = paypal.CardFields({
2 // ...
3 onError = (error) => {
4 // Handle the error object
5 console.error(error);
6 },
7 // ...
8});

Card field properties

The following card field properties are used to capture a payment. Use the render() method to render these instances to the DOM.

PropertyTypeField createdRequired
CVVFieldFunctionCard CVV or CID, a 3 or 4-digit codeYes
ExpiryFieldFunctionCard expiration dateYes
NameFieldFunctionName for the cardNo
NumberFieldFunctionCard numberYes

Card field options

Customize event callbacks or the style of each field with the following options:

PropertyTypeDescriptionRequired
inputEventsObject inputEventsAn object containing callbacks for when a specified input event occurs for a field.No
styleObject style guideStyle a field with supported CSS properties.No
placeholderStringEach card field has a default placeholder text. Pass a placeholder object to customize this text.No

Example: Card field properties

1const cardNameContainer = document.getElementById("card-name-field-container");
2const nameField = cardField.NameField({
3 placeholder: "Enter your full name as it appears on your card",
4inputEvents: {
5 onChange: (event)=> {
6 console.log("returns a stateObject", event);
7 }
8},
9style: {
10 ".invalid": {
11 "color": "purple",
12 }
13}
14});
15 });
16nameField.render(cardNameContainer);
17const cardNumberContainer = document.getElementById("card-number-field-container");
18const numberField = cardField.NumberField(/*options*/);
19numberField.render(cardNumberContainer);
20const cardExpiryContainer = document.getElementById("card-expiry-field-container");
21const expiryField = cardField.ExpiryField(/*options*/);
22expiryField.render(cardExpiryContainer);
23const cardCvvContainer = document.getElementById("card-cvv-field-container");
24const cvvField = cardField.CVVField(/*options*/);
25cvvField.render(cardCvvContainer);

Style card fields

Change the layout, width, height, and outer styling of the card fields. Modify the elements you supply as containers with your current stylesheets. For example, input: { border: 1px solid #333; }.

Supported CSS properties

The CSS properties listed are the only properties supported in the advanced credit and debit card payments configuration. If you specify an unsupported CSS property, a warning is logged to the browser console.

  • appearance
  • color
  • direction
  • font
  • font-family
  • font-size
  • font-size-adjust
  • font-stretch
  • font-style
  • font-variant
  • font-variant-alternates
  • font-variant-caps
  • font-variant-east-asian
  • font-variant-ligatures
  • font-variant-numeric
  • font-weight
  • letter-spacing
  • line-height
  • opacity
  • outline
  • padding
  • padding-bottom
  • padding-left
  • padding-right
  • padding-top
  • text-shadow
  • transition
  • -moz-appearance
  • -moz-osx-font-smoothing
  • -moz-tap-highlight-color
  • -moz-transition
  • -webkit-appearance
  • -webkit-osx-font-smoothing
  • -webkit-tap-highlight-color
  • -webkit-transition

Style parent fields

Pass a style object to the parent cardField component to apply the object to every field.

1const cardStyle = {
2 'input': {
3 'font-size': '16px',
4 'font-family': 'courier, monospace',
5 'font-weight': 'lighter',
6 'color': '#ccc',
7 },
8 '.invalid': {
9 'color': 'purple',
10 },
11};
12const cardField = paypal.CardFields({
13 style: cardStyle
14});

Style individual fields

Pass a style object to an individual card field to apply the object to that field only. This overrides any object passed through a parent component.

1const nameFieldStyle = {
2 'input': {
3 'color': 'blue'
4 }
5 '.invalid': {
6 'color': 'purple'
7 },
8};
9const nameField = cardField.NameField({
10 style: nameFieldStyle
11}).render('#card-name-field-container');

inputEvents

You can pass an inputEvents object into a parent cardField component or each card field individually.

Pass an inputEvents object to the parent cardField component to apply the object to every field.

Pass an inputEvents object to an individual card field to apply the object to that field only. This overrides any object passed through a parent component.

Supported input event callbacks

You can pass the following callbacks to the inputEvents object:

Event NameDescription
onChangeCalled when the input in any field changes.
onFocusCalled when any field gets focus.
onBlurCalled when any field loses focus.
onInputSubmitRequestCalled when a payer submits the field.

Example: inputEvents into parent component

Pass the inputEvents object into the parent CardFields component:

1const cardField = paypal.CardFields({
2 inputEvents: {
3 onChange: function(data) => {
4 // Do something when an input changes
5 },
6 onFocus: function(data) => {
7 // Do something when a field gets focus
8 },
9 onBlur: function(data) => {
10 // Do something when a field loses focus
11 }
12 onInputSubmitRequest: function(data) => {
13 if (data.isFormValid) {
14 // Submit the card form for the payer
15 } else {
16 // Inform payer that some fields aren't valid
17 }
18 }
19 }
20})

Example: inputEvents into individual component

Pass the inputEvents object into each individual field component:

1const cardField = paypal.CardFields(/* options */)
2const nameField = cardField.NameField({
3 inputEvents: {
4 onChange: function(data) => {
5 // Do something when the input of only the name field changes
6 },
7 onFocus: function(data) => {
8 // Do something when only the name field gets focus
9 },
10 onBlur: function(data) => {
11 // Do something when only name field loses focus
12 }
13 onInputSubmitRequest: function(data) => {
14 if (data.isFormValid) {
15 // Submit the card form for the payer
16 } else {
17 // Inform payer that some fields aren't valid
18 }
19 }
20 }
21});

Sample state object

Each of the event callbacks returns a state object similar to the following example:

1data: {
2 cards: [{code: {name: 'CVV', size: 3}, niceType: "Visa", type: "visa"}]
3 emittedBy: "number", // Not returned for getState()
4 isFormValid: false,
5 errors: ["INVALID_CVV"]
6 fields: {
7 cardCvvField: {
8 isFocused: false,
9 isEmpty: true,
10 isValid: false,
11 isPotentiallyValid: true,
12 },
13 cardNumberField: {
14 isFocused: true,
15 isEmpty: false,
16 isValid: false,
17 isPotentiallyValid: true,
18 },
19 cardNameField: {
20 isFocused: false,
21 isEmpty: true,
22 isValid: false,
23 isPotentiallyValid: true,
24 },
25 cardExpiryField: {
26 isFocused: false,
27 isEmpty: true,
28 isValid: false,
29 isPotentiallyValid: true,
30 },
31 },
32}

Validate individual fields

Validate individual fields when an input event occurs:

1const cardFields = paypal.CardFields({/* options */});
2let cardContainer = document.getElementById("#card-number-field-container")
3const cardNumberField = cardFields.NumberField({
4 // Add valid or invalid class when the validation changes on the field
5 inputEvents: {
6 onChange: (data) => {
7 cardContainer.className = data.fields.cardNumberField.isValid ? 'valid' : 'invalid';
8 }
9 }
10})

Validate entire card form

Validate an entire card form when an input event occurs:

1const formContainer = document.getElementById("form-container")
2const cardFields = paypal.CardFields({
3 inputEvents: {
4 onChange: (data) => {
5 formContainer.className = data.isFormValid ? 'valid' : 'invalid'
6 }
7 }
8});

Methods on parent card fields

The following methods are supported on parent card fields:

  • getState()
  • isEligible()
  • submit()

getState() -> {promise | void}

Returns a promise that resolves into a stateObject. Includes the state of all fields, possible card types, and an array of errors.

Example

1const cardField = paypal.CardFields(/* options */)
2// ...
3// Render the card fields
4// ...
5cardFields.getState().then((data) => {
6 // Submit only if the current
7 // state of the form is valid
8 if (data.isFormValid) {
9 cardFields.submit().then(() => {
10 //Submit success
11 }).catch((error) => {
12 //Submit error
13 });
14 }
15});

isEligible() -> {Boolean}

Checks if a cardField instance can render based on configuration and business rules.

Example

1const cardField = paypal.CardFields(/* options */)
2if (cardFields.isEligible()) {
3 cardFields.NumberField().render("#card-number-field-container");
4 cardFields.CVVField().render("#card-cvv-field-container");
5 // ...
6}

submit() -> {promise | void}

Submits payment information.

1// Add click listener to merchant-supplied submit button
2// and call the submit function on the CardField component
3multiCardFieldButton.addEventListener("click", () => {
4 cardField.submit().then(() => {
5 console.log("Card Fields submit");
6 }).catch((err) => {
7 console.log("There was an error with card fields: ", err);
8 });
9});

Methods on individual card fields

The following methods are supported on individual card fields:

  • addClass()
  • clear()
  • focus()
  • removeAttribute()
  • removeClass()
  • render()
  • setAttribute()
  • setMessage()

addClass() -> {promise | void}

Adds a class to a field. Use this method to update field styles when events occur elsewhere during checkout.

1const cardField = paypal.CardFields(/* options */)
2const numberField = cardField.NumberField(/* options */)
3numberField.addClass("purple");
4numberField.render(cardNumberContainer);

clear() -> {void}

Clears the value of the field.

1const cardField = paypal.CardFields(/* options */)
2const nameField = cardField.NameField(/* options */);
3nameField.render(cardNameContainer);
4nameField.clear();

focus() -> {void}

Focuses the field.

1const cardField = paypal.CardFields(/* options */)
2const nameField = cardField.NameField(/* options */)
3nameField.render(cardNameContainer);
4nameField.focus();

removeAttribute() -> {promise | void}

Removes an attribute from a field where called.

Supported attributes to remove

You can remove the following attributes with removeAttribute:

  • aria-invalid
  • aria-required
  • disabled
  • placeholder
1const cardField = paypal.CardFields(/* options */)
2const numberField = cardField.NumberField(/* options */)
3numberField.render(cardNumberContainer);
4numberField.removeAttribute("placeholder");

removeClass() -> {promise | void}

Pass the class name as a string in removeClass to remove a class from a field. Use this method to update field styles when events occur elsewhere in the checkout flow.

1const cardField = paypal.CardFields(/* options */)
2const numberField = cardField.NumberField(/* options */)
3numberField.render(cardNumberContainer);
4numberField.removeClass("purple");

render() -> {promise | void}

Renders the individual card fields to the DOM for checkout.

Pass the HTML element reference or CSS selector string for the input field.

1const cardNumberContainer = document.getElementById("card-number-field-container");
2const cardField = paypal.CardFields(/* options */)
3cardField.NumberField(/* options */).render(cardNumberContainer);
4// OR use a selector string
5cardField.NumberField(/*options*/).render("#card-number-field-container")

setAttribute() -> {promise | void}

Sets the supported attributes and values of a field. Pass in attributes and values as strings.

1const cardField = paypal.CardFields(/* options */)
2const nameField = cardField.NameField(/* options */)
3nameField.setAttribute("placeholder", "Enter your full name");
4nameField.render(cardNameContainer);

setMessage() -> {void}

Sets a message on a field for screen readers. Pass the message as a string in setMessage.

1const cardField = paypal.CardFields(/* options */)
2const nameField = cardField.NameField(/* options */)
3nameField.render(cardNameContainer);
4nameField.setMessage("Enter your full name");

Type definitions

cardSecurityCode

Information about the security code for a card.

PropertyTypeDescription
nameStringThe name of a security code for a card. Valid values are CVV, CID, and CVC.
sizeNumberThe expected length of the security code, typically 3 or 4 digits.

cardType

Information about the card type sent in the cards array as a part of the stateObject.

PropertyTypeDescription
typeStringThe code-readable card type. Valid values are:
  • american-express
  • diners-club
  • discover
  • jcb
  • maestro
  • mastercard
  • unionpay
  • visa
  • elo
  • hiper, hipercard
codeObject cardSecurityCodeContains data about the card brand's security code requirements. For example, on a Visa card, the CVV is 3 digits. On an American Express card, the CID is 4 digits.
niceTypeStringThe human-readable card type. Valid values are:
  • American Express
  • Diner Club
  • discover
  • JCB
  • Maestro
  • Mastercard
  • UnionPay
  • Visa
  • Elo
  • Hiper,Hipercard

cardFieldData

Field data for card payments is sent for each card field in the stateObject.

PropertyTypeDescription
isFocusedBooleanShows whether the input field is currently focused.
isEmptyBooleanShows whether the user has entered a value in the input.
isPotentiallyValidBooleanShows whether the current input can be valid. For example, if a payer enters 41 for the card number, the input can become valid. However, if the payer enters 4x, the input can't become valid.
isValidBooleanShows whether the input is valid and can be submitted.

stateObject

PropertyTypeDescription
cardsArray of cardTypeReturns an array of potential cards. If the card type has been determined, the array contains only 1 card.
emittedByStringThe name of the field associated with an event. emittedBy isn't included if returned by getState. Valid values are "name","number", "cvv", and "expiry".
errorsArrayArray of card fields that are currently not valid. Potential values are "INELIGIBLE_CARD_VENDOR","INVALID_NAME", "INVALID_NUMBER", "INVALID_EXPIRY" or "INVALID_CVV".
isFormValidBooleanShows whether the form is valid.
fieldsObjectContains data about the field in the context of the event. Valid values are "cardNameField", "cardCvvField", "cardNumberField" and "cardExpiryField". Each of these keys contain an object of type cardFieldData.

Full example

The following sample shows how a full hosted card fields script might show up in HTML:

1<html>
2 <head>
3 <meta charset="UTF-8">
4 <title>Checkout Page</title>
5 </head>
6 <body>
7 <div id="checkout-form">
8 <div id="card-name-field-container"></div>
9 <div id="card-number-field-container"></div>
10 <div id="card-expiry-field-container"></div>
11 <div id="card-cvv-field-container"></div>
12 <button id="multi-card-field-button" type="button">Pay now with Card Fields</button>
13 </div>
14 </body>
15 <script src="https://www.paypal.com/sdk/js?client-id=<your-client-id>&components=card-fields"></script>
16 <script>
17 // Custom styles object (optional)
18 const styleObject = {
19 input: {
20 "font-size": "16 px",
21 "font-family": "monospace",
22 "font-weight": "lighter",
23 color: "blue",
24 },
25 ".invalid": {
26 color: "purple",
27 },
28 ":hover": {
29 color: "orange",
30 },
31 ".purple": {
32 color: "purple",
33 },
34 };
35 // Create the card fields component and define callbacks
36 const cardField = paypal.CardFields({
37 style: styleObject,
38 createOrder: function (data, actions) {
39 return fetch("/api/paypal/order/create/", {
40 method: "post",
41 })
42 .then((res) => {
43 return res.json();
44 })
45 .then((orderData) => {
46 return orderData.id;
47 });
48 },
49 onApprove: function (data, actions) {
50 const { orderID } = data;
51 return fetch('/api/paypal/orders/${orderID}/capture/', {
52 method: "post",
53 })
54 .then((res) => {
55 return res.json();
56 })
57 .then((orderData) => {
58 // Redirect to success page
59 });
60 },
61 inputEvents: {
62 onChange: function (data) {
63 // Handle a change event in any of the fields
64 },
65 onFocus: function(data) {
66 // Handle a focus event in any of the fields
67 },
68 onBlur: function(data) {
69 // Handle a blur event in any of the fields
70 },
71 onInputSubmitRequest: function(data) {
72 // Handle an attempt to submit the entire card form
73 // while focusing any of the fields
74 }
75 },
76 });
77 // Define the container for each field and the submit button
78 const cardNameContainer = document.getElementById("card-name-field-container"); // Optional field
79 const cardNumberContainer = document.getElementById("card-number-field-container");
80 const cardCvvContainer = document.getElementById("card-cvv-field-container");
81 const cardExpiryContainer = document.getElementById("card-expiry-field-container");
82 const multiCardFieldButton = document.getElementById("multi-card-field-button");
83 // Render each field after checking for eligibility
84 if (cardField.isEligible()) {
85 const nameField = cardField.NameField();
86 nameField.render(cardNameContainer);
87 const numberField = cardField.NumberField();
88 numberField.render(cardNumberContainer);
89 const cvvField = cardField.CVVField();
90 cvvField.render(cardCvvContainer);
91 const expiryField = cardField.ExpiryField();
92 expiryField.render(cardExpiryContainer);
93 // Add click listener to the submit button and call the submit function on the CardField component
94 multiCardFieldButton.addEventListener("click", () => {
95 cardField
96 .submit()
97 .then(() => {
98 // Handle a successful payment
99 })
100 .catch((err) => {
101 // Handle an unsuccessful payment
102 });
103 });
104 }
105 </script>
106</html>

Funding eligibility

The payment buttons automatically render all eligible buttons in a single location on your page by default.

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 show up.

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

paypal.rememberFunding( fundingSources )

When the customer chooses to save a funding source, that source is stored and available to use for future payments.

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

paypal.getFundingSources

Loop over funding sources and payment methods.

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

paypal.isFundingEligible( fundingSource )

Check for funding eligibility from current funding sources.

1paypal.isFundingEligible(fundingSource);

Funding

This table includes the available funding sources. The payment buttons automatically render all eligible buttons in a single location on your page by default. If you need to override this, you can specify the buttons you want 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 (Legacy) *

* Important: Sofort will be sunset on April 18, 2024. PayPal will not support Sofort payments starting April 19, 2024. Offer your users PayPal wallet and other alternative payment methods. Learn more.

Messages

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

See also