Skip to main content
Use the PayPal v6 JavaScript SDK to integrate PayPal, Venmo, Pay Later, and other payment methods into web applications. This reference covers payment eligibility checking, session management, callback handling, and web components.

Check payment eligibility

Before displaying payment buttons to your buyers, check which payment methods are available for the current transaction. Eligibility depends on various factors including the buyer’s location, currency, merchant configuration, and transaction amount.

sdkInstance.findEligibleMethods(options?)

Use findEligibleMethods to determine which payment methods are available for the current context. This method queries PayPal’s eligibility service and returns an object with methods to check specific payment options.

Parameters

ParameterRequiredDescription
currencyCodeno

string. The three-letter ISO 4217 currency code for the transaction (e.g., “USD”, “EUR”, “GBP”). This affects payment method availability, especially for Pay Later options which have currency restrictions. Default: “USD”

countryCodeno

string. The two-letter ISO 3166-1 alpha-2 country code representing the buyer’s country. This determines regional payment method availability. For example, Venmo is only available in the US. If not specified, the SDK attempts to detect the buyer’s country.

amountno

string. The transaction amount as a string (e.g., “99.99”). The amount affects Pay Later eligibility, as different financing options have minimum and maximum amount thresholds.

Returns

Returns a Promise that resolves to an EligiblePaymentMethods object with methods to check and retrieve payment method information. The returned object provides these methods:
  • isEligible(method) - Check if a specific payment method is available
  • getDetails(method) - Get additional information about a payment method

Example

// Check with default settings
const paymentMethods = await sdkInstance.findEligibleMethods();

// Check with specific currency and amount
const paymentMethods = await sdkInstance.findEligibleMethods({
  currencyCode: "USD",
  countryCode: "US",
  amount: "125.00",
});

// Use the eligibility results
if (paymentMethods.isEligible("paypal")) {
  // Show PayPal button
}

if (paymentMethods.isEligible("paylater")) {
  const details = paymentMethods.getDetails("paylater");
  // Show Pay Later button with product-specific messaging
}

paymentMethods.isEligible(method)

Check whether a specific payment method is available for the current transaction.

Parameters

ParameterRequiredDescription
methodyes

string. The payment method identifier to check.

Supported values:

  • paypal — PayPal Checkout
  • venmo — Venmo (US only)
  • paylater — Pay Later / Pay in 4
  • credit — PayPal Credit

Returns

Returns true if the payment method is available, false otherwise.

Example

// Check individual payment methods
const canUsePayPal = paymentMethods.isEligible("paypal");
const canUseVenmo = paymentMethods.isEligible("venmo");

// Conditionally show buttons
if (paymentMethods.isEligible("venmo")) {
  document.getElementById("venmo-button").style.display = "block";
}

paymentMethods.getDetails(method)

Retrieve additional configuration details for a specific payment method. This is particularly useful for Pay Later and PayPal Credit, which require additional attributes for proper button rendering.

Parameters

ParameterRequiredDescription
methodyes

string. The payment method to get details for.

Currently returns details for:

  • paylater — Returns product code and country
  • credit — Returns country configuration

Returns

Returns an object with payment method-specific details. The structure varies by payment method. For Pay Later:
{
  productCode: string; // e.g., "PAY_IN_4"
  countryCode: string; // e.g., "US"
}
For PayPal Credit:
{
  countryCode: string; // e.g., "US"
}

Example

// Get Pay Later configuration
const payLaterDetails = paymentMethods.getDetails("paylater");
const button = document.querySelector("paylater-button");
button.productCode = payLaterDetails.productCode;
button.countryCode = payLaterDetails.countryCode;

// Get PayPal Credit configuration
const creditDetails = paymentMethods.getDetails("credit");

Creating payment sessions

Payment sessions manage the complete payment flow from initiation through completion. Each payment method has its own session creation method that returns a session object with methods to start and control the payment process.

sdkInstance.createPayPalOneTimePaymentSession(options)

