PayPalCheckout

PayPalCheckout

This class represents a PayPal Checkout component that coordinates with the PayPal SDK. Instances of this class can generate payment data and tokenize authorized payments.

All UI (such as preventing actions on the parent page while authentication is in progress) is managed by the PayPal SDK. You must provide your PayPal client-id as a query parameter. You can retrieve this value from the PayPal Dashboard.

Constructor

new PayPalCheckout(options)

Do not use this constructor directly. Use braintree-web.paypal-checkout.create instead.

Integrate Checkout Flow with PayPal SDK

You must have PayPal's script, configured with various query parameters, loaded on your page:

<script src="https://www.paypal.com/sdk/js?client-id=your-sandbox-or-prod-client-id"></script>
<div id="paypal-button"></div>

When passing values in the createPayment method, make sure they match the corresponding parameters in the query parameters for the PayPal SDK script.

braintree.client.create({
  authorization: 'authorization'
}).then(function (clientInstance) {
  return braintree.paypalCheckout.create({
    client: clientInstance
  });
}).then(function (paypalCheckoutInstance) {
  return paypal.Buttons({
    createOrder: function () {
      return paypalCheckoutInstance.createPayment({
        flow: 'checkout',
        currency: 'USD',
        amount: '10.00',
        intent: 'capture' // this value must either be `capture` or match the intent passed into the PayPal SDK intent query parameter
        // your other createPayment options here
      });
    },

    onApprove: function (data, actions) {
      // some logic here before tokenization happens below
      return paypalCheckoutInstance.tokenizePayment(data).then(function (payload) {
        // Submit payload.nonce to your server
      });
    },

    onCancel: function () {
      // handle case where user cancels
    },

    onError: function (err) {
      // handle case where error occurs
    }
  }).render('#paypal-button');
}).catch(function (err) {
 console.error('Error!', err);
});

Integrate Vault Flow with PayPal SDK

You must have PayPal's script, configured with various query parameters, loaded on your page:

<script src="https://www.paypal.com/sdk/js?client-id=your-sandbox-or-prod-client-id&vault=true"></script>
<div id="paypal-button"></div>

When passing values in the createPayment method, make sure they match the corresponding parameters in the query parameters for the PayPal SDK script.

braintree.client.create({
  authorization: 'authorization'
}).then(function (clientInstance) {
  return braintree.paypalCheckout.create({
    client: clientInstance
  });
}).then(function (paypalCheckoutInstance) {
  return paypal.Buttons({
    createBillingAgreement: function () {
      return paypalCheckoutInstance.createPayment({
        flow: 'vault'
        // your other createPayment options here
      });
    },

    onApprove: function (data, actions) {
      // some logic here before tokenization happens below
      return paypalCheckoutInstance.tokenizePayment(data).then(function (payload) {
        // Submit payload.nonce to your server
      });
    },

    onCancel: function () {
      // handle case where user cancels
    },

    onError: function (err) {
      // handle case where error occurs
    }
  }).render('#paypal-button');
}).catch(function (err) {
 console.error('Error!', err);
});

Integrate with Checkout.js (deprecated PayPal SDK)

If you are creating a new PayPal integration, please follow the previous integration guide to use the current version of the PayPal SDK. Use this integration guide only as a reference if you are already integrated with Checkout.js.

You must have PayPal's Checkout.js script loaded on your page.

<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4 log-level="warn"></script>
braintree.client.create({
  authorization: 'authorization'
}).then(function (clientInstance) {
  return braintree.paypalCheckout.create({
    client: clientInstance
  });
}).then(function (paypalCheckoutInstance) {
  return paypal.Button.render({
    env: 'production', // or 'sandbox'

    payment: function () {
      return paypalCheckoutInstance.createPayment({
        // your createPayment options here
      });
    },

    onAuthorize: function (data, actions) {
      // some logic here before tokenization happens below
      return paypalCheckoutInstance.tokenizePayment(data).then(function (payload) {
        // Submit payload.nonce to your server
      });
    }
  }, '#paypal-button');
}).catch(function (err) {
 console.error('Error!', err);
});
Parameters:
Name Type Description
options object

see paypal-checkout.create

Source:

Methods

createPayment(options, callbackopt) → {Promise|void}

