@nkhind/vivawallet-sdk
Version:
Non-Official VivaWallet API SDK
70 lines (69 loc) • 2.69 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const VivaSkull_class_1 = __importDefault(require("./VivaSkull.class"));
const functions_1 = require("../utils/functions");
class VivaAuth extends VivaSkull_class_1.default {
/**
* This code is used for Viva Wallet webhook verification (validation and events) and should be return in the `json` response with the following format:
* ```json
* {
* "key": "<webhookCode>"
* }
* ```
*/
webhookCode = null;
vivaTotken = null;
constructor(datas) {
super(datas);
}
/** Credentials verification, `throw` error if credentials is not gived ***(required for API calls)*** */
async init() {
this.vivaTotken = await this.getVivaToken();
this.webhookCode = await this.getVivaWebhookCode();
if (!this.vivaTotken || !this.webhookCode)
throw new Error('Credentials failed');
}
/** Return the VivaWallet API Auth2.0 code from Credentials (needed for API Bearer calls) or `null` on request failed */
async getVivaToken() {
if (!this.smartClientId || !this.smartClientSecret)
throw new Error('Init not called');
try {
const r = await (0, functions_1.requests)(this.endpoints.auth.url, 'POST', {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' +
Buffer.from(this.smartClientId + ':' + this.smartClientSecret).toString('base64'),
}, {
grant_type: 'client_credentials',
});
if (r.data && r.data.access_token)
return r.data.access_token;
}
catch (e) {
console.log('Viva token', e);
}
return null;
}
getVivaBasicToken() {
return Buffer.from(this.merchantId + ':' + this.apikey).toString('base64');
}
/** Return the code needed for Viva webhooks returns or `null` on request failed */
async getVivaWebhookCode() {
if (!this.merchantId || !this.apikey)
throw new Error('Init not called');
try {
const r = await (0, functions_1.requests)(this.endpoints.webhookAuth.url, 'GET', {
Authorization: 'Basic ' + this.getVivaBasicToken(),
});
if (r.data && r.data.Key)
return r.data.Key;
}
catch (e) {
console.log('Webhook code', e);
}
return null;
}
}
exports.default = VivaAuth;