Create a payment session for one-time PayPal payments. This session handles the complete PayPal Checkout flow, including payment approval, shipping address changes, and order updates.

Parameters

The options object configures callbacks that handle different stages of the payment flow. These callbacks allow you to respond to buyer actions and update your order accordingly.
ParameterRequiredDescription
onApproveyes

function(data). Called when the buyer approves the payment in the PayPal flow. This is where you should capture or authorize the payment on your server.

The function receives a data object containing:

  • orderId — The PayPal order ID to capture
  • payerId — The buyer’s PayPal payer ID

This function can return a Promise if you need to perform async operations like capturing the payment.

onCancelno

function(data). Called when the buyer cancels the payment flow by closing the PayPal window or clicking cancel.

The data object contains:

  • orderId — The order ID (if one was created)

Use this callback to:

  • Track abandoned checkouts
  • Re-enable your checkout button
  • Show a message to the buyer
onErrorno

function(error). Called when an error occurs during the payment flow. This includes network errors, validation errors, or payment failures.

The error object contains:

  • code — Error code for identifying the issue
  • message — Human-readable error description

Use this to display user-friendly error messages and log errors for debugging.

onShippingAddressChangeno

function(data). Called when the buyer changes their shipping address within the PayPal flow. This allows you to update shipping costs or restrict certain addresses.

The data object contains:

  • orderId — The current order ID
  • shippingAddress — The new address object

Return a Promise to update the order with new shipping costs. If you reject the Promise, the address change will be rejected.

onShippingOptionsChangeno

function(data). Called when the buyer selects a different shipping option (e.g., standard vs. express shipping).

The data object contains:

  • orderId — The current order ID
  • selectedShippingOption — The selected option details

Return a Promise to update the order total with the new shipping cost.

orderIdno

string. An existing PayPal order ID to use for this session. This allows you to create the order on your server before starting the payment flow (eager order creation).

If not provided, you’ll pass an order creation function to the start() method.

commitno

boolean. Controls the final button text in the PayPal flow:

  • true — Shows “Pay Now” (payment happens immediately)
  • false — Shows “Continue” (additional confirmation step)

Default: true

Returns

Returns a PaymentSession object with methods to control the payment flow.
interface PaymentSession {
  start(options?: StartOptions, orderPromise: Promise): Promise<void>;
  hasReturned(): boolean;
  resume(): Promise<void>;
}

Example

const paypalSession = sdkInstance.createPayPalOneTimePaymentSession({
  onApprove: async (data) => {
    // Capture the payment on your server
    const response = await fetch(`/api/orders/${data.orderId}/capture`, {
      method: "POST",
    });

    if (response.ok) {
      // Payment successful
      window.location.href = "/order/complete";
    } else {
      throw new Error("Capture failed");
    }
  },

  onShippingAddressChange: async (data) => {
    // Calculate new shipping cost based on address
    const shippingCost = await calculateShipping(data.shippingAddress);

    // Update the order with new shipping
    return fetch(`/api/orders/${data.orderId}/update-shipping`, {
      method: "PATCH",
      body: JSON.stringify({ shippingCost }),
    });
  },

  onCancel: (data) => {
    console.log("Payment cancelled", data);
    // Re-enable checkout button
    document.getElementById("checkout-btn").disabled = false;
  },

  onError: (error) => {
    console.error("Payment error:", error);
    // Show error message to buyer
    showErrorMessage("Payment failed. Please try again.");
  },
});

sdkInstance.createPayPalSavePaymentSession(options)

Create a session for saving PayPal as a payment method for future use (vaulting). This allows buyers to save their PayPal account for faster checkout in future purchases. The parameters and usage are identical to createPayPalOneTimePaymentSession, except the onApprove callback receives a billingToken instead of requiring immediate payment capture.

Example

const saveSession = sdkInstance.createPayPalSavePaymentSession({
  onApprove: async (data) => {
    // Save the billing token to your customer's profile
    await savePaymentMethod({
      customerId: currentUser.id,
      billingToken: data.billingToken,
      type: "paypal",
    });

    showSuccess("PayPal saved for future purchases");
  },
});