Creates a PayPal payment ID or billing token using the given options. This is meant to be passed to the PayPal JS SDK. When a callback is defined, the function returns undefined and invokes the callback with the id to be used with the PayPal JS SDK. Otherwise, it returns a Promise that resolves with the id.

Parameters:
Name Type Attributes Description
options object

All options for the PayPalCheckout component.

Properties
Name Type Attributes Default Description
flow string

Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer ID, the PayPal account will be added to that customer as a saved payment method.

intent string <optional>
authorize
  • authorize - Submits the transaction for authorization but not settlement.
  • order - Validates the transaction without an authorization (i.e. without holding funds). Useful for authorizing and capturing funds up to 90 days after the order has been placed. Only available for Checkout flow.
  • capture - Payment will be immediately submitted for settlement upon creating a transaction. sale can be used as an alias for this value.
offerCredit boolean <optional>
false

Offers PayPal Credit as the default funding instrument for the transaction. If the customer isn't pre-approved for PayPal Credit, they will be prompted to apply for it.

amount string | number <optional>

The amount of the transaction. Required when using the Checkout flow. Should not include shipping cost.

  • Supports up to 2 digits after the decimal point
currency string <optional>

The currency code of the amount, such as 'USD'. Required when using the Checkout flow.

displayName string <optional>

The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account

requestBillingAgreement boolean <optional>

If true and flow = checkout, the customer will be prompted to consent to a billing agreement during the checkout flow. This value is ignored when flow = vault.

billingAgreementDetails object <optional>

When requestBillingAgreement = true, allows for details to be set for the billing agreement portion of the flow.

Properties
Name Type Attributes Description
description string <optional>

Description of the billing agreement to display to the customer.

vaultInitiatedCheckoutPaymentMethodToken string <optional>

Use the payment method nonce representing a PayPal account with a Billing Agreement ID to create the payment and redirect the customer to select a new financial instrument. This option is only applicable to the checkout flow.

shippingOptions Array.<shippingOption> <optional>

List of shipping options offered by the payee or merchant to the payer to ship or pick up their items.

enableShippingAddress boolean <optional>
false

Returns a shipping address object in PayPal#tokenize.

shippingAddressOverride object <optional>

Allows you to pass a shipping address you have already collected into the PayPal payment flow.

Properties
Name Type Attributes Description
line1 string

Street address.

line2 string <optional>

Street address (extended).

city string

City.

state string

State.

postalCode string

Postal code.

countryCode string

Country.

phone string <optional>

Phone number.

recipientName string <optional>

Recipient's name.

shippingAddressEditable boolean <optional>
true

Set to false to disable user editing of the shipping address.

billingAgreementDescription string <optional>

Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters.

landingPageType string <optional>

Use this option to specify the PayPal page to display when a user lands on the PayPal site to complete the payment.

  • login - A PayPal account login page is used.
  • billing - A non-PayPal account landing page is used.
lineItems Array.<lineItem> <optional>

The line items for this transaction. It can include up to 249 line items.

callback callback <optional>

The second argument is a PayPal paymentId or billingToken string, depending on whether options.flow is checkout or vault. This is also what is resolved by the promise if no callback is provided.

Source:
Examples
// this paypal object is created by the PayPal JS SDK
// see https://github.com/paypal/paypal-checkout-components
paypal.Buttons({
  createOrder: function () {
    // when createPayment resolves, it is automatically passed to the PayPal JS SDK
    return paypalCheckoutInstance.createPayment({
      flow: 'checkout',
      amount: '10.00',
      currency: 'USD',
      intent: 'capture' // this value must either be `capture` or match the intent passed into the PayPal SDK intent query parameter
    });
  },
  // Add other options, e.g. onApproved, onCancel, onError
}).render('#paypal-button');
// shippingOptions are passed to createPayment. You can review the result from onAuthorize to determine which shipping option id was selected.
```javascript
braintree.client.create({
  authorization: 'authorization'
}).then(function (clientInstance) {
  return braintree.paypalCheckout.create({
    client: clientInstance
  });
}).then(function (paypalCheckoutInstance) {
  return paypal.Button.render({
    env: 'production'

    payment: function () {
      return paypalCheckoutInstance.createPayment({
        flow: 'checkout',
        amount: '10.00',
        currency: 'USD',
        shippingOptions: [
          {
            id: 'UUID-9',
            type: 'PICKUP',
            label: 'Store Location Five',
            selected: true,
            amount: {
              value: '1.00',
              currency: 'USD'
            }
          },
          {
            id: 'shipping-speed-fast',
            type: 'SHIPPING',
            label: 'Fast Shipping',
            selected: false,
            amount: {
              value: '1.00',
              currency: 'USD'
            }
          },
          {
            id: 'shipping-speed-slow',
            type: 'SHIPPING',
            label: 'Slow Shipping',
            selected: false,
            amount: {
              value: '1.00',
              currency: 'USD'
            }
          }
        ]
      });
    },

    onAuthorize: function (data, actions) {
      return paypalCheckoutInstance.tokenizePayment(data).then(function (payload) {
        // Submit payload.nonce to your server
      });
    }
  }, '#paypal-button');
}).catch(function (err) {
 console.error('Error!', err);
});
```

