@openlib.dev/mn-payment-sdk
Version:
Монголын төлбөрийн хэрэгсэлүүд SDK
1,637 lines (1,610 loc) • 68.7 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
var index_exports = {};
__export(index_exports, {
Bank: () => Bank,
EbarimtClient: () => EbarimtClient,
GolomtClient: () => GolomtClient,
HipayClient: () => HipayClient,
InvoiceType: () => InvoiceType,
MchatAuth: () => MchatAuth,
MchatOnlineQrGenerate: () => MchatOnlineQrGenerate,
MchatOnlineQrcheck: () => MchatOnlineQrcheck,
MchatTransactionSettlement: () => MchatTransactionSettlement,
MongolchatClient: () => MongolchatClient,
MonpayCheckQr: () => MonpayCheckQr,
MonpayClient: () => MonpayClient,
MonpayDeeplinkAuth: () => MonpayDeeplinkAuth,
MonpayDeeplinkCheck: () => MonpayDeeplinkCheck,
MonpayDeeplinkClient: () => MonpayDeeplinkClient,
MonpayDeeplinkCreate: () => MonpayDeeplinkCreate,
MonpayGenerateQr: () => MonpayGenerateQr,
PassClient: () => PassClient,
QPay: () => QPay,
QPayAuthRefresh: () => QPayAuthRefresh,
QPayAuthToken: () => QPayAuthToken,
QPayInvoiceCancel: () => QPayInvoiceCancel,
QPayInvoiceCreate: () => QPayInvoiceCreate,
QPayInvoiceGet: () => QPayInvoiceGet,
QPayPaymentCancel: () => QPayPaymentCancel,
QPayPaymentCheck: () => QPayPaymentCheck,
QPayPaymentGet: () => QPayPaymentGet,
QPayPaymentList: () => QPayPaymentList,
QPayPaymentRefund: () => QPayPaymentRefund,
QpayClient: () => QpayClient,
SocialPayClient: () => SocialPayClient,
SocialPayInvoiceCancel: () => SocialPayInvoiceCancel,
SocialPayInvoiceCheck: () => SocialPayInvoiceCheck,
SocialPayInvoicePhone: () => SocialPayInvoicePhone,
SocialPayInvoiceQr: () => SocialPayInvoiceQr,
SocialPayPaymentCancel: () => SocialPayPaymentCancel,
SocialPayPaymentSettlement: () => SocialPayPaymentSettlement,
StorepayAuth: () => StorepayAuth,
StorepayClient: () => StorepayClient,
StorepayLoan: () => StorepayLoan,
StorepayLoanCheck: () => StorepayLoanCheck,
StorepayUserPossibleAmount: () => StorepayUserPossibleAmount,
TdbCgClient: () => TdbCgClient,
TokipayClient: () => TokipayClient,
TokipayDeeplink: () => TokipayDeeplink,
TokipayPaymentCancel: () => TokipayPaymentCancel,
TokipayPaymentQr: () => TokipayPaymentQr,
TokipayPaymentScanUser: () => TokipayPaymentScanUser,
TokipayPaymentSentUser: () => TokipayPaymentSentUser,
TokipayPaymentStatus: () => TokipayPaymentStatus,
TokipayPhoneRequest: () => TokipayPhoneRequest,
TokipayRefund: () => TokipayRefund,
TokipayTransactionStatus: () => TokipayTransactionStatus
});
module.exports = __toCommonJS(index_exports);
// src/qpay/apis.ts
var QPayAuthToken = {
url: "/auth/token",
method: "POST"
};
var QPayAuthRefresh = {
url: "/auth/refresh",
method: "POST"
};
var QPayPaymentGet = {
url: "/payment/get/",
method: "GET"
};
var QPayPaymentCheck = {
url: "/payment/check",
method: "POST"
};
var QPayPaymentCancel = {
url: "/payment/cancel",
method: "DELETE"
};
var QPayPaymentRefund = {
url: "/payment/refund/",
method: "DELETE"
};
var QPayPaymentList = {
url: "/payment/url",
method: "POST"
};
var QPayInvoiceCreate = {
url: "/invoice",
method: "POST"
};
var QPayInvoiceGet = {
url: "/invoice/",
method: "GET"
};
var QPayInvoiceCancel = {
url: "/invoice/",
method: "DELETE"
};
// src/qpay/client.ts
var import_axios2 = __toESM(require("axios"));
// src/common/errors/payment-error.ts
var PaymentError = class _PaymentError extends Error {
constructor(details) {
super(details.message);
this.name = "PaymentError";
this.code = details.code;
this.provider = details.provider;
this.originalError = details.originalError;
this.requestId = details.requestId;
this.timestamp = details.timestamp || Date.now();
}
toJSON() {
return {
code: this.code,
message: this.message,
provider: this.provider,
originalError: this.originalError,
requestId: this.requestId,
timestamp: this.timestamp
};
}
static fromProviderError(provider, error) {
var _a;
const details = {
code: "PROVIDER_ERROR" /* PROVIDER_ERROR */,
message: error.message || "Unknown provider error",
provider,
originalError: error
};
if ((_a = error.response) == null ? void 0 : _a.data) {
details.message = error.response.data.error || error.response.data.message || details.message;
}
return new _PaymentError(details);
}
static fromNetworkError(error) {
return new _PaymentError({
code: "NETWORK_ERROR" /* NETWORK_ERROR */,
message: error.message || "Network error occurred",
originalError: error
});
}
static fromTimeoutError(error) {
return new _PaymentError({
code: "TIMEOUT" /* TIMEOUT */,
message: error.message || "Request timed out",
originalError: error
});
}
};
// src/common/errors/http-error-handler.ts
var import_axios = __toESM(require("axios"));
var HttpErrorHandler = class {
static handleError(provider, error) {
if (import_axios.default.isAxiosError(error)) {
const axiosError = error;
if (!axiosError.response) {
throw PaymentError.fromNetworkError(error);
}
if (axiosError.code === "ECONNABORTED") {
throw PaymentError.fromTimeoutError(error);
}
const status = axiosError.response.status;
const data = axiosError.response.data;
switch (status) {
case 400:
throw new PaymentError({
code: "INVALID_REQUEST" /* INVALID_REQUEST */,
message: (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || "Invalid request",
provider,
originalError: error
});
case 401:
case 403:
throw new PaymentError({
code: "UNAUTHORIZED" /* UNAUTHORIZED */,
message: (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || "Unauthorized access",
provider,
originalError: error
});
case 404:
throw new PaymentError({
code: "INVALID_REQUEST" /* INVALID_REQUEST */,
message: (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || "Resource not found",
provider,
originalError: error
});
case 408:
throw PaymentError.fromTimeoutError(error);
case 429:
throw new PaymentError({
code: "PROVIDER_ERROR" /* PROVIDER_ERROR */,
message: (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || "Too many requests",
provider,
originalError: error
});
case 500:
case 502:
case 503:
case 504:
throw new PaymentError({
code: "PROVIDER_UNAVAILABLE" /* PROVIDER_UNAVAILABLE */,
message: (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || "Payment provider is currently unavailable",
provider,
originalError: error
});
default:
throw PaymentError.fromProviderError(provider, error);
}
}
if (error instanceof Error) {
throw new PaymentError({
code: "INTERNAL_ERROR" /* INTERNAL_ERROR */,
message: error.message,
provider,
originalError: error
});
}
throw new PaymentError({
code: "INTERNAL_ERROR" /* INTERNAL_ERROR */,
message: "An unknown error occurred",
provider,
originalError: error
});
}
};
// src/qpay/client.ts
var MAX_RETRIES = 3;
var TIMEOUT_MS = 3e4;
var RETRY_DELAY_MS = 1e3;
var QpayClient = class {
constructor(config) {
this.endpoint = config.endpoint;
this.password = config.password;
this.username = config.username;
this.callback = config.callback;
this.invoiceCode = config.invoiceCode;
this.merchantId = config.merchantId;
this.loginObject = null;
}
sleep(ms) {
return __async(this, null, function* () {
return new Promise((resolve) => setTimeout(resolve, ms));
});
}
makeRequest(config) {
return __async(this, null, function* () {
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
console.log(`[QPayClient] Making ${config.method} request to ${config.url} (Attempt ${attempt}/${MAX_RETRIES})`);
const response = yield (0, import_axios2.default)(config);
const data = response.data;
if (data.error) {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: data.error || "Payment failed",
provider: "qpay",
requestId: data.id || data.error
});
}
console.log(`[QPayClient] Successfully completed ${config.method} request to ${config.url}`);
return data;
} catch (error) {
lastError = error;
if (error instanceof PaymentError) {
throw error;
}
const isRetryable = error.code === "ECONNABORTED" || // Timeout
error.code === "ECONNRESET" || // Connection reset
error.code === "ETIMEDOUT" || // Connection timeout
error.response && error.response.status >= 500;
if (!isRetryable || attempt === MAX_RETRIES) {
break;
}
console.log(`[QPayClient] Request failed, retrying in ${RETRY_DELAY_MS}ms... (Error: ${error.message})`);
yield this.sleep(RETRY_DELAY_MS * attempt);
}
}
HttpErrorHandler.handleError("qpay", lastError);
});
}
httpRequest(body, api, urlExt = "") {
return __async(this, null, function* () {
try {
const authObj = yield this.authQpayV2();
this.loginObject = authObj;
const config = {
method: api.method,
url: this.endpoint + api.url + urlExt,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.loginObject.accessToken}`
},
timeout: TIMEOUT_MS
};
if (body) {
config.data = body;
}
return this.makeRequest(config);
} catch (error) {
HttpErrorHandler.handleError("qpay", error);
}
});
}
authQpayV2() {
return __async(this, null, function* () {
if (this.loginObject) {
const expireInA = new Date(this.loginObject.expiresIn * 1e3);
const expireInB = new Date(expireInA.getTime() - 12 * 60 * 60 * 1e3);
const now = /* @__PURE__ */ new Date();
if (now < expireInB) {
return this.loginObject;
}
}
try {
const config = {
method: QPayAuthToken.method,
url: this.endpoint + QPayAuthToken.url,
headers: {
"Content-Type": "application/json"
},
auth: {
username: this.username,
password: this.password
},
timeout: TIMEOUT_MS
};
console.log(`[QPayClient] Making authentication request (Attempt 1/1)`);
const response = yield (0, import_axios2.default)(config);
const data = response.data;
if (data.error) {
throw new PaymentError({
code: "UNAUTHORIZED" /* UNAUTHORIZED */,
message: data.error || "Authentication failed",
provider: "qpay"
});
}
console.log(`[QPayClient] Successfully authenticated`);
return data;
} catch (error) {
HttpErrorHandler.handleError("qpay", error);
}
});
}
refreshToken() {
return __async(this, null, function* () {
var _a;
if (!this.loginObject) {
throw new Error("No login object available");
}
const config = {
method: QPayAuthRefresh.method,
url: this.endpoint + QPayAuthRefresh.url,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.loginObject.refreshToken}`
}
};
try {
const response = yield (0, import_axios2.default)(config);
return response.data;
} catch (error) {
if ((_a = error.response) == null ? void 0 : _a.data) {
throw new Error(error.response.data.error || error.response.data);
}
throw error;
}
});
}
createInvoice(input) {
return __async(this, null, function* () {
const vals = new URLSearchParams();
for (const [key, value] of Object.entries(input.callbackParam)) {
vals.append(key, value);
}
const request = {
invoiceCode: this.invoiceCode,
senderInvoiceCode: input.senderCode,
senderBranchCode: input.senderBranchCode,
invoiceReceiverCode: input.receiverCode,
invoiceDescription: input.description,
amount: input.amount,
callbackUrl: `${this.callback}?${vals.toString()}`
};
return this.httpRequest(
request,
QPayInvoiceCreate
);
});
}
getInvoice(invoiceId) {
return __async(this, null, function* () {
return this.httpRequest(
null,
QPayInvoiceGet,
invoiceId
);
});
}
cancelInvoice(invoiceId) {
return __async(this, null, function* () {
return this.httpRequest(
null,
QPayInvoiceCancel,
invoiceId
);
});
}
getPayment(invoiceId) {
return __async(this, null, function* () {
return this.httpRequest(
null,
QPayPaymentGet,
invoiceId
);
});
}
checkPayment(invoiceId, pageLimit, pageNumber) {
return __async(this, null, function* () {
const request = {
objectID: invoiceId,
objectType: "INVOICE",
offset: {
pageLimit,
pageNumber
}
};
return this.httpRequest(
request,
QPayPaymentCheck
);
});
}
cancelPayment(invoiceId, paymentUUID) {
return __async(this, null, function* () {
const request = {
callbackUrl: this.callback + paymentUUID,
note: `Cancel payment - ${invoiceId}`
};
return this.httpRequest(
request,
QPayPaymentCancel,
invoiceId
);
});
}
refundPayment(invoiceId, paymentUUID) {
return __async(this, null, function* () {
const request = {
callbackUrl: this.callback + paymentUUID,
note: `Cancel payment - ${invoiceId}`
};
return this.httpRequest(
request,
QPayPaymentRefund,
invoiceId
);
});
}
};
// src/qpay/index.ts
var QPay = class {
constructor(username, password, endpoint, callback, invoiceCode, merchantId) {
this.endpoint = endpoint;
this.password = password;
this.username = username;
this.callback = callback;
this.invoiceCode = invoiceCode;
this.merchantId = merchantId;
this.loginObject = null;
}
createInvoice(input) {
return __async(this, null, function* () {
const vals = new URLSearchParams();
for (const [k, v] of Object.entries(input.callbackParam)) {
vals.append(k, v);
}
const amountInt = input.amount;
const request = {
invoiceCode: this.invoiceCode,
senderInvoiceCode: input.senderCode,
senderBranchCode: input.senderBranchCode,
invoiceReceiverCode: input.receiverCode,
invoiceDescription: input.description,
amount: amountInt,
callbackUrl: `${this.callback}?${vals.toString()}`
};
const response = yield this.httpRequestQPay(
QPayInvoiceCreate,
"",
request
);
return response;
});
}
getInvoice(invoiceId) {
return __async(this, null, function* () {
const response = yield this.httpRequestQPay(
QPayInvoiceGet,
invoiceId
);
return response;
});
}
cancelInvoice(invoiceId) {
return __async(this, null, function* () {
const response = yield this.httpRequestQPay(
QPayInvoiceCancel,
invoiceId
);
return response;
});
}
getPayment(invoiceId) {
return __async(this, null, function* () {
const response = yield this.httpRequestQPay(QPayPaymentGet, invoiceId);
return response;
});
}
checkPayment(invoiceId, pageLimit, pageNumber) {
return __async(this, null, function* () {
const req = {
objectID: invoiceId,
objectType: "INVOICE",
offset: {
pageLimit,
pageNumber
}
};
const response = yield this.httpRequestQPay(
QPayPaymentCheck,
"",
req
);
return response;
});
}
cancelPayment(invoiceId, paymentUUID) {
return __async(this, null, function* () {
const req = {
callbackUrl: `${this.callback}${paymentUUID}`,
note: `Cancel payment - ${invoiceId}`
};
const response = yield this.httpRequestQPay(
QPayPaymentCancel,
invoiceId,
req
);
return response;
});
}
refundPayment(invoiceId, paymentUUID) {
return __async(this, null, function* () {
const req = {
callbackUrl: `${this.callback}${paymentUUID}`,
note: `Cancel payment - ${invoiceId}`
};
const response = yield this.httpRequestQPay(
QPayPaymentRefund,
invoiceId,
req
);
return response;
});
}
authQPayV2() {
return __async(this, null, function* () {
var _a;
if (this.loginObject) {
const expireInA = new Date(((_a = this.loginObject) == null ? void 0 : _a.expiresIn) * 1e3);
const expireInB = new Date(expireInA.getTime() - 12 * 60 * 60 * 1e3);
const now = /* @__PURE__ */ new Date();
if (now < expireInB) {
return this.loginObject;
}
}
const url = `${this.endpoint}/${QPayAuthToken.url}`;
const headers = {
"Content-Type": "application/json"
};
const basicAuth = btoa(`${this.username}:${this.password}`);
const requestOptions = {
method: QPayAuthToken.method,
headers: __spreadProps(__spreadValues({}, headers), {
Authorization: `Basic ${basicAuth}`
})
};
const response = yield fetch(url, requestOptions);
if (!response.ok) {
const errorMessage = yield response.text();
throw new Error(
`${(/* @__PURE__ */ new Date()).toISOString()}-QPay auth response: ${errorMessage}`
);
}
return response.json();
});
}
httpRequestQPay(api, urlExt, body) {
return __async(this, null, function* () {
let authObj;
authObj = yield this.authQPayV2();
this.loginObject = authObj;
const requestBody = body ? JSON.stringify(body) : "";
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.loginObject.accessToken}`
};
const requestOptions = {
method: api.method,
headers,
body: requestBody
};
const response = yield fetch(
`${this.endpoint}${api.url}${urlExt}`,
requestOptions
);
if (!response.ok) {
const errorMessage = yield response.text();
throw new Error(errorMessage);
}
return response.json();
});
}
refreshToken() {
return __async(this, null, function* () {
var _a;
const url = `${this.endpoint}/${QPayAuthRefresh.url}`;
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${(_a = this.loginObject) == null ? void 0 : _a.refreshToken}`
};
const requestOptions = {
method: QPayAuthRefresh.method,
headers
};
const response = yield fetch(url, requestOptions);
if (!response.ok) {
const errorMessage = yield response.text();
throw new Error(
`${(/* @__PURE__ */ new Date()).toISOString()}-QPay token refresh response: ${errorMessage}`
);
}
return response.json();
});
}
};
// src/golomt/client.ts
var import_axios3 = __toESM(require("axios"));
var import_crypto = __toESM(require("crypto"));
// src/golomt/apis.ts
var ECommerceInvoiceCreate = {
url: "/api/invoice",
method: "POST"
};
var ECommerceInquiry = {
url: "/api/inquiry",
method: "POST"
};
var ECommercePayByToken = {
url: "/api/pay",
method: "POST"
};
// src/golomt/client.ts
var GolomtClient = class {
constructor(config) {
this.endpoint = config.endpoint;
this.secret = config.secret;
this.bearerToken = config.bearerToken;
}
boolToString(v) {
return v ? "Y" : "N";
}
generateHMAC(secret, data) {
return import_crypto.default.createHmac("sha256", secret).update(data).digest("hex");
}
appendAsString(...args) {
return args.join("");
}
getUrlByInvoiceId(invoice, lang, paymentMethod) {
return `${this.endpoint}/${paymentMethod}/${lang}/${invoice}`;
}
payByToken(amount, token, transactionId, lang) {
return __async(this, null, function* () {
const checksum = this.generateHMAC(
this.secret,
this.appendAsString(amount, transactionId, token)
);
const request = {
amount: amount.toString(),
checksum,
token,
transactionId,
lang,
invoice: ""
// This will be set by the server
};
const response = yield this.httpRequestGolomtEcommerce(request, ECommercePayByToken);
if (response.errorCode !== "000") {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: response.errorDesc,
provider: "golomt",
requestId: transactionId
});
}
return response;
});
}
createInvoice(input) {
return __async(this, null, function* () {
const amount = input.amount.toFixed(2);
const checksum = this.generateHMAC(
this.secret,
this.appendAsString(
input.transactionId,
amount,
input.returnType,
input.callback
)
);
const request = {
amount,
checksum,
transactionId: input.transactionId,
returnType: input.returnType,
callback: input.callback,
genToken: this.boolToString(input.getToken),
socialDeeplink: this.boolToString(input.socialDeeplink)
};
return this.httpRequestGolomtEcommerce(request, ECommerceInvoiceCreate);
});
}
inquiry(transactionId) {
return __async(this, null, function* () {
const checksum = this.generateHMAC(
this.secret,
this.appendAsString(transactionId, transactionId)
);
const request = {
checksum,
transactionId
};
const response = yield this.httpRequestGolomtEcommerce(request, ECommerceInquiry);
if (response.errorCode !== "000") {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: response.errorDesc,
provider: "golomt",
requestId: transactionId
});
}
return response;
});
}
httpRequestGolomtEcommerce(body, api) {
return __async(this, null, function* () {
try {
const response = yield (0, import_axios3.default)({
method: api.method,
url: `${this.endpoint}${api.url}`,
data: body,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.bearerToken}`
}
});
return response.data;
} catch (error) {
HttpErrorHandler.handleError("golomt", error);
}
});
}
};
// src/ebarimt/client.ts
var import_axios4 = __toESM(require("axios"));
var EbarimtClient = class {
constructor(config) {
this.endpoint = config.endpoint;
}
float64ToString(f) {
return f.toFixed(2);
}
stockInputToStock(input) {
let amount = 0;
let vat = 0;
let citytax = 0;
const stocks = [];
for (const v of input) {
amount += v.unitPrice * v.qty;
vat += v.vat;
citytax += v.cityTax;
stocks.push({
code: v.code,
name: v.name,
qty: this.float64ToString(v.qty),
measureUnit: v.measureUnit,
unitPrice: this.float64ToString(v.unitPrice),
cityTax: this.float64ToString(v.cityTax),
vat: this.float64ToString(v.vat),
barCode: v.barCode,
totalAmount: this.float64ToString(v.unitPrice * v.qty)
});
}
return { stocks, amount, vat, citytax };
}
createInputToRequestBody(input) {
const districtCode = input.districtCode || "34";
const branchNo = input.branchNo || "001";
const { stocks, amount, vat, citytax } = this.stockInputToStock(input.stocks);
return {
amount: this.float64ToString(amount),
vat: this.float64ToString(vat),
cashAmount: this.float64ToString(0),
nonCashAmount: this.float64ToString(amount),
cityTax: this.float64ToString(citytax),
customerNo: input.customerNo,
billType: input.billType,
branchNo,
districtCode,
billIdSuffix: input.billIdSuffix,
stocks
};
}
getNewEbarimt(input) {
return __async(this, null, function* () {
const body = this.createInputToRequestBody(input);
if (input.billType === "3" && !body.customerNo) {
throw new Error("CustomerNo is required for organization type bills");
}
const response = yield import_axios4.default.post(`${this.endpoint}/put`, body, {
headers: {
"Content-Type": "application/json"
}
});
return response.data;
});
}
sendData() {
return __async(this, null, function* () {
yield import_axios4.default.get(`${this.endpoint}/sendData`);
});
}
returnBill(billId, date) {
return __async(this, null, function* () {
const response = yield import_axios4.default.post(
`${this.endpoint}/returnBill`,
{
returnBillId: billId,
date
},
{
headers: {
"Content-Type": "application/json"
}
}
);
return response.data.success;
});
}
checkApi() {
return __async(this, null, function* () {
const response = yield import_axios4.default.get(`${this.endpoint}/checkApi`);
return response.data;
});
}
};
// src/hipay/client.ts
var import_axios5 = __toESM(require("axios"));
// src/hipay/apis.ts
var HipayCheckout = {
url: "/checkout",
method: "POST"
};
var HipayCheckoutGet = {
url: "/checkout/get/",
method: "GET"
};
var HipayPaymentGet = {
url: "/payment/get/",
method: "GET"
};
var HipayPaymentCorrection = {
url: "/pos/correction",
method: "POST"
};
var HipayStatement = {
url: "/pos/statement",
method: "POST"
};
// src/hipay/client.ts
var MAX_RETRIES2 = 3;
var TIMEOUT_MS2 = 3e4;
var RETRY_DELAY_MS2 = 1e3;
var HipayClient = class {
constructor(config) {
this.endpoint = config.endpoint;
this.token = config.token;
this.entityId = config.entityId;
}
sleep(ms) {
return __async(this, null, function* () {
return new Promise((resolve) => setTimeout(resolve, ms));
});
}
makeRequest(config) {
return __async(this, null, function* () {
var _a;
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES2; attempt++) {
try {
console.log(`[HipayClient] Making ${config.method} request to ${config.url} (Attempt ${attempt}/${MAX_RETRIES2})`);
const response = yield (0, import_axios5.default)(config);
const data = response.data;
if (((_a = data.result) == null ? void 0 : _a.code) && data.result.code !== "000.000.000") {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: `${data.result.code}: ${data.result.description || "Payment failed"}`,
provider: "hipay",
requestId: data.id || data.result.code
});
}
console.log(`[HipayClient] Successfully completed ${config.method} request to ${config.url}`);
return data;
} catch (error) {
lastError = error;
if (error instanceof PaymentError) {
throw error;
}
const isRetryable = error.code === "ECONNABORTED" || // Timeout
error.code === "ECONNRESET" || // Connection reset
error.code === "ETIMEDOUT" || // Connection timeout
error.response && error.response.status >= 500;
if (!isRetryable || attempt === MAX_RETRIES2) {
break;
}
console.log(`[HipayClient] Request failed, retrying in ${RETRY_DELAY_MS2}ms... (Error: ${error.message})`);
yield this.sleep(RETRY_DELAY_MS2 * attempt);
}
}
HttpErrorHandler.handleError("hipay", lastError);
});
}
httpRequest(body, api) {
return __async(this, null, function* () {
const config = {
method: api.method,
url: this.endpoint + api.url,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.token}`
},
data: body,
timeout: TIMEOUT_MS2
};
return this.makeRequest(config);
});
}
checkout(amount) {
return __async(this, null, function* () {
const request = {
entityId: this.entityId,
amount,
currency: "MNT",
qrData: true,
signal: false
};
return this.httpRequest(request, HipayCheckout);
});
}
checkoutGet(checkoutId) {
return __async(this, null, function* () {
const ext = `${checkoutId}?entityId=${this.entityId}`;
return this.httpRequest(null, HipayCheckoutGet);
});
}
paymentGet(paymentId) {
return __async(this, null, function* () {
const ext = `${paymentId}?entityId=${this.entityId}`;
return this.httpRequest(null, HipayPaymentGet);
});
}
paymentCorrection(paymentId) {
return __async(this, null, function* () {
const request = {
entityId: this.entityId,
paymentId
};
return this.httpRequest(request, HipayPaymentCorrection);
});
}
statement(date) {
return __async(this, null, function* () {
const request = {
entityId: this.entityId,
date
};
return this.httpRequest(request, HipayStatement);
});
}
};
// src/mongolchat/client.ts
var import_axios6 = __toESM(require("axios"));
// src/mongolchat/apis.ts
var MchatAuth = {
url: "/application/auth",
method: "GET"
};
var MchatOnlineQrGenerate = {
url: "/worker/onlineqr/generate",
method: "POST"
};
var MchatOnlineQrcheck = {
url: "/worker/onlineqr/status",
method: "POST"
};
var MchatTransactionSettlement = {
url: "/worker/settle/upload",
method: "POST"
};
// src/mongolchat/client.ts
var MAX_RETRIES3 = 3;
var TIMEOUT_MS3 = 3e4;
var RETRY_DELAY_MS3 = 1e3;
var MongolchatClient = class {
constructor(config) {
this.endpoint = config.endpoint;
this.apiKey = config.apiKey;
this.workerKey = config.workerKey;
this.appSecret = config.appSecret;
this.branchNo = config.branchNo;
}
sleep(ms) {
return __async(this, null, function* () {
return new Promise((resolve) => setTimeout(resolve, ms));
});
}
makeRequest(config) {
return __async(this, null, function* () {
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES3; attempt++) {
try {
console.log(`[MongolchatClient] Making ${config.method} request to ${config.url} (Attempt ${attempt}/${MAX_RETRIES3})`);
const response = yield (0, import_axios6.default)(config);
const data = response.data;
if (data.code !== 1e3) {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: data.message || "Payment failed",
provider: "mongolchat",
requestId: data.referenceNumber || data.code
});
}
console.log(`[MongolchatClient] Successfully completed ${config.method} request to ${config.url}`);
return data;
} catch (error) {
lastError = error;
if (error instanceof PaymentError) {
throw error;
}
const isRetryable = error.code === "ECONNABORTED" || // Timeout
error.code === "ECONNRESET" || // Connection reset
error.code === "ETIMEDOUT" || // Connection timeout
error.response && error.response.status >= 500;
if (!isRetryable || attempt === MAX_RETRIES3) {
break;
}
console.log(`[MongolchatClient] Request failed, retrying in ${RETRY_DELAY_MS3}ms... (Error: ${error.message})`);
yield this.sleep(RETRY_DELAY_MS3 * attempt);
}
}
HttpErrorHandler.handleError("mongolchat", lastError);
});
}
httpRequest(body, api) {
return __async(this, null, function* () {
const config = {
method: api.method,
url: this.endpoint + api.url,
headers: {
"Content-Type": "application/json",
"api-key": this.apiKey,
"Authorization": `WorkerKey ${this.workerKey}`
},
data: body,
timeout: TIMEOUT_MS3
};
return this.makeRequest(config);
});
}
generateQR(input) {
return __async(this, null, function* () {
return this.httpRequest(input, MchatOnlineQrGenerate);
});
}
checkQR(qr) {
return __async(this, null, function* () {
return this.httpRequest({ qr }, MchatOnlineQrcheck);
});
}
};
// src/pass/client.ts
var import_axios7 = __toESM(require("axios"));
// src/pass/apis.ts
var PassCreateOrder = {
url: "/create_order",
method: "POST"
};
var PassInqueryOrder = {
url: "/order_inquiry",
method: "POST"
};
var PassNotifyOrder = {
url: "/order_notify",
method: "POST"
};
var PassCancelOrder = {
url: "/cancel_order",
method: "POST"
};
var PassVoidOrder = {
url: "/void",
method: "POST"
};
// src/pass/client.ts
var MAX_RETRIES4 = 3;
var TIMEOUT_MS4 = 3e4;
var RETRY_DELAY_MS4 = 1e3;
var PassClient = class {
constructor(config) {
this.endpoint = config.endpoint;
this.ecommerceToken = config.ecommerceToken;
this.callback = config.callback;
}
sleep(ms) {
return __async(this, null, function* () {
return new Promise((resolve) => setTimeout(resolve, ms));
});
}
makeRequest(config) {
return __async(this, null, function* () {
var _a;
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES4; attempt++) {
try {
console.log(`[PassClient] Making ${config.method} request to ${config.url} (Attempt ${attempt}/${MAX_RETRIES4})`);
const response = yield (0, import_axios7.default)(config);
const data = response.data;
if ((_a = data.msg) == null ? void 0 : _a.code) {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: `[${data.msg.code}] (${data.msg.level}) ${data.msg.body}`,
provider: "pass",
requestId: data.orderId || data.msg.code
});
}
console.log(`[PassClient] Successfully completed ${config.method} request to ${config.url}`);
return data;
} catch (error) {
lastError = error;
if (error instanceof PaymentError) {
throw error;
}
const isRetryable = error.code === "ECONNABORTED" || // Timeout
error.code === "ECONNRESET" || // Connection reset
error.code === "ETIMEDOUT" || // Connection timeout
error.response && error.response.status >= 500;
if (!isRetryable || attempt === MAX_RETRIES4) {
break;
}
console.log(`[PassClient] Request failed, retrying in ${RETRY_DELAY_MS4}ms... (Error: ${error.message})`);
yield this.sleep(RETRY_DELAY_MS4 * attempt);
}
}
HttpErrorHandler.handleError("pass", lastError);
});
}
httpRequestPass(body, api) {
return __async(this, null, function* () {
const config = {
method: api.method,
url: this.endpoint + api.url,
headers: {
"Content-Type": "application/json"
},
data: body,
timeout: TIMEOUT_MS4
};
return this.makeRequest(config);
});
}
createOrder(amount, callbackParams) {
return __async(this, null, function* () {
const params = new URLSearchParams(callbackParams);
const request = {
ecommerceToken: this.ecommerceToken,
amount: amount * 100,
// Convert to cents
callbackUrl: `${this.callback}?${params.toString()}`
};
return this.httpRequestPass(request, PassCreateOrder);
});
}
inqueryOrder(orderId) {
return __async(this, null, function* () {
const request = {
ecommerceToken: this.ecommerceToken,
orderId
};
return this.httpRequestPass(request, PassInqueryOrder);
});
}
notifyOrder(orderId, phone) {
return __async(this, null, function* () {
const request = {
ecommerceToken: this.ecommerceToken,
orderId,
phone
};
return this.httpRequestPass(request, PassNotifyOrder);
});
}
cancelOrder(orderId) {
return __async(this, null, function* () {
const request = {
ecommerceToken: this.ecommerceToken,
orderId
};
return this.httpRequestPass(request, PassCancelOrder);
});
}
voidOrder(orderId) {
return __async(this, null, function* () {
const request = {
ecommerceToken: this.ecommerceToken,
orderId
};
return this.httpRequestPass(request, PassVoidOrder);
});
}
};
// src/socialpay/apis.ts
var SocialPayInvoicePhone = {
url: "/pos/invoice/phone",
method: "POST"
};
var SocialPayInvoiceQr = {
url: "/pos/invoice/qr",
method: "POST"
};
var SocialPayInvoiceCancel = {
url: "/pos/invoice/cancel",
method: "POST"
};
var SocialPayInvoiceCheck = {
url: "/pos/invoice/check",
method: "POST"
};
var SocialPayPaymentCancel = {
url: "/pos/payment/cancel",
method: "POST"
};
var SocialPayPaymentSettlement = {
url: "/pos/settlement",
method: "POST"
};
// src/socialpay/client.ts
var SocialPayClient = class {
constructor(config) {
this.endpoint = config.endpoint;
}
httpRequest(body, api) {
return __async(this, null, function* () {
try {
const response = yield fetch(this.endpoint + api.url, {
method: api.method,
headers: {
"Content-Type": "application/json"
},
body: body ? JSON.stringify(body) : void 0
});
if (!response.ok) {
const errorText = yield response.text();
throw new PaymentError({
code: "PROVIDER_ERROR" /* PROVIDER_ERROR */,
message: `HTTP error! status: ${response.status} - ${errorText}`,
provider: "socialpay"
});
}
const data = yield response.json();
if (data.code && data.code !== 0) {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: data.message || "Payment failed",
provider: "socialpay",
requestId: data.id
});
}
return data;
} catch (error) {
HttpErrorHandler.handleError("socialpay", error);
}
});
}
createInvoicePhone(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayInvoicePhone);
});
}
createInvoiceQr(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayInvoiceQr);
});
}
cancelInvoice(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayInvoiceCancel);
});
}
checkInvoice(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayInvoiceCheck);
});
}
cancelPayment(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayPaymentCancel);
});
}
settlement(request) {
return __async(this, null, function* () {
return this.httpRequest(request, SocialPayPaymentSettlement);
});
}
};
// src/storepay/apis.ts
var StorepayAuth = {
url: "/oauth/token",
method: "POST"
};
var StorepayLoan = {
url: "/merchant/loan",
method: "POST"
};
var StorepayLoanCheck = {
url: "/merchant/loan/check/",
method: "GET"
};
var StorepayUserPossibleAmount = {
url: "/user/possibleAmount",
method: "POST"
};
// src/storepay/client.ts
var MAX_RETRIES5 = 3;
var TIMEOUT_MS5 = 3e4;
var RETRY_DELAY_MS5 = 1e3;
var StorepayClient = class {
constructor(config) {
this.appUsername = config.appUsername;
this.appPassword = config.appPassword;
this.username = config.username;
this.password = config.password;
this.authUrl = config.authUrl;
this.baseUrl = config.baseUrl;
this.storeId = config.storeId;
this.callbackUrl = config.callbackUrl;
this.expireIn = null;
this.loginObject = null;
}
sleep(ms) {
return __async(this, null, function* () {
return new Promise((resolve) => setTimeout(resolve, ms));
});
}
makeRequest(url, options) {
return __async(this, null, function* () {
var _a, _b, _c, _d;
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES5; attempt++) {
try {
console.log(`[StorepayClient] Making ${options.method} request to ${url} (Attempt ${attempt}/${MAX_RETRIES5})`);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS5);
const response = yield fetch(url, __spreadProps(__spreadValues({}, options), {
signal: controller.signal
}));
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = yield response.text();
throw new PaymentError({
code: "PROVIDER_ERROR" /* PROVIDER_ERROR */,
message: `HTTP error! status: ${response.status} - ${errorText}`,
provider: "storepay"
});
}
const data = yield response.json();
if (data.status !== "Success") {
throw new PaymentError({
code: "PAYMENT_FAILED" /* PAYMENT_FAILED */,
message: `${data.status}: ${((_b = (_a = data.msgList) == null ? void 0 : _a[0]) == null ? void 0 : _b.code) || ""} - ${((_d = (_c = data.msgList) == null ? void 0 : _c[0]) == null ? void 0 : _d.text) || ""}`,
provider: "storepay",
requestId: data.id
});
}
console.log(`[StorepayClient] Successfully completed ${options.method} request to ${url}`);
return data;
} catch (error) {
lastError = error;
if (error instanceof PaymentError) {
throw error;
}
const isRetryable = error.name === "AbortError" || // Timeout
error.name === "TypeError" || // Network error
error.response && error.response.status >= 500;
if (!isRetryable || attempt === MAX_RETRIES5) {
break;
}
console.log(`[StorepayClient] Request failed, retrying in ${RETRY_DELAY_MS5}ms... (Error: ${error.message})`);
yield this.sleep(RETRY_DELAY_MS5 * attempt);
}
}
HttpErrorHandler.handleError("storepay", lastError);
});
}
httpRequest(body, api, urlExt = "") {
return __async(this, null, function* () {
try {
const authObj = yield this.authStorepay();
this.loginObject = authObj;
const url = this.baseUrl + api.url + urlExt;
const options = {
method: api.method,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.loginObject.access_token}`
}
};
if (body) {
options.body = JSON.stringify(body);
}
return this.makeRequest(url, options);
} catch (error) {
HttpErrorHandler.handleError("storepay", error);
}
});
}
authStorepay() {
return __async(this, null, function* () {
if (this.loginObject && this.expireIn && Date.now() < this.expireIn) {
return this.loginObject;
}
const url = `${this.authUrl}${StorepayAuth.url}?grant_type=password&username=${this.appUsername}&password=${this.appPassword}`;
const options = {
method: StorepayAuth.method,
headers: {
"Content-Type": "application/json",
"Authorization": `Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`
}
};
try {
console.log(`[StorepayClient] Making authentication request (Attempt 1/1)`);
const response = yield this.makeRequest(url, options);
this.expireIn = Date.now() + response.expires_in * 1e3;
console.log(`[StorepayClient] Successfully authenticated`);
return response;
} catch (error) {
HttpErrorHandler.handleError("storepay", error);
}
});
}
loan(input) {
return __async(this, null, function* () {
const request = {
storeId: this.storeId,
mobileNumber: input.mobileNumber,
description: input.description,
amount: input.amount.toString(),
callbackUrl: this.callbackUrl
};
const response = yield this.httpRequest(request, StorepayLoan);
return response.value;
});
}
loanCheck(id) {
return __async(this, null, function* () {
const response = yield this.httpRequest(null, StorepayLoanCheck, id);
return response.value;
});
}
userPossibleAmount(mobileNumber) {
return __async(this, null, function* () {
const request = {
mobileNumber
};
const response = yield this.httpRequest(request, StorepayUserPossibleAmount);
return response.value;
});
}
close() {
this.expireIn = null;
this.loginObject = null;
}
};
// src/tokipay/client.ts
var import_axios8 = __toESM(require("axios"));
// src/tokipay/apis.ts
var TokipayPaymentQr = {
url: "/jump/v4/spose/payment/request",
method: "POST"
};
var TokipayPaymentSentUser = {
url: "/jump/v4/spose/payment/user-request",
method: "POST"
};
var TokipayPaymentScanUser = {
url: "/jump/v4/spose/payment/scan/user-request",
method: "POST"
};
var TokipayPaymentStatus = {
url: "/jump/v4/spose/payment/status",
method: "GET"
};
var TokipayPaymentCancel = {
url: "/jump/v4/spose/payment/request",
method: "DELETE"
};
var TokipayRefund = {
url: "/jump/v4/spose/payment/refund",
method: "PUT"
};
var TokipayDeeplink = {
url: "/jump/v1/third-party/payment/deeplink",
method: "POST"
};
var TokipayPhoneRequest = {
url: "/jump/v1/third-party/payment/request",
method: "POST"
};
var TokipayTransactionStatus = {
url: "/jump/v1/third-party/payment/status",
method: "GET"
};
// src/tokipay/client.ts
var MAX_RETRIES6 = 3;
var TIMEOUT_MS6