sdkInstance.createVenmoOneTimePaymentSession(options)

Create a payment session for Venmo payments (US only). Venmo provides a mobile-optimized payment experience for US buyers using their Venmo balance or linked payment methods. The parameters are identical to createPayPalOneTimePaymentSession. Venmo sessions support the same callbacks and flow options.

Example

const venmoSession = sdkInstance.createVenmoOneTimePaymentSession({
  onApprove: async (data) => {
    // Capture the Venmo payment
    await captureOrder(data.orderId);
  },
});

sdkInstance.createPayLaterOneTimePaymentSession(options)

Create a session for Pay Later financing options. Pay Later allows buyers to pay in installments (like Pay in 4) or over time with longer-term financing. The parameters are identical to createPayPalOneTimePaymentSession. Pay Later availability depends on transaction amount and buyer eligibility.

Example

const payLaterSession = sdkInstance.createPayLaterOneTimePaymentSession({
  onApprove: async (data) => {
    await captureOrder(data.orderId);
    // Buyer has been approved for Pay Later financing
  },
});

// Configure the Pay Later button with product details
const details = paymentMethods.getDetails("paylater");
const button = document.querySelector("paylater-button");
button.productCode = details.productCode;
button.countryCode = details.countryCode;

sdkInstance.createPayPalCreditOneTimePaymentSession(options)

Create a session for PayPal Credit payments (US only). PayPal Credit offers buyers a reusable line of credit for purchases.

sdkInstance.createGooglePayOneTimePaymentSession()

Create a session for Google Pay. Google Pay sessions have a different flow that integrates with the Google Pay API.

Returns

Returns a GooglePaySession object with specialized methods for Google Pay integration.
interface GooglePaySession {
  confirmOrder(options: {
    orderId: string,
    paymentMethodData: object,
  }): Promise<{ status: string }>;
}

sdkInstance.createApplePayOneTimePaymentSession()

Create a session for Apple Pay. Apple Pay sessions integrate with the browser’s Payment Request API on supported devices.

sdkInstance.createFastlane()

Create a Fastlane instance for accelerated guest checkout. Fastlane enables one-click checkout for recognized guests.

Returns

Returns a Promise that resolves to a Fastlane instance.

Example

const fastlane = await sdkInstance.createFastlane();
// Use fastlane instance for guest checkout acceleration

sdkInstance.createPayPalMessages(options?)

Display PayPal Messages to show financing options and promotional messaging to buyers. These messages dynamically update based on the transaction amount and buyer eligibility.

Parameters

ParameterRequiredDescription
amountno

number. The product or cart amount to display messaging for. Messages update dynamically based on this amount.

placementno

string. The page placement context for the messages. This affects message format and content.

Values: product, cart, checkout

styleno

object. Visual styling options for the messages, including layout and logo configuration.

paymentSession.start(options?, orderPromise)

Start the payment user experience. This method opens the payment interface using the specified presentation mode and begins the checkout flow.

Parameters

ParameterRequiredDescription
optionsno

object. Configuration for how the payment UI is presented.

options.presentationModeno

string. Controls how the payment interface is displayed to the buyer.

Available modes:

  • auto — SDK automatically selects the best experience
  • popup — Opens in a popup window (desktop)
  • modal — Creates an iframe overlay on the current page
  • redirect — Full page redirect to PayPal
  • payment-handler — Uses browser Payment Request API
  • direct-app-switch — Enables app switch to use PayPal app

Default: auto

The SDK will automatically fall back to alternative modes if the requested mode is unavailable.

options.autoRedirectno

object. Configuration for redirect mode behavior.

  • enabled (boolean) — Whether to automatically redirect or return the URL

Only applies when using presentationMode: “redirect”.

options.fullPageOverlayno

object. Controls the background overlay when using popup mode.

  • enabled (boolean) — Show/hide the page overlay

Default: enabled: true

options.loadingScreenno

object. Customize the loading screen text.

  • label (string) — Currently only supports “connecting”