getClientId(callbackopt) → {Promise|void}

Resolves with the PayPal client id to be used when loading the PayPal SDK.

Parameters:
Name Type Attributes Description
callback callback <optional>

The second argument, id, is a the PayPal client id. If no callback is provided, the promise resolves with the PayPal client id.

Source:
Example
paypalCheckoutInstance.getClientId().then(function (id) {
 var script = document.createElement('script');

 script.src = 'https://www.paypal.com/sdk/js?client-id=' + id;
 script.onload = function () {
   // setup the PayPal SDK
 };

 document.body.appendChild(script);
});

loadPayPalSDK(optionsopt, callbackopt) → {Promise|void}

Resolves when the PayPal SDK has been successfully loaded onto the page.

Parameters:
Name Type Attributes Description
options object <optional>

A configuration object to modify the query params and data-attributes on the PayPal SDK. A subset of the parameters are listed below. For a full list of query params, see the PayPal docs.

Properties
Name Type Attributes Default Description
client-id string <optional>

By default, this will be the client id associated with the authorization used to create the Braintree component. When used in conjunction with passing authorization when creating the PayPal Checkout component, you can speed up the loading of the PayPal SDK.

intent string <optional>
"authorize"

By default, the PayPal SDK defaults to an intent of capture. Since the default intent when calling createPayment is authorize, the PayPal SDK will be loaded with intent=authorize. If you wish to use a different intent when calling createPayment, make sure it matches here. If sale is used, it will be converted to capture for the PayPal SDK. If the vault: true param is used, tokenize will be passed as the default intent.

locale string <optional>
en_US

Use this option to change the language, links, and terminology used in the PayPal flow. This locale will be used unless the buyer has set a preferred locale for their account. If an unsupported locale is supplied, a fallback locale (determined by buyer preference or browser data) will be used and no error will be thrown.

Supported locales are: da_DK, de_DE, en_AU, en_GB, en_US, es_ES, fr_CA, fr_FR, id_ID, it_IT, ja_JP, ko_KR, nl_NL, no_NO, pl_PL, pt_BR, pt_PT, ru_RU, sv_SE, th_TH, zh_CN, zh_HK, and zh_TW.

currency string <optional>
"USD"

If a currency is passed in createPayment, it must match the currency passed here.

vault boolean <optional>

Must be true when using flow: vault in createPayment.

components string <optional>
buttons

By default, the Braintree SDK will only load the PayPal smart buttons component. If you would like to load just the messages component, pass messages. If you would like to load both, pass buttons,messages

dataAttributes object <optional>

The data attributes to apply to the script. Any data attribute can be passed. A subset of the parameters are listed below. For a full list of data attributes, see the PayPal docs.

Properties
Name Type Attributes Description
client-token string <optional>

The client token to use in the script. (usually not needed)

csp-nonce string <optional>

See the PayPal docs about content security nonces.

callback callback <optional>

Called when the PayPal SDK has been loaded onto the page. The second argument is the PayPal Checkout instance. If no callback is provided, the promise resolves with the PayPal Checkout instance when the PayPal SDK has been loaded onto the page.

Source:
Examples

Without options

paypalCheckoutInstance.loadPayPalSDK().then(function () {
  // window.paypal.Buttons is now available to use
});

With options

paypalCheckoutInstance.loadPayPalSDK({
  'client-id': 'PayPal Client Id', // Can speed up rendering time to hardcode this value

  intent: 'capture', // Make sure this value matches the value in createPayment
  currency: 'USD', // Make sure this value matches the value in createPayment
}).then(function () {
  // window.paypal.Buttons is now available to use
});

