Loading wrapper and TypeScript types for the PayPal JS SDK
npm install @paypal/paypal-js> Loading wrapper and TypeScript types for the PayPal JS SDK
[![build status][build-badge]][build]
[![code coverage][coverage-badge]][coverage]
[![npm version][version-badge]][package]
[![bundle size][minzip-badge]][bundlephobia]
[![npm downloads][downloads-badge]][npmtrends]
[![apache license][license-badge]][license]
[build-badge]: https://img.shields.io/github/actions/workflow/status/paypal/paypal-js/main.yml?branch=main&logo=github&style=flat-square
[build]: https://github.com/paypal/paypal-js/actions/workflows/main.yml
[coverage-badge]: https://img.shields.io/codecov/c/github/paypal/paypal-js.svg?style=flat-square
[coverage]: https://codecov.io/github/paypal/paypal-js/
[version-badge]: https://img.shields.io/npm/v/@paypal/paypal-js.svg?style=flat-square
[package]: https://www.npmjs.com/package/@paypal/paypal-js
[minzip-badge]: https://img.shields.io/bundlephobia/minzip/@paypal/paypal-js.svg?style=flat-square
[bundlephobia]: https://bundlephobia.com/result?p=@paypal/paypal-js
[downloads-badge]: https://img.shields.io/npm/dm/@paypal/paypal-js.svg?style=flat-square
[npmtrends]: https://www.npmtrends.com/@paypal/paypal-js
[license-badge]: https://img.shields.io/npm/l/@paypal/paypal-js.svg?style=flat-square
[license]: https://github.com/paypal/paypal-js/blob/main/LICENSE
The default JS SDK code snippet blocks page rendering:
``html`
The above snippet can be difficult to implement in a non-blocking way, especially in single page web apps. This is where the paypal-js library comes in. It provides the following benefits over the above snippet:
- Async script loading to ensure page rendering isn't blocked.
- A Promise API to know when script loading is complete.
- A convenient way to reload the script when query parameters or data attributes change.
To get started, install paypal-js with npm.
`sh`
npm install @paypal/paypal-js
Import the loadScript function for asynchronously loading the Paypal JS SDK.
- accepts an object for passing query parameters and attributes to the JS SDK.
- returns a Promise that resolves with window.paypal after the JS SDK is finished loading.
#### Async/Await
`js
import { loadScript } from "@paypal/paypal-js";
let paypal;
try {
paypal = await loadScript({ clientId: "test" });
} catch (error) {
console.error("failed to load the PayPal JS SDK script", error);
}
if (paypal) {
try {
await paypal.Buttons().render("#your-container-element");
} catch (error) {
console.error("failed to render the PayPal Buttons", error);
}
}
`
#### Promises
`js
import { loadScript } from "@paypal/paypal-js";
loadScript({ clientId: "test" })
.then((paypal) => {
paypal
.Buttons()
.render("#your-container-element")
.catch((error) => {
console.error("failed to render the PayPal Buttons", error);
});
})
.catch((error) => {
console.error("failed to load the PayPal JS SDK script", error);
});
`
The loadScript function accepts an object for configuring the JS SDK. It's used for setting query parameters and script attributes. It accepts parameters in camelCase or kebab-case.
#### Query Parameters
The following example adds client-id and currency as query string parameters:
`js`
loadScript({ clientId: "YOUR_CLIENT_ID", currency: "EUR" });
Which will load the following
`
By default, the JS SDK only loads the buttons component. The components query string parameter can be used to load multiple components:
`js`
loadScript({
clientId: "YOUR_CLIENT_ID",
components: ["buttons", "marks", "messages"],
});
Which will load the following
`
View the full list of supported query parameters.
#### Data Attributes
All options prefixed with data are considered attributes. The following example adds data-page-type as an attribute:
`js`
loadScript({
clientId: "YOUR_CLIENT_ID",
dataPageType: "checkout",
});
Which will load the following
`
View the full list of supported script parameters.
#### Merchant Id Array
The merchantId option accepts an array to simplify the implementation for Multi-Seller Payments. With this approach the caller doesn't have to worry about managing the two different merchant id values (data-merchant-id and merchant-id).
Here's an example with multiple merchantId values:
`js`
loadScript({
clientId: "YOUR_CLIENT_ID",
merchantId: ["123", "456", "789"],
});
Which will load the following
`
Here's an example with one merchant-id value:
`js`
loadScript({
clientId: "YOUR_CLIENT_ID",
merchantId: ["123"],
});
When there's only one, the merchant-id is passed in using the query string.
`html`
#### sdkBaseUrl
For local development, the sdkBaseUrl option can be used to set the base url of the JS SDK:
`js`
loadScript({
clientId: "YOUR_CLIENT_ID",
sdkBaseUrl: "http://localhost.paypal.com:8000/sdk/js",
});
This library relies on JavaScript Promises. To support legacy browsers like IE 11, you must provide your own Promise polyfill. With a Promise polyfill this library will support the same browsers as the JS SDK.
The loadScript() function takes in a second parameter for providing a Promise ponyfill. It defaults to the global Promise object if it exists. There are two options for polyfilling the Promise object:
1. Use a global polyfill strategy that monkey patches the window.Promise API implementation.loadScript()
2. Use a ponyfill strategy that passes a Promise library into without affecting other code:
`js
import { loadScript } from "@paypal/paypal-js";
import PromisePonyfill from "promise-polyfill";
loadScript(options, PromisePonyfill).then((paypalObject) => {});
`
We also provide a legacy build that includes the promise-polyfill library. You can reference it from the CDN here:
`html`
The paypal-js script is also available on the unpkg CDN. The iife/paypal-js.js build assigns the loadScript function to the window object as window.paypalLoadScript. Here's an example:
`html`
The loadCustomScript function is a generic script loader function that works with any url.
- accepts an object for defining the script url and attributes.
- returns a promise to indicate if the script was successfully loaded.
#### Async/Await
`js
import { loadCustomScript } from "@paypal/paypal-js";
try {
await loadCustomScript({
url: "https://www.example.com/index.js",
attributes: {
id: "custom-id-value",
"data-foo": "custom-data-attribute",
},
});
console.log("successfully loaded the custom script");
} catch (error) {
console.error("failed to load the custom script", error);
}
`
#### Promises
`js
import { loadCustomScript } from "@paypal/paypal-js";
loadCustomScript({
url: "https://www.example.com/index.js",
attributes: { id: "custom-id-value", "data-foo": "custom-data-attribute" },
})
.then(() => {
console.log("successfully loaded the custom script");
})
.catch((err) => {
console.error("failed to load the custom script", err);
});
`
This package includes TypeScript type definitions for the PayPal JS SDK. This includes types for the window.paypal namespace. We support projects using TypeScript versions >= 3.8.
In addition to the type definitions above, this package also includes Typescript type definitions for the PayPal JS SDK V6.
#### Importing and Using V6 Types
A basic example showing data-typing for PayPal One Time Payment.
`ts
import type {
PayPalV6Namespace,
OnApproveDataOneTimePayments,
OnShippingAddressChangeData,
} from "@paypal/paypal-js/sdk-v6";
declare global {
interface Window {
paypal: PayPalV6Namespace;
}
}
const sdkInstance = await window.paypal.createInstance({
clientToken: "INSERT_YOUR_CLIENT_TOKEN_HERE",
components: ["paypal-payments", "venmo-payments"],
});
function onApproveCallback(data: OnApproveDataOneTimePayments) {}
function onShippingAddressChangeCallback(data: OnShippingAddressChangeData) {}
const paypalCheckout = sdkInstance.createPayPalOneTimePaymentSession({
onApprove: onApproveCallback,
onShippingAddressChange: onShippingAddressChangeCallback,
});
``