orderPromiseyes

Promise. A Promise that creates or retrieves the PayPal order. This Promise should resolve to an object containing the orderId.

The order creation can happen asynchronously while the payment UI is loading, improving perceived performance.

Returns

For most presentation modes, returns a Promise that resolves when the payment flow completes or is cancelled. For redirect mode with autoRedirect.enabled: false, returns the redirect URL:
Promise<{ redirectURL: string }>

Example

// Basic usage with auto mode
await paymentSession.start(
  { presentationMode: "auto" },
  createOrder() // Returns Promise<{orderId: string}>
);

// Redirect mode with manual handling
const { redirectURL } = await paymentSession.start(
  {
    presentationMode: "redirect",
    autoRedirect: { enabled: false },
  },
  createOrder()
);

if (redirectURL) {
  // Manually redirect the buyer to a new tab
  // Only recommended for use cases where the v6 SDK is being wrapped in an iframe
  // Or usage with redirect flow for webview use cases
  window.location.href = redirectURL;
}

// Fallback pattern for incompatible browsers
const modes = [
  { mode: "popup", errorCode: "ERR_DEV_UNABLE_TO_OPEN_POPUP" },
  { mode: "modal", errorCode: null },
];

for (const { mode, errorCode } of modes) {
  try {
    await paymentSession.start({ presentationMode: mode }, createOrder());
    break; // Success
  } catch (error) {
    if (errorCode && error.code === errorCode) {
      continue; // Try next mode
    }
    throw error; // Unexpected error
  }
}

paymentSession.hasReturned()

Check if the current page load is a return from a redirect payment flow. Use this method on page load to detect and resume interrupted payment sessions.

Returns

Returns true if the buyer is returning from a PayPal redirect, false otherwise.

Example

// Runs on page load when SDK has finished downloading
async function onPayPalWebSdkLoaded() {
  try {
    const clientToken = await getBrowserSafeClientToken();
    const sdkInstance = await window.paypal.createInstance({
      clientToken,
      components: ["paypal-payments"],
      pageType: "checkout",
    });
    const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession(
      paymentSessionOptions
    );
    // Check to see if Buyer is returning from PayPal
    if (paypalPaymentSession.hasReturned()) {
      // Original callbacks will be triggered
      await paypalPaymentSession.resume();
    } else {
      setupPayPalButton(paypalPaymentSession);
    }
  } catch (error) {
    console.error(error);
  }
}

paymentSession.resume()

Resume a payment session after returning from a redirect flow. This method continues the payment process and triggers the appropriate callbacks based on the payment outcome.

Returns

Returns a Promise that resolves when the session is successfully resumed.

Handling callbacks

Callbacks allow you to respond to events during the payment flow. Each callback receives specific data about the event and can optionally return a Promise to perform asynchronous operations.

onApprove(data)

Called when the buyer successfully approves the payment. This is where you should capture or authorize the payment on your server.

Parameters

The callback receives a data object with the following properties:
PropertyTypeDescription
orderIdstringThe PayPal order ID that was approved. Use this to capture the payment on your server.
payerIdstringThe buyer’s PayPal payer ID. This identifies the PayPal account used for payment.
paymentIdstring | undefinedLegacy payment ID for backwards compatibility. Only present in certain flows.
billingTokenstring | undefinedToken for saving payment method. Only present when using save payment sessions.

Return value

The callback can optionally return a Promise. If a Promise is returned, the SDK waits for it to resolve before completing the flow.

Example

onApprove: async (data) => {
  console.log("Payment approved for order:", data.orderId);

  // Capture the payment on your server
  const response = await fetch(`/api/orders/${data.orderId}/capture`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
  });

  const captureData = await response.json();

  if (captureData.status === "COMPLETED") {
    // Redirect to success page
    window.location.href = `/order/success?id=${data.orderId}`;
  } else {
    throw new Error("Payment capture failed");
  }
};

onCancel(data)

Called when the buyer cancels the payment without completing it. This typically happens when they close the PayPal window or explicitly click a cancel button.