With Vaulting

paypalCheckoutInstance.loadPayPalSDK({
  vault: true
}).then(function () {
  // window.paypal.Buttons is now available to use
});

teardown(callbackopt) → {Promise|void}

Cleanly tear down anything set up by create.

Parameters:
Name Type Attributes Description
callback callback <optional>

Called once teardown is complete. No data is returned if teardown completes successfully.

Source:
Examples
paypalCheckoutInstance.teardown();

With callback

paypalCheckoutInstance.teardown(function () {
  // teardown is complete
});

tokenizePayment(tokenizeOptions, callbackopt) → {Promise|void}

Tokenizes the authorize data from the PayPal JS SDK when completing a buyer approval flow. When a callback is defined, invokes the callback with tokenizePayload and returns undefined. Otherwise, returns a Promise that resolves with a tokenizePayload.

Parameters:
Name Type Attributes Description
tokenizeOptions object

Tokens and IDs required to tokenize the payment.

Properties
Name Type Attributes Default Description
payerId string

Payer ID returned by PayPal onApproved callback.

paymentId string <optional>

Payment ID returned by PayPal onApproved callback.

billingToken string <optional>

Billing Token returned by PayPal onApproved callback.

vault boolean <optional>
true

Whether or not to vault the resulting PayPal account (if using a client token generated with a customer id and the vault flow).

callback callback <optional>

The second argument, payload, is a tokenizePayload. If no callback is provided, the promise resolves with a tokenizePayload.

Source:
Example

Opt out of auto-vaulting behavior

// create the paypalCheckoutInstance with a client token generated with a customer id
paypal.Buttons({
  createBillingAgreement: function () {
    return paypalCheckoutInstance.createPayment({
      flow: 'vault'
      // your other createPayment options here
    });
  },
  onApproved: function (data) {
    data.vault = false;

    return paypalCheckoutInstance.tokenizePayment(data);
  },
  // Add other options, e.g. onCancel, onError
}).render('#paypal-button');

updatePayment(options, callbackopt) → {Promise|void}

Use this function to update line items and/or shipping options associated with a PayPalCheckout flow (paymentId). When a callback is defined, this function returns undefined and invokes the callback. The second callback argument, data, is the returned server data. If no callback is provided, updatePayment returns a promise that resolves with the server data.

Parameters:
Name Type Attributes Description
options object

All options for the PayPalCheckout component.

Properties
Name Type Attributes Description
paymentId string

This should be PayPal paymentId.

amount string | number <optional>

The amount of the transaction, including the amount of the selected shipping option.

  • Supports up to 2 decimal digits.
currency string

The currency code of the amount, such as 'USD'. Required when using the Checkout flow.

shippingOptions Array.<shippingOption> <optional>

List of shipping options offered by the payee or merchant to the payer to ship or pick up their items.

lineItems Array.<lineItem> <optional>

The line items for this transaction. It can include up to 249 line items.

callback callback <optional>

The second argument is a PayPal paymentId or billingToken string, depending on whether options.flow is checkout or vault. This is also what is resolved by the promise if no callback is provided.

Source:
Example
// this paypal object is created by the PayPal JS SDK
// see https://github.com/paypal/paypal-checkout-components
paypal.Buttons({
  createOrder: function () {
    // when createPayment resolves, it is automatically passed to the PayPal JS SDK
    return paypalCheckoutInstance.createPayment({
      //
    });
  },
  onShippingChange: function (data) {
    // Examine data and determine if the payment needs to be updated.
    // when updatePayment resolves, it is automatically passed to the PayPal JS SDK
    return paypalCheckoutInstance.updatePayment({
        paymentId: data.paymentId,
        amount: '15.00',
        currency: 'USD',
        shippingOptions: [
          {
            id: 'shipping-speed-fast',
            type: 'SHIPPING',
            label: 'Fast Shipping',
            selected: true,
            amount: {
              value: '5.00',
              currency: 'USD'
            }
          },
          {
            id: 'shipping-speed-slow',
            type: 'SHIPPING',
            label: 'Slow Shipping',
            selected: false,
            amount: {
              value: '1.00',
              currency: 'USD'
            }
          }
        ]
    });
  }
  // Add other options, e.g. onApproved, onCancel, onError
}).render('#paypal-button');

