securepay
Version:
https://www.securepay.com.au/
77 lines (69 loc) • 2.67 kB
text/typescript
import { AuthenticationAudience } from './../../enums/authentication-audience.enum';
import { AuthenticationGrantType } from "../../enums/authentication-grant-type.enum";
import { Endpoints } from "../../enums/endpoints.enum";
import { SandboxEndpoints } from "../../enums/endpoints.sandbox.enum";
import { DebugLevel } from '../../enums/debug-level.enum';
import { SecurePayToken } from '../../interfaces/common/token.interface';
import { UtilsService } from '../common/utils/utils.service';
import axios from "axios";
import { CacheKeys } from '../../enums/cache-keys.enum';
import { CacheService } from '../common/cache/cache.service';
import { SecurepayConstruction } from '../../interfaces/common/construction.interface';
export class AuthenticationService {
private _utils: UtilsService;
private _cache: CacheService;
/** Variables */
private clientId : string = "";
private clientSecret : string = "";
private sandbox : boolean = true;
private debugLevel : DebugLevel = DebugLevel.NONE;
constructor(options : SecurepayConstruction) {
this._utils = new UtilsService();
this._cache = new CacheService();
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.sandbox = options.sandbox || false;
this.debugLevel = options.debugLevel || DebugLevel.NONE;
}
/**
* Get Jwt Token
*/
async getJwtToken() {
const token: SecurePayToken = await this._cache.get(CacheKeys.JWT_TOKEN);
if (token)
return `${token.token_type} ${token.access_token}`
else
return this.auth();
}
/**
* Request Token
*
* @param payload
*/
async auth() {
/** Fetch Token */
const { data } = await axios.post(
this.sandbox ? SandboxEndpoints.AUTHENTICATION : Endpoints.AUTHENTICATION,
{
grant_type : AuthenticationGrantType.DEFAULT,
audience : AuthenticationAudience.DEFAULT
},
{
headers: {
Authorization : `Basic ${this._utils.base64Encode(`${this.clientId}:${this.clientSecret}`)}`,
"Content-Type" : "application/x-www-form-urlencoded"
}
}
).catch(error => {
if (this.debugLevel && this.debugLevel >= DebugLevel.ERROR)
console.error("[Securepay Auth]", error.response.data);
throw error.response.data;
})
/** Store Into Cache Manager */
const token = data as SecurePayToken;
await this._cache.set(CacheKeys.JWT_TOKEN, token, {
ttl: token.expires_in - 10 /** Remove Estimated Time Spent During Transaction */
});
return `${token.token_type} ${token.access_token}`
}
}