Parameters

PropertyTypeDescription
orderIdstring | undefinedThe order ID if one was created before cancellation. May be undefined if cancelled before order creation.

Example

onCancel: (data) => {
  console.log("Payment cancelled", data);

  // Use your own analytics to track cancellation
  // Awlays ensure this is a non-blocking call
  analytics.track("checkout_abandoned", {
    orderId: data.orderId,
    timestamp: Date.now(),
  });

  // Show a message to the buyer
  showMessage("Your payment was cancelled. Your cart items are still saved.");

  // Re-enable the checkout button
  document.getElementById("checkout-button").disabled = false;
};

onError(error)

Called when an error occurs during the payment flow. This includes network errors, validation failures, and payment processing errors.

Parameters

The callback receives an error object with these properties:
PropertyTypeDescription
codestringA specific error code identifying the type of error. Use this for programmatic error handling.
messagestringA human-readable error description. This may contain technical details not suitable for buyers.

Common error codes

CodeDescriptionRecommended action
ERR_INVALID_CLIENT_TOKENClient token is invalid or expiredGenerate a new token and reinitialize
ERR_DOMAIN_MISMATCHCurrent domain doesn’t match tokenVerify domain configuration
ERR_DEV_UNABLE_TO_OPEN_POPUPPopup was blocked by browserFall back to modal or redirect mode
ERR_FLOW_PAYMENT_HANDLER_BROWSER_INCOMPATIBLEPayment handler not supportedUse traditional checkout flow
INSTRUMENT_DECLINEDPayment method was declinedSuggest alternative payment method
NETWORK_ERRORNetwork request failedRetry or check connection

Example

onError: (error) => {
  console.error("Payment error:", error);

  // Log to error tracking service
  errorReporter.log(error);

  // Show user-friendly message based on error code
  let message;
  switch (error.code) {
    case "ERR_INVALID_CLIENT_TOKEN":
      message = "Your session has expired. Please refresh and try again.";
      setTimeout(() => location.reload(), 3000);
      break;
    case "INSTRUMENT_DECLINED":
      message =
        "Your payment was declined. Please try a different payment method.";
      break;
    case "NETWORK_ERROR":
      message = "Connection lost. Please check your internet and try again.";
      break;
    default:
      message = "Something went wrong. Please try again.";
  }

  showErrorMessage(message);
};

onShippingAddressChange(data)

Called when the buyer selects or changes their shipping address within the PayPal flow. Use this callback to update shipping costs, validate addresses, or apply location-based restrictions.

Parameters

PropertyTypeDescription
orderIdstringThe current order ID
shippingAddressobjectThe newly selected shipping address
shippingAddress.citystringCity name
shippingAddress.statestringState or province code
shippingAddress.countryCodestringISO 3166-1 alpha-2 country code
shippingAddress.postalCodestringPostal or ZIP code

Return value

Return a Promise to update the order asynchronously. If the Promise rejects, the address change will be rejected and the buyer must select a different address.

Example

onShippingAddressChange: async (data) => {
  const { shippingAddress } = data;

  // Check if we ship to this address
  if (!isShippableLocation(shippingAddress)) {
    // Reject the address change
    throw new Error("Shipping not available to this location");
  }

  // Calculate new shipping cost
  const shippingCost = calculateShipping({
    address: shippingAddress,
    items: cartItems,
  });

  // Update the order with new shipping
  const response = await fetch(`/api/orders/${data.orderId}/shipping`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      shippingAddress,
      shippingCost,
    }),
  });

  if (!response.ok) {
    throw new Error("Failed to update shipping");
  }
};

onShippingOptionsChange(data)

Called when the buyer selects a different shipping option (e.g., standard vs. express delivery). Use this to update the order total with the selected shipping cost.

Parameters

PropertyTypeDescription
orderIdstringThe current order ID
selectedShippingOptionobjectDetails of the selected shipping option

Example

