tonb-merchant-api-client
Version:
Merchant API client is a library to interact with TONB Merchant API.
180 lines (179 loc) • 6.92 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpProvider = void 0;
const axios_1 = __importDefault(require("axios"));
const axios_retry_1 = __importDefault(require("axios-retry"));
const crypto_1 = require("crypto");
/** HttpProvider provides methods to communicate with Merchant API via HTTP. */
class HttpProvider {
constructor(settings) {
// if client is provided then use it
if ('client' in settings) {
this._client = settings.client;
// Accessing the Authorization header
const headers = settings.client.defaults.headers;
this._apiKey = String(headers['Authorization']);
if (!this._apiKey) {
console.error('Authorization header not found');
}
return;
}
this._apiKey = settings.apiKey;
this._client = axios_1.default.create({
baseURL: new URL(`/m/${settings.merchantId}/`, settings.url).href,
headers: {
Authorization: settings.apiKey,
},
});
(0, axios_retry_1.default)(axios_1.default, {
retries: 3,
});
}
createInvoice(data) {
return __awaiter(this, void 0, void 0, function* () {
let resp;
try {
resp = yield this._sendWithAuth('POST', `/invoice`, data);
}
catch (e) {
return this._invalidData(e);
}
if (!this._isSuccess(resp)) {
return this._invalidData();
}
return {
data: this._parseInvoiceResponse(resp.data.data),
isValid: true,
};
});
}
cancelInvoice(invoiceId) {
return __awaiter(this, void 0, void 0, function* () {
let resp;
try {
resp = yield this._sendWithAuth('PATCH', `/invoice/cancel`, {
invoiceId,
});
}
catch (e) {
return this._invalidData(e);
}
if (!this._isSuccess(resp)) {
return this._invalidData();
}
return {
data: this._parseInvoiceResponse(resp.data.data),
isValid: true,
};
});
}
getInvoiceInfo(invoiceId) {
return __awaiter(this, void 0, void 0, function* () {
let resp;
try {
resp = yield this._sendWithAuth('GET', `/invoice/info?id=${invoiceId}`);
}
catch (e) {
return this._invalidData(e);
}
if (!this._isSuccess(resp)) {
return this._invalidData();
}
return {
data: this._parseInvoiceResponse(resp.data.data),
isValid: true,
};
});
}
getInvoiceStats() {
return __awaiter(this, void 0, void 0, function* () {
let resp;
try {
resp = yield this._sendWithAuth('GET', `/invoice/stats`);
}
catch (e) {
return this._invalidData(e);
}
if (!this._isSuccess(resp)) {
return this._invalidData();
}
return {
data: Object.assign({}, resp.data.data),
isValid: true,
};
});
}
isUpdateValid(update) {
const { data } = update;
const { sign } = data, others = __rest(data, ["sign"]);
const response = Object.entries(others)
.sort()
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.map(([_key, value]) => value)
.join(';');
const hmac = (0, crypto_1.createHmac)('sha256', this._apiKey);
hmac.update(response);
const signReceived = hmac.digest('hex');
return sign === signReceived;
}
_sendWithAuth(method, path, data) {
switch (method) {
case 'POST':
return this._client.post(path, data);
case 'GET':
return this._client.get(path);
case 'PATCH':
return this._client.patch(path, data);
}
throw new Error(`unsupported method: ${method}`);
}
_invalidData(e) {
return {
data: null,
isValid: false,
error: e,
};
}
_parseInvoiceResponse(invoiceResponse) {
return Object.assign(Object.assign({}, invoiceResponse), { id: Number(invoiceResponse.id), amount: BigInt(invoiceResponse.amount), order_id: BigInt(invoiceResponse.order_id), createdAt: invoiceResponse.createdAt
? Date.parse(invoiceResponse.createdAt)
: undefined, updatedAt: invoiceResponse.updatedAt
? Date.parse(invoiceResponse.updatedAt)
: undefined, user_from_id: invoiceResponse.user_from_id
? BigInt(invoiceResponse.user_from_id)
: undefined, user_to_id: invoiceResponse.user_to_id
? BigInt(invoiceResponse.user_to_id)
: undefined, wallet_from_id: invoiceResponse.wallet_from_id
? Number(invoiceResponse.wallet_from_id)
: undefined, wallet_to_id: invoiceResponse.wallet_to_id
? Number(invoiceResponse.wallet_to_id)
: undefined });
}
_isSuccess(res) {
return Math.floor(res.status / 100) === 2 && !!res.data;
}
}
exports.HttpProvider = HttpProvider;