simple-paypal-sdk
Version:
Simple PayPal SDK for Node.js.
71 lines (70 loc) • 2.37 kB
JavaScript
import MemoryCache from "memory-cache";
const cache = new MemoryCache.Cache();
class PayPal {
constructor(options = {}) {
this.clientId = options.clientId || options.client_id;
this.clientSecret = options.clientSecret || options.client_secret;
this.environment = options.environment || "sandbox";
if (!this.clientId || !this.clientSecret) {
throw new TypeError("No clientId or clientSecret");
}
}
_getURL(url) {
if (url.startsWith("https://")) {
return url;
}
url = url.replace(/^\//, "");
return this.environment === "sandbox" ? `https://api.sandbox.paypal.com/${url}` : `https://api.paypal.com/${url}`;
}
async _authenticate() {
const url = `${this._getURL("v1/oauth2/token")}`;
const key = `paypal:${this.environment}:${this.clientId}:${this.clientSecret}:accessToken`;
const accessToken = cache.get(key);
if (accessToken) {
return accessToken;
}
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(`${this.clientId}:${this.clientSecret}`)}`,
"Content-Type": "application/x-www-form-urlencoded"
},
body: "grant_type=client_credentials"
});
if (!response.ok) {
const text = await response.text();
throw new Error(`PayPal OAuth failed with status ${response.status}: ${text}`);
}
const data = await response.json();
cache.put(key, data.access_token, data.expires_in * 1e3 - 3e4);
return data.access_token;
}
async execute({ method = "GET", url, headers = {}, body }) {
const accessToken = await this._authenticate();
const fetchOptions = {
method,
headers: Object.assign({
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/x-www-form-urlencoded"
}, headers)
};
if (typeof body === "string") {
fetchOptions.body = body;
} else {
if (body != null) {
fetchOptions.body = new URLSearchParams(body);
}
}
const response = await fetch(this._getURL(url), fetchOptions);
if (!response.ok) {
const text = await response.text();
throw new Error(`PayPal request failed with status ${response.status}: ${text}`);
}
const data = await response.json();
return data;
}
}
var worker_default = PayPal;
export {
worker_default as default
};