```

Type Definitions

lineItem :object

Properties:
Name Type Attributes Description
quantity string

Number of units of the item purchased. This value must be a whole number and can't be negative or zero.

unitAmount string

Per-unit price of the item. Can include up to 2 decimal places. This value can't be negative or zero.

name string

Item name. Maximum 127 characters.

kind string

Indicates whether the line item is a debit (sale) or credit (refund) to the customer. Accepted values: debit and credit.

unitTaxAmount string <nullable>

Per-unit tax price of the item. Can include up to 2 decimal places. This value can't be negative or zero.

description string <nullable>

Item description. Maximum 127 characters.

productCode string <nullable>

Product or UPC code for the item. Maximum 127 characters.

url string <nullable>

The URL to product information.

Source:

shippingOption :object

Properties:
Name Type Description
id string

A unique ID that identifies a payer-selected shipping option.

label string

A description that the payer sees, which helps them choose an appropriate shipping option. For example, Free Shipping, USPS Priority Shipping, Expédition prioritaire USPS, or USPS yōuxiān fā huò. Localize this description to the payer's locale.

selected boolean

If selected = true is specified as part of the API request it represents the shipping option that the payee/merchant expects to be pre-selected for the payer when they first view the shipping options within the PayPal checkout experience. As part of the response if a shipping option has selected = true it represents the shipping option that the payer selected during the course of checkout with PayPal. Only 1 shippingOption can be set to selected = true.

type string

The method by which the payer wants to get their items. The possible values are:

  • SHIPPING - The payer intends to receive the items at a specified address.
  • PICKUP - The payer intends to pick up the items at a specified address. For example, a store address.
amount object

The shipping cost for the selected option.

Properties
Name Type Description
currency string

The three-character ISO-4217 currency code. PayPal does not support all currencies.

value string

The amount the shipping option will cost. Includes the specified number of digits after decimal separator for the ISO-4217 currency code.

Source:

tokenizePayload :object

PayPal Checkout tokenized payload. Returned in PayPalCheckout#tokenizePayment's callback as the second argument, data.

Properties:
Name Type Attributes Description
nonce string

The payment method nonce.

type string

The payment method type, always PayPalAccount.

details object

Additional PayPal account details.

Properties
Name Type Attributes Description
email string

User's email address.

payerId string

User's payer ID, the unique identifier for each PayPal account.

firstName string

User's given name.

lastName string

User's surname.

countryCode string <nullable>

User's 2 character country code.

phone string <nullable>

User's phone number (e.g. 555-867-5309).

shippingAddress object <nullable>

User's shipping address details, only available if shipping address is enabled.

Properties
Name Type Description
recipientName string

Recipient of postage.

line1 string

Street number and name.

line2 string

Extended address.

city string

City or locality.

state string

State or region.

postalCode string

Postal code.

countryCode string

2 character country code (e.g. US).

billingAddress object <nullable>

User's billing address details. Not available to all merchants; contact support for details on eligibility and enabling this feature. Alternatively, see shippingAddress above as an available client option.

Properties
Name Type Description
line1 string

Street number and name.

line2 string

Extended address.

city string

City or locality.

state string

State or region.

postalCode string

Postal code.

countryCode string

2 character country code (e.g. US).

creditFinancingOffered object <nullable>

This property will only be present when the customer pays with PayPal Credit.

Properties
Name Type Description
totalCost object

This is the estimated total payment amount including interest and fees the user will pay during the lifetime of the loan.

Properties
Name Type Description
value string

An amount defined by ISO 4217 for the given currency.

currency string

3 letter currency code as defined by ISO 4217.

term number

Length of financing terms in months.

monthlyPayment object

This is the estimated amount per month that the customer will need to pay including fees and interest.

Properties
Name Type Description
value string

An amount defined by ISO 4217 for the given currency.

currency string

3 letter currency code as defined by ISO 4217.

totalInterest object

Estimated interest or fees amount the payer will have to pay during the lifetime of the loan.

Properties
Name Type Description
value string

An amount defined by ISO 4217 for the given currency.

currency string

3 letter currency code as defined by ISO 4217.

payerAcceptance boolean

Status of whether the customer ultimately was approved for and chose to make the payment using the approved installment credit.

cartAmountImmutable boolean

Indicates whether the cart amount is editable after payer's acceptance on PayPal side.

Source: