assembly-payments
Version:
Assembly Payments API Typescript/Javascript Bindings
135 lines (134 loc) • 5.07 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = exports.jitter = void 0;
/**
* @title Assembly API
* @version 2.0
* @baseUrl https://virtserver.swaggerhub.com/AssemblyPlatforms/assembly-api/2.0
* @contact <support@assemblypayments.com> (http://docs.assemblypayments.com/)
*
* Assembly (formely PromisePay) is a powerful payments engine custom-built for platforms and marketplaces.
*/
const axios_1 = __importDefault(require("axios"));
const bunyan_1 = __importDefault(require("bunyan"));
const middleware_1 = require("./middleware");
const tokens_1 = __importDefault(require("./resources/tokens"));
let log;
const getDefaultLogger = () => {
if (log)
return log;
log = bunyan_1.default.createLogger({
name: 'assembly-payments-node',
level: bunyan_1.default.DEBUG,
});
return log;
};
const elapsed = start => {
const time = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
return time;
};
class AuthClient {
constructor({ baseURL = 'https://au-0000.auth.assemblypay.com/', clientId, clientSecret, scope, logger, }) {
this.clientId = clientId;
this.baseURL = baseURL;
this.clientSecret = clientSecret;
this.scope = scope;
this.logger = logger !== null && logger !== void 0 ? logger : getDefaultLogger();
this.instance = axios_1.default.create({ baseURL });
}
async request(params) {
return this.instance.request(params).then(resp => resp.data);
}
}
const jitter = () => Math.floor(Math.random() * 5) + 1;
exports.jitter = jitter;
class Client {
constructor({ baseURL = 'https://secure.api.promisepay.com/', authBaseURL = 'https://au-0000.auth.assemblypay.com/', clientId, clientSecret, timeout = 180 * 1000, logger, retries = 3, scope, }) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.baseURL = baseURL;
this.scope = scope;
this.authBaseURL = authBaseURL;
this.logger = logger !== null && logger !== void 0 ? logger : getDefaultLogger();
this.retries = retries;
this.instance = axios_1.default.create({
baseURL,
timeout,
responseType: 'json',
});
this.authClient = new AuthClient({
baseURL: authBaseURL,
clientId,
logger,
clientSecret,
scope,
});
middleware_1.expiredToken(this, this.retries);
}
getHeaders(secure = true) {
var _a;
const headers = {
'User-Agent': `Assembly Payments Node`,
};
if (secure) {
return Object.assign(Object.assign({}, headers), { Authorization: `Bearer ${(_a = this === null || this === void 0 ? void 0 : this.token) === null || _a === void 0 ? void 0 : _a.access_token}` });
}
return headers;
}
async refresh() {
await tokens_1.default(this.authClient)
.token({
client_id: this.clientId,
client_secret: this.clientSecret,
scope: this.scope,
grant_type: 'client_credentials',
})
.then(resp => {
var _a;
this.token = resp;
this.refreshedAt = new Date();
const expires = ((_a = this.token.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000;
this.expiresAt = new Date(this.refreshedAt.getTime() + expires);
// get refresh window 5-10 minutes from expiry
const window = 1000 * 5 + exports.jitter() * 60 * 1000;
this.refreshAt = new Date(this.refreshedAt.getTime() + (expires - window));
this.logger.debug({
refreshAt: this.refreshAt,
expiresAt: this.expiresAt,
expires,
window,
refreshedAt: this.refreshedAt,
}, `token refreshed`);
});
}
async conditionalRefresh(secure) {
if (!secure) {
return;
}
if (!this.token || !this.refreshAt) {
this.logger.debug(`no token present - refreshing token`);
await this.refresh();
return;
}
const expired = new Date() > this.refreshAt;
if (expired) {
this.logger.debug(`in refresh window refreshing token`);
await this.refresh();
}
}
async request(params) {
const start = process.hrtime();
await this.conditionalRefresh(params.secure);
const headers = this.getHeaders(params.secure);
const data = await this.instance
.request(Object.assign(Object.assign({}, params), { headers }))
.then(resp => resp.data);
this.logger.debug(`${params.url} elapsed time (ms): ${elapsed(start)}`);
return data;
}
}
exports.Client = Client;
exports.default = Client;