UNPKG

@doctech/fib

Version:

First Iraqi Bank payment integration for DocTech

80 lines (79 loc) 2.71 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FIBClient = void 0; const axios_1 = __importDefault(require("axios")); class FIBClient { constructor(config) { this.token = null; this.tokenExpiry = null; this.config = config; this.client = axios_1.default.create({ baseURL: config.baseUrl, }); } async ensureToken() { if (!this.token || (this.tokenExpiry && Date.now() > this.tokenExpiry)) { await this.authenticate(); } return this.token; } async authenticate() { try { const params = new URLSearchParams(); params.append("grant_type", "client_credentials"); params.append("client_id", this.config.clientId); params.append("client_secret", this.config.clientSecret); const response = await this.client.post("/auth/realms/fib-online-shop/protocol/openid-connect/token", params); this.token = response.data.access_token; this.tokenExpiry = Date.now() + response.data.expires_in * 1000; } catch (_a) { throw new Error("Failed to authenticate with FIB"); } } async createPayment(options) { const token = await this.ensureToken(); try { const response = await this.client.post("/protected/v1/payments", options, { headers: { Authorization: `Bearer ${token}`, }, }); return response.data; } catch (_a) { throw new Error("Failed to create payment"); } } async getPaymentStatus(paymentId) { const token = await this.ensureToken(); try { const response = await this.client.get(`/protected/v1/payments/${paymentId}/status`, { headers: { Authorization: `Bearer ${token}`, }, }); return response.data; } catch (_a) { throw new Error("Failed to get payment status"); } } async cancelPayment(paymentId) { const token = await this.ensureToken(); try { await this.client.post(`/protected/v1/payments/${paymentId}/cancel`, {}, { headers: { Authorization: `Bearer ${token}`, }, }); } catch (_a) { throw new Error("Failed to cancel payment"); } } } exports.FIBClient = FIBClient;