onShippingOptionsChange: async (data) => {
  const { selectedShippingOption } = data;

  // Update order with new shipping option
  await updateOrderShipping({
    orderId: data.orderId,
    shippingId: selectedShippingOption.id,
    shippingCost: selectedShippingOption.amount.value,
  });
};

Web components

PayPal.js provides native web components for rendering payment buttons. These components automatically handle styling and accessibility while allowing customization through CSS variables.

paypal-button

The PayPal button web component renders a PayPal-branded button that buyers click to start the payment flow.

Attributes

AttributeTypeDescription
typestring

Controls the button label text. Different types are optimized for different contexts in your checkout flow.

Values:

  • pay — “Pay with PayPal”
  • checkout — “PayPal Checkout”
  • buynow — “PayPal Buy Now”
  • subscribe — “PayPal Subscribe”
classstring

Applies a predefined color scheme to the button.

Values:

  • paypal-gold — Gold background (recommended)
  • paypal-blue — Blue background
  • paypal-white — White with border

CSS variables

Customize the button appearance using CSS custom properties:
VariableDescriptionExample values
--paypal-button-border-radiusBorder radius for the button4px, 20px, 50px
--paypal-mark-border-radiusBorder radius for the PayPal mark/logo4px, 8px

Example

<!-- Basic button -->
<paypal-button type="pay" class="paypal-gold"></paypal-button>

<!-- Initially hidden button -->
<paypal-button type="checkout" class="paypal-blue" hidden> </paypal-button>

<!-- Custom styled button -->
<style>
  paypal-button {
    --paypal-button-border-radius: 10px;
    width: 100%;
    max-width: 350px;
  }

  paypal-button.custom-style {
    --paypal-button-border-radius: 25px;
  }
</style>

<paypal-button type="pay" class="paypal-gold custom-style"></paypal-button>

<script>
  // Attach click handler
  const onClick = async () => {
    try {
      await paypalSession.start({ presentationMode: "auto" }, createOrder());
    } catch (error) {
      console.log(error);
    }
  };

  document.querySelector("paypal-button").addEventListener("click", onClick);
</script>

venmo-button

The Venmo button web component renders a Venmo-branded button for US buyers. The attributes and styling options are identical to <paypal-button>.

Example

<venmo-button type="pay" class="venmo-blue"></venmo-button>

paylater-button

The Pay Later button component displays financing options to buyers. This button requires additional configuration based on the available Pay Later products.

Attributes

AttributeTypeDescription
productCodestringThe specific Pay Later product to display (e.g., “PAY_IN_4”). Get this from paymentMethods.getDetails('paylater').
countryCodestringThe country code for the Pay Later offer. Required for proper messaging display.

Example

// Configure Pay Later button
const payLaterDetails = paymentMethods.getDetails("paylater");

const button = document.querySelector("paylater-button");
button.productCode = payLaterDetails.productCode;
button.countryCode = payLaterDetails.countryCode;
button.removeAttribute("hidden");

paypal-credit-button

The PayPal Credit button component displays PayPal’s credit offering for eligible buyers (US only).

Attributes

AttributeTypeDescription
countryCodestringThe country code for PayPal Credit availability. Required for proper display.

Example

const creditDetails = paymentMethods.getDetails("credit");

const button = document.querySelector("paypal-credit-button");
button.countryCode = creditDetails.countryCode;

Browser compatibility

The Javascript SDK v6 supports modern browsers. Check browser compatibility before initializing the SDK to ensure optimal user experience.

Minimum supported versions

Browser (web/mobile web)Minimum Supported Version
Chrome69
Safari12
Firefox63
Samsung Internet10
Edge79

Browser support check

Use the window.isBrowserSupportedByPayPal() function to verify browser compatibility before initializing the SDK:
// Check browser compatibility
if (window.isBrowserSupportedByPayPal()) {
  // Initialize PayPal SDK
  const sdkInstance = await window.paypal.createInstance({
    clientToken: clientToken,
  });
} else {
  // Show fallback payment options or browser upgrade message
  showBrowserNotSupportedMessage();
}