@gatepaybd/core
Version:
Official JavaScript/TypeScript SDK for GatePay payment gateway supporting bKash, Nagad, Rocket and other Bangladesh payment methods
229 lines (219 loc) • 8.22 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('axios')) :
typeof define === 'function' && define.amd ? define(['exports', 'axios'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.GatePaySDK = {}, global.axios));
})(this, (function (exports, axios) { 'use strict';
class GatePaySDKError extends Error {
constructor(error) {
super(error.message);
this.name = 'GatePaySDKError';
this.code = error.code;
this.details = error.details;
}
}
class GatePayValidationError extends Error {
constructor(message) {
super(message);
this.name = 'GatePayValidationError';
}
}
class GatePayNetworkError extends Error {
constructor(message) {
super(message);
this.name = 'GatePayNetworkError';
}
}
class ApiClient {
constructor(config) {
this.config = config;
const baseUrl = config.baseUrl || this.getDefaultBaseUrl(config.environment);
this.client = axios.create({
baseURL: baseUrl,
timeout: config.timeout || 30000,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.apiKey}`,
},
});
this.setupInterceptors();
}
getDefaultBaseUrl(environment) {
return environment === 'production'
? 'https://api.payflow.com'
: 'https://sandbox-api.payflow.com';
}
setupInterceptors() {
// Response interceptor for error handling
this.client.interceptors.response.use((response) => response, (error) => {
if (error.response) {
// Server responded with error status
const apiResponse = error.response.data;
if (apiResponse.error) {
throw new GatePaySDKError(apiResponse.error);
}
}
else if (error.request) {
// Network error
throw new GatePayNetworkError('Network error occurred');
}
throw error;
});
}
async get(url, params) {
const response = await this.client.get(url, { params });
return this.handleResponse(response);
}
async post(url, data) {
const response = await this.client.post(url, data);
return this.handleResponse(response);
}
async put(url, data) {
const response = await this.client.put(url, data);
return this.handleResponse(response);
}
async delete(url) {
const response = await this.client.delete(url);
return this.handleResponse(response);
}
handleResponse(response) {
const { data } = response;
if (!data.success) {
throw new GatePaySDKError(data.error);
}
return data.data;
}
}
class PaymentManager {
constructor(apiClient) {
this.apiClient = apiClient;
}
/**
* Create a new payment
*/
async create(request) {
this.validateCreatePaymentRequest(request);
return this.apiClient.post('/payments', request);
}
/**
* Get payment by ID
*/
async get(paymentId) {
if (!paymentId) {
throw new GatePayValidationError('Payment ID is required');
}
return this.apiClient.get(`/payments/${paymentId}`);
}
/**
* List transactions with optional filters
*/
async list(options = {}) {
const params = this.buildListParams(options);
return this.apiClient.get('/payments', params);
}
/**
* Execute/process a payment
*/
async execute(paymentId) {
if (!paymentId) {
throw new GatePayValidationError('Payment ID is required');
}
return this.apiClient.post(`/payments/${paymentId}/execute`);
}
/**
* Refund a payment
*/
async refund(request) {
this.validateRefundRequest(request);
return this.apiClient.post('/payments/refund', request);
}
validateCreatePaymentRequest(request) {
if (!request.amount || request.amount <= 0) {
throw new GatePayValidationError('Amount must be greater than 0');
}
if (!request.paymentMethod) {
throw new GatePayValidationError('Payment method is required');
}
}
validateRefundRequest(request) {
if (!request.transactionId) {
throw new GatePayValidationError('Transaction ID is required');
}
if (request.amount !== undefined && request.amount <= 0) {
throw new GatePayValidationError('Refund amount must be greater than 0');
}
}
buildListParams(options) {
const params = {};
if (options.page)
params.page = options.page;
if (options.limit)
params.limit = options.limit;
if (options.status)
params.status = options.status;
if (options.currency)
params.currency = options.currency;
if (options.startDate)
params.startDate = options.startDate.toISOString();
if (options.endDate)
params.endDate = options.endDate.toISOString();
return params;
}
}
class GatePaySDK {
constructor(config) {
this.validateConfig(config);
this.apiClient = new ApiClient(config);
this.payments = new PaymentManager(this.apiClient);
}
validateConfig(config) {
if (!config.apiKey) {
throw new GatePayValidationError('API key is required');
}
if (config.environment && !['sandbox', 'production'].includes(config.environment)) {
throw new GatePayValidationError('Environment must be either "sandbox" or "production"');
}
}
/**
* Test the API connection and authentication
*/
async ping() {
try {
return await this.apiClient.get('/ping');
}
catch (error) {
throw error;
}
}
}
// Payment method types
exports.PaymentMethod = void 0;
(function (PaymentMethod) {
PaymentMethod["BKASH"] = "BKASH";
PaymentMethod["NAGAD"] = "NAGAD";
PaymentMethod["ROCKET"] = "ROCKET";
PaymentMethod["UPAY"] = "UPAY";
PaymentMethod["MCASH"] = "MCASH";
PaymentMethod["VISA"] = "VISA";
PaymentMethod["MASTERCARD"] = "MASTERCARD";
PaymentMethod["AMEX"] = "AMEX";
PaymentMethod["INTERNET_BANKING"] = "INTERNET_BANKING";
})(exports.PaymentMethod || (exports.PaymentMethod = {}));
// Payment status
exports.PaymentStatus = void 0;
(function (PaymentStatus) {
PaymentStatus["PENDING"] = "PENDING";
PaymentStatus["PROCESSING"] = "PROCESSING";
PaymentStatus["COMPLETED"] = "COMPLETED";
PaymentStatus["FAILED"] = "FAILED";
PaymentStatus["CANCELLED"] = "CANCELLED";
PaymentStatus["REFUNDED"] = "REFUNDED";
})(exports.PaymentStatus || (exports.PaymentStatus = {}));
// Main exports
exports.GatePayNetworkError = GatePayNetworkError;
exports.GatePaySDK = GatePaySDK;
exports.GatePaySDKError = GatePaySDKError;
exports.GatePayValidationError = GatePayValidationError;
exports.default = GatePaySDK;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=gatepay.umd.js.map