paypal-rest-api
Version:
A typescript module for integrating with PayPal REST APIs.
75 lines (74 loc) • 2.61 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const abstracts_1 = require("../abstracts");
const schemas_1 = require("./schemas");
class Oauth extends abstracts_1.Api {
constructor(client, _clientId, _clientSecret) {
super(client, {}, {});
this._clientId = _clientId;
this._clientSecret = _clientSecret;
}
get clientId() {
return this._clientId;
}
set clientId(id) {
this._clientId = this.schemaValidate(id, Oauth.schemas.clientId);
}
get clientSecret() {
return this._clientSecret;
}
set clientSecret(id) {
this._clientSecret = this.schemaValidate(id, Oauth.schemas.clientSecret);
}
requestAccessToken(options = {}) {
const validate = this.schemaValidate({
auth: {
password: this.clientSecret,
user: this.clientId,
},
}, Oauth.schemas.access);
return this.client.request(Object.assign({}, options, validate));
}
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
if (!this.valid()) {
const response = yield this.requestAccessToken();
this.setAccessToken(JSON.parse(response.body));
}
return this.token;
});
}
setAccessToken(token) {
token.expiration = new Date().setSeconds(token.expires_in);
this.token = token;
}
expired() {
if (Date.now() > this.token.expiration) {
return true;
}
return false;
}
valid() {
if (!this.token || !this.token.access_token || !this.token.expiration || this.expired()) {
return false;
}
return true;
}
}
Oauth.paths = {
access: "/v1/oauth2/token",
};
Oauth.schemas = {
access: schemas_1.oauthAccessTokenRequestSchema,
clientId: schemas_1.clientIdSchema,
clientSecret: schemas_1.secretSchema,
};
exports.Oauth = Oauth;