@bijayx/nepal-pay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +319 -2
- package/dist/index.cjs +1039 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +427 -0
- package/dist/index.d.ts +427 -0
- package/dist/index.js +1016 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1016 @@
|
|
|
1
|
+
import { timingSafeEqual, createHmac } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/core/errors/nepal-pay-error.ts
|
|
4
|
+
var ErrorCode = {
|
|
5
|
+
CONFIGURATION_ERROR: "CONFIGURATION_ERROR",
|
|
6
|
+
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
7
|
+
AUTHENTICATION_FAILED: "AUTHENTICATION_FAILED",
|
|
8
|
+
GATEWAY_ERROR: "GATEWAY_ERROR",
|
|
9
|
+
NETWORK_ERROR: "NETWORK_ERROR",
|
|
10
|
+
TIMEOUT: "TIMEOUT",
|
|
11
|
+
INVALID_CALLBACK: "INVALID_CALLBACK",
|
|
12
|
+
INVALID_SIGNATURE: "INVALID_SIGNATURE",
|
|
13
|
+
AMOUNT_MISMATCH: "AMOUNT_MISMATCH",
|
|
14
|
+
REFERENCE_MISMATCH: "REFERENCE_MISMATCH"
|
|
15
|
+
};
|
|
16
|
+
var NepalPayError = class extends Error {
|
|
17
|
+
gateway;
|
|
18
|
+
details;
|
|
19
|
+
constructor(message, options = {}) {
|
|
20
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
21
|
+
this.name = new.target.name;
|
|
22
|
+
this.gateway = options.gateway ?? null;
|
|
23
|
+
this.details = Object.freeze({ ...options.details ?? {} });
|
|
24
|
+
}
|
|
25
|
+
/** Plain-object form for structured logging / API error responses. */
|
|
26
|
+
toJSON() {
|
|
27
|
+
return {
|
|
28
|
+
name: this.name,
|
|
29
|
+
code: this.code,
|
|
30
|
+
message: this.message,
|
|
31
|
+
gateway: this.gateway,
|
|
32
|
+
details: this.details
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/core/errors/index.ts
|
|
38
|
+
var ConfigurationError = class extends NepalPayError {
|
|
39
|
+
code = ErrorCode.CONFIGURATION_ERROR;
|
|
40
|
+
};
|
|
41
|
+
var ValidationError = class _ValidationError extends NepalPayError {
|
|
42
|
+
code = ErrorCode.VALIDATION_ERROR;
|
|
43
|
+
/** Field name → messages, e.g. `{ amount: ['must be an integer number of paisa'] }`. */
|
|
44
|
+
fields;
|
|
45
|
+
constructor(message, fields = {}, options) {
|
|
46
|
+
super(message, { ...options, details: { ...options?.details, fields } });
|
|
47
|
+
this.fields = Object.freeze({ ...fields });
|
|
48
|
+
}
|
|
49
|
+
/** Build from a field map; the message summarises the first problem. */
|
|
50
|
+
static fromFields(fields, options) {
|
|
51
|
+
const [field, messages] = Object.entries(fields)[0] ?? ["input", ["is invalid"]];
|
|
52
|
+
return new _ValidationError(`Invalid ${field}: ${messages[0] ?? "is invalid"}`, fields, options);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var AuthenticationError = class extends NepalPayError {
|
|
56
|
+
code = ErrorCode.AUTHENTICATION_FAILED;
|
|
57
|
+
};
|
|
58
|
+
var GatewayError = class extends NepalPayError {
|
|
59
|
+
code = ErrorCode.GATEWAY_ERROR;
|
|
60
|
+
statusCode;
|
|
61
|
+
responseBody;
|
|
62
|
+
/** True when trying again later may succeed (5xx, or the gateway says it is unavailable). */
|
|
63
|
+
retryable;
|
|
64
|
+
constructor(message, options = {}) {
|
|
65
|
+
super(message, {
|
|
66
|
+
...options,
|
|
67
|
+
details: { ...options.details, statusCode: options.statusCode ?? null }
|
|
68
|
+
});
|
|
69
|
+
this.statusCode = options.statusCode ?? null;
|
|
70
|
+
this.responseBody = options.responseBody;
|
|
71
|
+
this.retryable = options.retryable ?? (this.statusCode === null || this.statusCode >= 500);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var NetworkError = class extends NepalPayError {
|
|
75
|
+
code;
|
|
76
|
+
constructor(message, options = {}) {
|
|
77
|
+
super(message, options);
|
|
78
|
+
this.code = options.timeout === true ? ErrorCode.TIMEOUT : ErrorCode.NETWORK_ERROR;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
var InvalidCallbackError = class extends NepalPayError {
|
|
82
|
+
code = ErrorCode.INVALID_CALLBACK;
|
|
83
|
+
};
|
|
84
|
+
var InvalidSignatureError = class extends NepalPayError {
|
|
85
|
+
code = ErrorCode.INVALID_SIGNATURE;
|
|
86
|
+
};
|
|
87
|
+
var PaymentMismatchError = class extends NepalPayError {
|
|
88
|
+
code;
|
|
89
|
+
expected;
|
|
90
|
+
actual;
|
|
91
|
+
constructor(code, expected, actual, options) {
|
|
92
|
+
const what = code === ErrorCode.AMOUNT_MISMATCH ? "amount" : "reference";
|
|
93
|
+
super(`Payment ${what} mismatch: expected ${String(expected)}, got ${String(actual)}`, {
|
|
94
|
+
...options,
|
|
95
|
+
details: { ...options?.details, expected, actual }
|
|
96
|
+
});
|
|
97
|
+
this.code = code;
|
|
98
|
+
this.expected = expected;
|
|
99
|
+
this.actual = actual;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
function isNepalPayError(error) {
|
|
103
|
+
return error instanceof NepalPayError;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/core/http/http-client.ts
|
|
107
|
+
var USER_AGENT = "@bijayx/nepal-pay (+https://github.com/BijayX/nepal-pay-node)";
|
|
108
|
+
var HttpClient = class {
|
|
109
|
+
constructor(gateway, options = {}) {
|
|
110
|
+
this.gateway = gateway;
|
|
111
|
+
this.timeoutMs = options.timeoutMs ?? 15e3;
|
|
112
|
+
this.retries = Math.max(0, options.retries ?? 2);
|
|
113
|
+
this.retryDelayMs = Math.max(0, options.retryDelayMs ?? 200);
|
|
114
|
+
this.fetchFn = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
115
|
+
this.logger = options.logger;
|
|
116
|
+
}
|
|
117
|
+
gateway;
|
|
118
|
+
timeoutMs;
|
|
119
|
+
retries;
|
|
120
|
+
retryDelayMs;
|
|
121
|
+
fetchFn;
|
|
122
|
+
logger;
|
|
123
|
+
async send(request) {
|
|
124
|
+
const attempts = request.idempotent ? this.retries + 1 : 1;
|
|
125
|
+
let lastError;
|
|
126
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
127
|
+
if (attempt > 0) await sleep(this.retryDelayMs * 2 ** (attempt - 1));
|
|
128
|
+
try {
|
|
129
|
+
const response = await this.attempt(request);
|
|
130
|
+
if (response.status >= 500 && attempt < attempts - 1) {
|
|
131
|
+
this.logger?.warn(
|
|
132
|
+
"nepal-pay: gateway 5xx, retrying",
|
|
133
|
+
this.logContext(request, { status: response.status, attempt })
|
|
134
|
+
);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
return response;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (!(error instanceof NetworkError)) throw error;
|
|
140
|
+
lastError = error;
|
|
141
|
+
if (attempt < attempts - 1) {
|
|
142
|
+
this.logger?.warn(
|
|
143
|
+
"nepal-pay: network error, retrying",
|
|
144
|
+
this.logContext(request, { code: error.code, attempt })
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
throw lastError ?? new NetworkError("Request failed", { gateway: this.gateway });
|
|
150
|
+
}
|
|
151
|
+
async attempt(request) {
|
|
152
|
+
const headers = {
|
|
153
|
+
Accept: "application/json",
|
|
154
|
+
"User-Agent": USER_AGENT,
|
|
155
|
+
...request.headers
|
|
156
|
+
};
|
|
157
|
+
const init = {
|
|
158
|
+
method: request.method,
|
|
159
|
+
headers,
|
|
160
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
161
|
+
};
|
|
162
|
+
if (request.json !== void 0) {
|
|
163
|
+
headers["Content-Type"] = "application/json";
|
|
164
|
+
init.body = JSON.stringify(request.json);
|
|
165
|
+
}
|
|
166
|
+
const started = Date.now();
|
|
167
|
+
let response;
|
|
168
|
+
try {
|
|
169
|
+
response = await this.fetchFn(request.url, init);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
const timeout = isTimeout(error);
|
|
172
|
+
throw new NetworkError(
|
|
173
|
+
timeout ? `${this.gateway} did not respond within ${this.timeoutMs} ms` : `Could not reach ${this.gateway}: ${error instanceof Error ? error.message : String(error)}`,
|
|
174
|
+
{ gateway: this.gateway, timeout, cause: error, details: { url: request.url } }
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
const body = parseBody(await response.text());
|
|
178
|
+
this.logger?.debug(
|
|
179
|
+
"nepal-pay: request",
|
|
180
|
+
this.logContext(request, { status: response.status, durationMs: Date.now() - started })
|
|
181
|
+
);
|
|
182
|
+
return { status: response.status, body };
|
|
183
|
+
}
|
|
184
|
+
/** Never includes headers or bodies — they carry secret keys and customer data. */
|
|
185
|
+
logContext(request, extra) {
|
|
186
|
+
return {
|
|
187
|
+
gateway: this.gateway,
|
|
188
|
+
method: request.method,
|
|
189
|
+
url: stripQuery(request.url),
|
|
190
|
+
...extra
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
function parseBody(text) {
|
|
195
|
+
if (text.trim() === "") return null;
|
|
196
|
+
try {
|
|
197
|
+
return JSON.parse(text);
|
|
198
|
+
} catch {
|
|
199
|
+
return text;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function isTimeout(error) {
|
|
203
|
+
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
204
|
+
}
|
|
205
|
+
function stripQuery(url) {
|
|
206
|
+
const index = url.indexOf("?");
|
|
207
|
+
return index === -1 ? url : url.slice(0, index);
|
|
208
|
+
}
|
|
209
|
+
function sleep(ms) {
|
|
210
|
+
return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// src/core/types.ts
|
|
214
|
+
var PaymentStatus = {
|
|
215
|
+
/** Money received. The only status that should fulfil an order. */
|
|
216
|
+
COMPLETED: "completed",
|
|
217
|
+
PENDING: "pending",
|
|
218
|
+
INITIATED: "initiated",
|
|
219
|
+
REFUNDED: "refunded",
|
|
220
|
+
PARTIALLY_REFUNDED: "partially_refunded",
|
|
221
|
+
EXPIRED: "expired",
|
|
222
|
+
CANCELED: "canceled",
|
|
223
|
+
FAILED: "failed",
|
|
224
|
+
/** eSewa: payment is in a halted state — hold the order and re-check later. */
|
|
225
|
+
AMBIGUOUS: "ambiguous",
|
|
226
|
+
NOT_FOUND: "not_found",
|
|
227
|
+
/** The gateway returned a status this library does not know; inspect `raw`. */
|
|
228
|
+
UNKNOWN: "unknown"
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// src/core/gateway.ts
|
|
232
|
+
var BaseGateway = class {
|
|
233
|
+
environment;
|
|
234
|
+
http;
|
|
235
|
+
constructor(gatewayName, options) {
|
|
236
|
+
const environment = options.environment ?? "sandbox";
|
|
237
|
+
if (environment !== "sandbox" && environment !== "production") {
|
|
238
|
+
throw new ConfigurationError(`environment must be "sandbox" or "production"`, {
|
|
239
|
+
gateway: gatewayName
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
this.environment = environment;
|
|
243
|
+
this.http = new HttpClient(gatewayName, options);
|
|
244
|
+
}
|
|
245
|
+
get isSandbox() {
|
|
246
|
+
return this.environment === "sandbox";
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Applies the expectations stored at initiate time.
|
|
250
|
+
* Reference is always checked; amount only matters once money has moved.
|
|
251
|
+
*/
|
|
252
|
+
assertExpected(result, expected) {
|
|
253
|
+
if (!expected) return result;
|
|
254
|
+
if (expected.reference !== void 0 && expected.reference !== result.reference) {
|
|
255
|
+
throw new PaymentMismatchError(
|
|
256
|
+
ErrorCode.REFERENCE_MISMATCH,
|
|
257
|
+
expected.reference,
|
|
258
|
+
result.reference,
|
|
259
|
+
{
|
|
260
|
+
gateway: this.name
|
|
261
|
+
}
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (result.status === PaymentStatus.COMPLETED && expected.amount !== result.amount) {
|
|
265
|
+
throw new PaymentMismatchError(ErrorCode.AMOUNT_MISMATCH, expected.amount, result.amount, {
|
|
266
|
+
gateway: this.name
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
result(fields) {
|
|
272
|
+
return { gateway: this.name, isPaid: fields.status === PaymentStatus.COMPLETED, ...fields };
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
function callbackValue(params, key) {
|
|
276
|
+
const value = params[key];
|
|
277
|
+
const first = Array.isArray(value) ? value[0] : value;
|
|
278
|
+
return first === void 0 || first.trim() === "" ? void 0 : first;
|
|
279
|
+
}
|
|
280
|
+
function requireOption(value, name, gateway, envHint) {
|
|
281
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
282
|
+
throw new ConfigurationError(`${gateway}: "${name}" is required (usually from ${envHint})`, {
|
|
283
|
+
gateway
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
return value;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// src/core/money.ts
|
|
290
|
+
function assertPaisa(value, field = "amount", { allowZero = false } = {}) {
|
|
291
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
|
|
292
|
+
throw ValidationError.fromFields({ [field]: ["must be an integer number of paisa"] });
|
|
293
|
+
}
|
|
294
|
+
if (value < 0 || !allowZero && value === 0) {
|
|
295
|
+
throw ValidationError.fromFields({
|
|
296
|
+
[field]: [allowZero ? "must not be negative" : "must be greater than zero"]
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
function paisaToRupeeString(paisa) {
|
|
302
|
+
assertPaisa(paisa, "amount", { allowZero: true });
|
|
303
|
+
const rupees = Math.trunc(paisa / 100);
|
|
304
|
+
const rest = paisa % 100;
|
|
305
|
+
return rest === 0 ? String(rupees) : `${rupees}.${String(rest).padStart(2, "0")}`;
|
|
306
|
+
}
|
|
307
|
+
var RUPEE_PATTERN = /^\d+(\.\d+)?$/;
|
|
308
|
+
function parseRupees(value, field = "total_amount") {
|
|
309
|
+
const text = typeof value === "number" ? String(value) : typeof value === "string" ? value : "";
|
|
310
|
+
const normalized = text.replace(/,/g, "").trim();
|
|
311
|
+
if (!RUPEE_PATTERN.test(normalized)) {
|
|
312
|
+
throw ValidationError.fromFields({ [field]: [`is not a valid rupee amount`] });
|
|
313
|
+
}
|
|
314
|
+
const [whole = "0", fraction = ""] = normalized.split(".");
|
|
315
|
+
const paisa = Number(whole) * 100 + Math.round(Number(`0.${fraction || "0"}`) * 100);
|
|
316
|
+
return assertPaisa(paisa, field, { allowZero: true });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/core/validation/validate-initiate.ts
|
|
320
|
+
var ORDER_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
|
|
321
|
+
var METADATA_KEY_PATTERN = /^[a-z0-9_]{1,50}$/;
|
|
322
|
+
var FieldErrors = class {
|
|
323
|
+
errors = {};
|
|
324
|
+
add(field, message) {
|
|
325
|
+
(this.errors[field] ??= []).push(message);
|
|
326
|
+
}
|
|
327
|
+
throwIfAny(gateway) {
|
|
328
|
+
if (Object.keys(this.errors).length > 0) {
|
|
329
|
+
throw ValidationError.fromFields(this.errors, { gateway });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
function isAbsoluteHttpUrl(value) {
|
|
334
|
+
if (typeof value !== "string") return false;
|
|
335
|
+
try {
|
|
336
|
+
const url = new URL(value);
|
|
337
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
338
|
+
} catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function isPaisa(value, allowZero) {
|
|
343
|
+
return typeof value === "number" && Number.isSafeInteger(value) && (allowZero ? value >= 0 : value > 0);
|
|
344
|
+
}
|
|
345
|
+
function nonBlank(value) {
|
|
346
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
347
|
+
}
|
|
348
|
+
function validateInitiateInput(input, gateway, rules = {}) {
|
|
349
|
+
const errors = new FieldErrors();
|
|
350
|
+
if (!isPaisa(input.amount, false)) {
|
|
351
|
+
errors.add("amount", "must be a positive integer number of paisa");
|
|
352
|
+
} else if (rules.minAmount !== void 0 && input.amount < rules.minAmount) {
|
|
353
|
+
errors.add("amount", `must be at least ${rules.minAmount} paisa`);
|
|
354
|
+
}
|
|
355
|
+
if (typeof input.orderId !== "string" || !ORDER_ID_PATTERN.test(input.orderId)) {
|
|
356
|
+
errors.add("orderId", "must be 1-64 characters: letters, digits and hyphens only");
|
|
357
|
+
}
|
|
358
|
+
if (!nonBlank(input.orderName)) {
|
|
359
|
+
errors.add("orderName", "is required");
|
|
360
|
+
} else if (input.orderName.length > 255) {
|
|
361
|
+
errors.add("orderName", "must be at most 255 characters");
|
|
362
|
+
}
|
|
363
|
+
if (!isAbsoluteHttpUrl(input.returnUrl))
|
|
364
|
+
errors.add("returnUrl", "must be an absolute http(s) URL");
|
|
365
|
+
if (input.failureUrl !== void 0 && !isAbsoluteHttpUrl(input.failureUrl)) {
|
|
366
|
+
errors.add("failureUrl", "must be an absolute http(s) URL");
|
|
367
|
+
}
|
|
368
|
+
const breakdown = {
|
|
369
|
+
tax: input.breakdown?.tax ?? 0,
|
|
370
|
+
serviceCharge: input.breakdown?.serviceCharge ?? 0,
|
|
371
|
+
deliveryCharge: input.breakdown?.deliveryCharge ?? 0
|
|
372
|
+
};
|
|
373
|
+
for (const [key, value] of Object.entries(breakdown)) {
|
|
374
|
+
if (!isPaisa(value, true))
|
|
375
|
+
errors.add(`breakdown.${key}`, "must be a non-negative integer number of paisa");
|
|
376
|
+
}
|
|
377
|
+
const extras = breakdown.tax + breakdown.serviceCharge + breakdown.deliveryCharge;
|
|
378
|
+
const baseAmount = (isPaisa(input.amount, false) ? input.amount : 0) - extras;
|
|
379
|
+
if (isPaisa(input.amount, false) && extras > 0 && baseAmount <= 0) {
|
|
380
|
+
errors.add("breakdown", "tax + service + delivery charges must be less than amount");
|
|
381
|
+
}
|
|
382
|
+
const metadata = input.metadata ?? {};
|
|
383
|
+
const metadataKeys = Object.keys(metadata);
|
|
384
|
+
if (rules.maxMetadataKeys !== void 0 && metadataKeys.length > rules.maxMetadataKeys) {
|
|
385
|
+
errors.add("metadata", `${gateway} accepts at most ${rules.maxMetadataKeys} metadata keys`);
|
|
386
|
+
}
|
|
387
|
+
for (const key of metadataKeys) {
|
|
388
|
+
if (!METADATA_KEY_PATTERN.test(key)) errors.add(`metadata.${key}`, "key must match [a-z0-9_]");
|
|
389
|
+
if (typeof metadata[key] !== "string") errors.add(`metadata.${key}`, "value must be a string");
|
|
390
|
+
}
|
|
391
|
+
if (input.customer?.email !== void 0 && !/^[^\s@]+@[^\s@]+$/.test(input.customer.email)) {
|
|
392
|
+
errors.add("customer.email", "must be a valid email address");
|
|
393
|
+
}
|
|
394
|
+
errors.throwIfAny(gateway);
|
|
395
|
+
return {
|
|
396
|
+
amount: input.amount,
|
|
397
|
+
baseAmount,
|
|
398
|
+
orderId: input.orderId,
|
|
399
|
+
orderName: input.orderName.trim(),
|
|
400
|
+
returnUrl: input.returnUrl,
|
|
401
|
+
failureUrl: input.failureUrl ?? input.returnUrl,
|
|
402
|
+
customer: input.customer ?? null,
|
|
403
|
+
breakdown,
|
|
404
|
+
metadata: { ...metadata }
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/gateways/esewa/esewa.config.ts
|
|
409
|
+
var ESEWA = "esewa";
|
|
410
|
+
var ESEWA_URLS = {
|
|
411
|
+
sandbox: {
|
|
412
|
+
form: "https://rc-epay.esewa.com.np/api/epay/main/v2/form",
|
|
413
|
+
status: "https://rc.esewa.com.np/api/epay/transaction/status/"
|
|
414
|
+
},
|
|
415
|
+
production: {
|
|
416
|
+
form: "https://epay.esewa.com.np/api/epay/main/v2/form",
|
|
417
|
+
status: "https://esewa.com.np/api/epay/transaction/status/"
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
var ESEWA_SANDBOX_CREDENTIALS = {
|
|
421
|
+
productCode: "EPAYTEST",
|
|
422
|
+
secretKey: "8gBm/:&EnhH.1/q"
|
|
423
|
+
};
|
|
424
|
+
var ESEWA_MAX_PROPERTIES = 3;
|
|
425
|
+
var ESEWA_REQUEST_SIGNED_FIELDS = [
|
|
426
|
+
"total_amount",
|
|
427
|
+
"transaction_uuid",
|
|
428
|
+
"product_code"
|
|
429
|
+
];
|
|
430
|
+
|
|
431
|
+
// src/gateways/esewa/esewa.callback.ts
|
|
432
|
+
var REQUIRED_FIELDS = ["total_amount", "transaction_uuid", "product_code"];
|
|
433
|
+
function decodeEsewaCallback(data) {
|
|
434
|
+
const base64 = data.trim().replace(/ /g, "+").replace(/-/g, "+").replace(/_/g, "/");
|
|
435
|
+
const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
|
|
436
|
+
let parsed;
|
|
437
|
+
try {
|
|
438
|
+
parsed = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
|
|
439
|
+
} catch (error) {
|
|
440
|
+
throw new InvalidCallbackError('eSewa callback "data" is not valid base64-encoded JSON', {
|
|
441
|
+
gateway: ESEWA,
|
|
442
|
+
cause: error
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
446
|
+
throw new InvalidCallbackError('eSewa callback "data" must decode to a JSON object', {
|
|
447
|
+
gateway: ESEWA
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
const record = {};
|
|
451
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
452
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
453
|
+
record[key] = String(value);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const missing = REQUIRED_FIELDS.filter((field) => record[field] === void 0);
|
|
457
|
+
if (missing.length > 0) {
|
|
458
|
+
throw new InvalidCallbackError(`eSewa callback is missing: ${missing.join(", ")}`, {
|
|
459
|
+
gateway: ESEWA,
|
|
460
|
+
details: { missing }
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
return record;
|
|
464
|
+
}
|
|
465
|
+
function hmacSha256Base64(secret, message) {
|
|
466
|
+
return createHmac("sha256", secret).update(message, "utf8").digest("base64");
|
|
467
|
+
}
|
|
468
|
+
function safeEqual(a, b) {
|
|
469
|
+
const left = Buffer.from(a, "utf8");
|
|
470
|
+
const right = Buffer.from(b, "utf8");
|
|
471
|
+
if (left.length !== right.length) return false;
|
|
472
|
+
return timingSafeEqual(left, right);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// src/gateways/esewa/esewa.signature.ts
|
|
476
|
+
function buildSignatureMessage(fieldNames, values) {
|
|
477
|
+
const parts = [];
|
|
478
|
+
for (const name of fieldNames) {
|
|
479
|
+
const value = values[name];
|
|
480
|
+
if (value === void 0) return null;
|
|
481
|
+
parts.push(`${name}=${value}`);
|
|
482
|
+
}
|
|
483
|
+
return parts.join(",");
|
|
484
|
+
}
|
|
485
|
+
function signEsewa(secretKey, message) {
|
|
486
|
+
return hmacSha256Base64(secretKey, message);
|
|
487
|
+
}
|
|
488
|
+
function verifyEsewaSignature(secretKey, payload) {
|
|
489
|
+
const signature = payload.signature;
|
|
490
|
+
const signedFieldNames = payload.signed_field_names;
|
|
491
|
+
if (!signature || !signedFieldNames) return false;
|
|
492
|
+
const names = signedFieldNames.split(",").map((name) => name.trim()).filter(Boolean);
|
|
493
|
+
if (names.length === 0 || names.includes("signature")) return false;
|
|
494
|
+
const message = buildSignatureMessage(names, payload);
|
|
495
|
+
return message !== null && safeEqual(signEsewa(secretKey, message), signature);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// src/gateways/esewa/esewa.status.ts
|
|
499
|
+
var STATUS_MAP = {
|
|
500
|
+
COMPLETE: PaymentStatus.COMPLETED,
|
|
501
|
+
COMPLETED: PaymentStatus.COMPLETED,
|
|
502
|
+
PENDING: PaymentStatus.PENDING,
|
|
503
|
+
FULL_REFUND: PaymentStatus.REFUNDED,
|
|
504
|
+
PARTIAL_REFUND: PaymentStatus.PARTIALLY_REFUNDED,
|
|
505
|
+
AMBIGUOUS: PaymentStatus.AMBIGUOUS,
|
|
506
|
+
NOT_FOUND: PaymentStatus.NOT_FOUND,
|
|
507
|
+
CANCELED: PaymentStatus.CANCELED,
|
|
508
|
+
CANCELLED: PaymentStatus.CANCELED
|
|
509
|
+
};
|
|
510
|
+
function mapEsewaStatus(status) {
|
|
511
|
+
const key = status.trim().toUpperCase().replace(/[\s-]+/g, "_");
|
|
512
|
+
return STATUS_MAP[key] ?? PaymentStatus.UNKNOWN;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/gateways/esewa/esewa.gateway.ts
|
|
516
|
+
var EsewaGateway = class extends BaseGateway {
|
|
517
|
+
name = ESEWA;
|
|
518
|
+
productCode;
|
|
519
|
+
secretKey;
|
|
520
|
+
formUrl;
|
|
521
|
+
statusUrl;
|
|
522
|
+
constructor(options = {}) {
|
|
523
|
+
super(ESEWA, options);
|
|
524
|
+
const fallback = this.isSandbox ? ESEWA_SANDBOX_CREDENTIALS : void 0;
|
|
525
|
+
const productCode = options.productCode ?? fallback?.productCode;
|
|
526
|
+
const secretKey = options.secretKey ?? fallback?.secretKey;
|
|
527
|
+
if (!productCode?.trim() || !secretKey?.trim()) {
|
|
528
|
+
throw new ConfigurationError(
|
|
529
|
+
'esewa: "productCode" and "secretKey" are required in production (ESEWA_PRODUCT_CODE, ESEWA_SECRET_KEY)',
|
|
530
|
+
{ gateway: ESEWA }
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
this.productCode = productCode;
|
|
534
|
+
this.secretKey = secretKey;
|
|
535
|
+
this.formUrl = options.formUrl ?? ESEWA_URLS[this.environment].form;
|
|
536
|
+
this.statusUrl = options.statusUrl ?? ESEWA_URLS[this.environment].status;
|
|
537
|
+
}
|
|
538
|
+
initiate(input) {
|
|
539
|
+
return new Promise((resolve) => {
|
|
540
|
+
resolve(this.buildPayment(input));
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
async verify({ callback, expected }) {
|
|
544
|
+
const data = callbackValue(callback, "data");
|
|
545
|
+
let reference;
|
|
546
|
+
let amount;
|
|
547
|
+
if (data !== void 0) {
|
|
548
|
+
const decoded = decodeEsewaCallback(data);
|
|
549
|
+
if (!verifyEsewaSignature(this.secretKey, decoded)) {
|
|
550
|
+
throw new InvalidSignatureError("eSewa callback signature is invalid", { gateway: ESEWA });
|
|
551
|
+
}
|
|
552
|
+
if (decoded.product_code !== this.productCode) {
|
|
553
|
+
throw new InvalidSignatureError("eSewa callback is for a different product code", {
|
|
554
|
+
gateway: ESEWA
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
reference = decoded.transaction_uuid;
|
|
558
|
+
amount = parseRupees(decoded.total_amount);
|
|
559
|
+
} else {
|
|
560
|
+
reference = expected?.reference;
|
|
561
|
+
amount = expected?.amount;
|
|
562
|
+
}
|
|
563
|
+
if (reference === void 0 || amount === void 0) {
|
|
564
|
+
throw new InvalidCallbackError(
|
|
565
|
+
'eSewa callback has no "data"; pass expected.reference and expected.amount to check the status',
|
|
566
|
+
{ gateway: ESEWA }
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
const result = await this.lookup({ reference, amount });
|
|
570
|
+
return this.assertExpected(result, expected);
|
|
571
|
+
}
|
|
572
|
+
async lookup({ reference, amount }) {
|
|
573
|
+
const fields = {};
|
|
574
|
+
if (typeof reference !== "string" || reference.trim() === "")
|
|
575
|
+
fields.reference = ["is required"];
|
|
576
|
+
if (amount === void 0) fields.amount = ["is required by eSewa status checks"];
|
|
577
|
+
if (Object.keys(fields).length > 0)
|
|
578
|
+
throw ValidationError.fromFields(fields, { gateway: ESEWA });
|
|
579
|
+
const total = paisaToRupeeString(assertPaisa(amount));
|
|
580
|
+
const query = new URLSearchParams({
|
|
581
|
+
product_code: this.productCode,
|
|
582
|
+
total_amount: total,
|
|
583
|
+
transaction_uuid: reference
|
|
584
|
+
});
|
|
585
|
+
const response = await this.http.send({
|
|
586
|
+
method: "GET",
|
|
587
|
+
url: `${this.statusUrl}?${query.toString()}`,
|
|
588
|
+
idempotent: true
|
|
589
|
+
});
|
|
590
|
+
return this.toResult(response, reference);
|
|
591
|
+
}
|
|
592
|
+
buildPayment(input) {
|
|
593
|
+
const payment = validateInitiateInput(input, ESEWA, { maxMetadataKeys: ESEWA_MAX_PROPERTIES });
|
|
594
|
+
const { tax, serviceCharge, deliveryCharge } = payment.breakdown;
|
|
595
|
+
const fields = {
|
|
596
|
+
amount: paisaToRupeeString(payment.baseAmount),
|
|
597
|
+
tax_amount: paisaToRupeeString(tax),
|
|
598
|
+
total_amount: paisaToRupeeString(payment.amount),
|
|
599
|
+
transaction_uuid: payment.orderId,
|
|
600
|
+
product_code: this.productCode,
|
|
601
|
+
product_service_charge: paisaToRupeeString(serviceCharge),
|
|
602
|
+
product_delivery_charge: paisaToRupeeString(deliveryCharge),
|
|
603
|
+
success_url: payment.returnUrl,
|
|
604
|
+
failure_url: payment.failureUrl,
|
|
605
|
+
signed_field_names: ESEWA_REQUEST_SIGNED_FIELDS.join(",")
|
|
606
|
+
};
|
|
607
|
+
const message = buildSignatureMessage(ESEWA_REQUEST_SIGNED_FIELDS, fields) ?? "";
|
|
608
|
+
fields.signature = signEsewa(this.secretKey, message);
|
|
609
|
+
for (const [key, value] of Object.entries(payment.metadata)) {
|
|
610
|
+
fields[`properties[${key}]`] = value;
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
gateway: ESEWA,
|
|
614
|
+
reference: payment.orderId,
|
|
615
|
+
orderId: payment.orderId,
|
|
616
|
+
amount: payment.amount,
|
|
617
|
+
redirect: { method: "POST", url: this.formUrl, fields: Object.freeze(fields) },
|
|
618
|
+
expiresAt: null,
|
|
619
|
+
raw: null
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
toResult(response, reference) {
|
|
623
|
+
const { status, body } = response;
|
|
624
|
+
if (isRecord(body) && typeof body.error_message === "string") {
|
|
625
|
+
throw new GatewayError(`eSewa status check failed: ${body.error_message}`, {
|
|
626
|
+
gateway: ESEWA,
|
|
627
|
+
statusCode: status,
|
|
628
|
+
responseBody: body,
|
|
629
|
+
retryable: true
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (status !== 200 || !isStatusBody(body)) {
|
|
633
|
+
throw new GatewayError(
|
|
634
|
+
`eSewa status check returned an unexpected response (HTTP ${status})`,
|
|
635
|
+
{
|
|
636
|
+
gateway: ESEWA,
|
|
637
|
+
statusCode: status,
|
|
638
|
+
responseBody: body
|
|
639
|
+
}
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
let amount;
|
|
643
|
+
try {
|
|
644
|
+
amount = parseRupees(body.total_amount);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
throw new GatewayError("eSewa status check returned an invalid total_amount", {
|
|
647
|
+
gateway: ESEWA,
|
|
648
|
+
statusCode: status,
|
|
649
|
+
responseBody: body,
|
|
650
|
+
cause: error
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
return this.result({
|
|
654
|
+
status: mapEsewaStatus(body.status),
|
|
655
|
+
reference: typeof body.transaction_uuid === "string" ? body.transaction_uuid : reference,
|
|
656
|
+
transactionId: typeof body.ref_id === "string" && body.ref_id !== "" ? body.ref_id : null,
|
|
657
|
+
amount,
|
|
658
|
+
fee: null,
|
|
659
|
+
raw: body
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
function isRecord(value) {
|
|
664
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
665
|
+
}
|
|
666
|
+
function isStatusBody(body) {
|
|
667
|
+
return isRecord(body) && typeof body.status === "string" && body.total_amount !== void 0;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/gateways/khalti/khalti.config.ts
|
|
671
|
+
var KHALTI = "khalti";
|
|
672
|
+
var KHALTI_MIN_AMOUNT = 1e3;
|
|
673
|
+
var KHALTI_BASE_URLS = {
|
|
674
|
+
sandbox: "https://dev.khalti.com/api/v2/",
|
|
675
|
+
production: "https://khalti.com/api/v2/"
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
// src/gateways/khalti/khalti.errors.ts
|
|
679
|
+
var NON_FIELD_KEYS = /* @__PURE__ */ new Set(["error_key", "detail", "status_code"]);
|
|
680
|
+
function isRecord2(value) {
|
|
681
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
682
|
+
}
|
|
683
|
+
function toKhaltiError(response, operation) {
|
|
684
|
+
const { status, body } = response;
|
|
685
|
+
const detail = isRecord2(body) && typeof body.detail === "string" ? body.detail : void 0;
|
|
686
|
+
if (status === 401 || status === 403) {
|
|
687
|
+
return new AuthenticationError(
|
|
688
|
+
`Khalti rejected the secret key${detail ? `: ${detail}` : ""}. Check KHALTI_SECRET_KEY and that it matches the environment.`,
|
|
689
|
+
{ gateway: KHALTI, details: { statusCode: status } }
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
if (status === 400 && isRecord2(body)) {
|
|
693
|
+
const fields = {};
|
|
694
|
+
for (const [key, value] of Object.entries(body)) {
|
|
695
|
+
if (NON_FIELD_KEYS.has(key)) continue;
|
|
696
|
+
fields[key] = Array.isArray(value) ? value.map(String) : [String(value)];
|
|
697
|
+
}
|
|
698
|
+
if (Object.keys(fields).length === 0 && detail) fields.request = [detail];
|
|
699
|
+
if (Object.keys(fields).length > 0) {
|
|
700
|
+
return ValidationError.fromFields(fields, { gateway: KHALTI });
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return new GatewayError(
|
|
704
|
+
`Khalti ${operation} failed with HTTP ${status}${detail ? `: ${detail}` : ""}`,
|
|
705
|
+
{
|
|
706
|
+
gateway: KHALTI,
|
|
707
|
+
statusCode: status,
|
|
708
|
+
responseBody: body
|
|
709
|
+
}
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// src/gateways/khalti/khalti.status.ts
|
|
714
|
+
var STATUS_MAP2 = {
|
|
715
|
+
completed: PaymentStatus.COMPLETED,
|
|
716
|
+
pending: PaymentStatus.PENDING,
|
|
717
|
+
initiated: PaymentStatus.INITIATED,
|
|
718
|
+
refunded: PaymentStatus.REFUNDED,
|
|
719
|
+
"partially refunded": PaymentStatus.PARTIALLY_REFUNDED,
|
|
720
|
+
expired: PaymentStatus.EXPIRED,
|
|
721
|
+
"user canceled": PaymentStatus.CANCELED,
|
|
722
|
+
"user cancelled": PaymentStatus.CANCELED,
|
|
723
|
+
canceled: PaymentStatus.CANCELED,
|
|
724
|
+
cancelled: PaymentStatus.CANCELED,
|
|
725
|
+
failed: PaymentStatus.FAILED
|
|
726
|
+
};
|
|
727
|
+
function mapKhaltiStatus(status) {
|
|
728
|
+
const key = status.trim().toLowerCase().replace(/[\s_]+/g, " ");
|
|
729
|
+
return STATUS_MAP2[key] ?? PaymentStatus.UNKNOWN;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// src/gateways/khalti/khalti.gateway.ts
|
|
733
|
+
var KhaltiGateway = class extends BaseGateway {
|
|
734
|
+
name = KHALTI;
|
|
735
|
+
secretKey;
|
|
736
|
+
websiteUrl;
|
|
737
|
+
baseUrl;
|
|
738
|
+
constructor(options) {
|
|
739
|
+
super(KHALTI, options);
|
|
740
|
+
this.secretKey = requireOption(options.secretKey, "secretKey", KHALTI, "KHALTI_SECRET_KEY");
|
|
741
|
+
this.websiteUrl = requireOption(options.websiteUrl, "websiteUrl", KHALTI, "KHALTI_WEBSITE_URL");
|
|
742
|
+
if (!isAbsoluteHttpUrl(this.websiteUrl)) {
|
|
743
|
+
throw new ConfigurationError('khalti: "websiteUrl" must be an absolute http(s) URL', {
|
|
744
|
+
gateway: KHALTI
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
const baseUrl = options.baseUrl ?? KHALTI_BASE_URLS[this.environment];
|
|
748
|
+
this.baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
|
|
749
|
+
}
|
|
750
|
+
async initiate(input) {
|
|
751
|
+
const payment = validateInitiateInput(input, KHALTI, { minAmount: KHALTI_MIN_AMOUNT });
|
|
752
|
+
const response = await this.http.send({
|
|
753
|
+
method: "POST",
|
|
754
|
+
url: `${this.baseUrl}epayment/initiate/`,
|
|
755
|
+
headers: this.authHeaders(),
|
|
756
|
+
json: this.buildInitiateBody(payment),
|
|
757
|
+
idempotent: false
|
|
758
|
+
});
|
|
759
|
+
if (response.status !== 200 && response.status !== 201) {
|
|
760
|
+
throw toKhaltiError(response, "initiate");
|
|
761
|
+
}
|
|
762
|
+
const body = parseInitiateResponse(response);
|
|
763
|
+
return {
|
|
764
|
+
gateway: KHALTI,
|
|
765
|
+
reference: body.pidx,
|
|
766
|
+
orderId: payment.orderId,
|
|
767
|
+
amount: payment.amount,
|
|
768
|
+
redirect: { method: "GET", url: body.payment_url },
|
|
769
|
+
expiresAt: parseDate(body.expires_at),
|
|
770
|
+
raw: body
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
async verify({ callback, expected }) {
|
|
774
|
+
const pidx = callbackValue(callback, "pidx") ?? expected?.reference;
|
|
775
|
+
if (pidx === void 0) {
|
|
776
|
+
throw new InvalidCallbackError('Khalti callback is missing "pidx"', { gateway: KHALTI });
|
|
777
|
+
}
|
|
778
|
+
const result = await this.lookup({ reference: pidx });
|
|
779
|
+
return this.assertExpected(result, expected);
|
|
780
|
+
}
|
|
781
|
+
async lookup({ reference }) {
|
|
782
|
+
if (typeof reference !== "string" || reference.trim() === "") {
|
|
783
|
+
throw ValidationError.fromFields({ reference: ["is required"] }, { gateway: KHALTI });
|
|
784
|
+
}
|
|
785
|
+
const response = await this.http.send({
|
|
786
|
+
method: "POST",
|
|
787
|
+
url: `${this.baseUrl}epayment/lookup/`,
|
|
788
|
+
headers: this.authHeaders(),
|
|
789
|
+
json: { pidx: reference },
|
|
790
|
+
idempotent: true
|
|
791
|
+
});
|
|
792
|
+
if (isLookupBody(response.body) && response.status < 500) {
|
|
793
|
+
return this.toResult(response.body);
|
|
794
|
+
}
|
|
795
|
+
if (isNotFound(response)) {
|
|
796
|
+
return this.result({
|
|
797
|
+
status: PaymentStatus.NOT_FOUND,
|
|
798
|
+
reference,
|
|
799
|
+
transactionId: null,
|
|
800
|
+
amount: 0,
|
|
801
|
+
fee: null,
|
|
802
|
+
raw: response.body
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
throw toKhaltiError(response, "lookup");
|
|
806
|
+
}
|
|
807
|
+
toResult(body) {
|
|
808
|
+
const amount = Number(body.total_amount);
|
|
809
|
+
if (!Number.isSafeInteger(amount) || amount < 0) {
|
|
810
|
+
throw new GatewayError("Khalti lookup returned an invalid total_amount", {
|
|
811
|
+
gateway: KHALTI,
|
|
812
|
+
responseBody: body
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
return this.result({
|
|
816
|
+
status: mapKhaltiStatus(body.status),
|
|
817
|
+
reference: body.pidx,
|
|
818
|
+
transactionId: body.transaction_id ?? null,
|
|
819
|
+
amount,
|
|
820
|
+
fee: typeof body.fee === "number" ? body.fee : null,
|
|
821
|
+
raw: body
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
buildInitiateBody(payment) {
|
|
825
|
+
const body = {
|
|
826
|
+
return_url: payment.returnUrl,
|
|
827
|
+
website_url: this.websiteUrl,
|
|
828
|
+
amount: payment.amount,
|
|
829
|
+
purchase_order_id: payment.orderId,
|
|
830
|
+
purchase_order_name: payment.orderName
|
|
831
|
+
};
|
|
832
|
+
if (payment.customer) {
|
|
833
|
+
const { name, email, phone } = payment.customer;
|
|
834
|
+
body.customer_info = {
|
|
835
|
+
...name !== void 0 && { name },
|
|
836
|
+
...email !== void 0 && { email },
|
|
837
|
+
...phone !== void 0 && { phone }
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
const { tax, serviceCharge, deliveryCharge } = payment.breakdown;
|
|
841
|
+
if (tax + serviceCharge + deliveryCharge > 0) {
|
|
842
|
+
body.amount_breakdown = [
|
|
843
|
+
{ label: "Amount", amount: payment.baseAmount },
|
|
844
|
+
{ label: "Tax", amount: tax },
|
|
845
|
+
{ label: "Service charge", amount: serviceCharge },
|
|
846
|
+
{ label: "Delivery charge", amount: deliveryCharge }
|
|
847
|
+
].filter((row, index) => index === 0 || row.amount > 0);
|
|
848
|
+
}
|
|
849
|
+
for (const [key, value] of Object.entries(payment.metadata)) {
|
|
850
|
+
body[`merchant_${key}`] = value;
|
|
851
|
+
}
|
|
852
|
+
return body;
|
|
853
|
+
}
|
|
854
|
+
authHeaders() {
|
|
855
|
+
return { Authorization: `Key ${this.secretKey}` };
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
function isRecord3(value) {
|
|
859
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
860
|
+
}
|
|
861
|
+
function isLookupBody(body) {
|
|
862
|
+
return isRecord3(body) && typeof body.pidx === "string" && typeof body.status === "string";
|
|
863
|
+
}
|
|
864
|
+
function isNotFound(response) {
|
|
865
|
+
const { status, body } = response;
|
|
866
|
+
return (status === 404 || status === 400) && isRecord3(body) && typeof body.detail === "string" && body.detail.trim().toLowerCase().replace(/\.$/, "") === "not found";
|
|
867
|
+
}
|
|
868
|
+
function parseInitiateResponse(response) {
|
|
869
|
+
const { body } = response;
|
|
870
|
+
if (!isRecord3(body) || typeof body.pidx !== "string" || typeof body.payment_url !== "string" || !isAbsoluteHttpUrl(body.payment_url)) {
|
|
871
|
+
throw new GatewayError("Khalti initiate returned an unexpected response", {
|
|
872
|
+
gateway: KHALTI,
|
|
873
|
+
statusCode: response.status,
|
|
874
|
+
responseBody: body
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
return body;
|
|
878
|
+
}
|
|
879
|
+
function parseDate(value) {
|
|
880
|
+
if (value === void 0) return null;
|
|
881
|
+
const date = new Date(value);
|
|
882
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/nepal-pay.ts
|
|
886
|
+
var NepalPay = class {
|
|
887
|
+
constructor(config) {
|
|
888
|
+
this.config = config;
|
|
889
|
+
if (typeof config !== "object" || typeof config.gateways !== "object") {
|
|
890
|
+
throw new ConfigurationError('NepalPay: "gateways" config is required');
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
config;
|
|
894
|
+
factories = /* @__PURE__ */ new Map([
|
|
895
|
+
["khalti", (options) => new KhaltiGateway(options)],
|
|
896
|
+
["esewa", (options) => new EsewaGateway(options)]
|
|
897
|
+
]);
|
|
898
|
+
instances = /* @__PURE__ */ new Map();
|
|
899
|
+
/** Names of gateways that have configuration. */
|
|
900
|
+
get configured() {
|
|
901
|
+
return Object.entries(this.config.gateways).filter(([, options]) => options !== void 0).map(([name]) => name);
|
|
902
|
+
}
|
|
903
|
+
gateway(name) {
|
|
904
|
+
const gatewayName = name ?? this.defaultGateway();
|
|
905
|
+
const cached = this.instances.get(gatewayName);
|
|
906
|
+
if (cached) return cached;
|
|
907
|
+
const factory = this.factories.get(gatewayName);
|
|
908
|
+
if (!factory) {
|
|
909
|
+
throw new ConfigurationError(`Unknown gateway "${gatewayName}". Register it with extend().`, {
|
|
910
|
+
gateway: gatewayName
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
const own = this.config.gateways[gatewayName];
|
|
914
|
+
if (own === void 0) {
|
|
915
|
+
throw new ConfigurationError(`Gateway "${gatewayName}" is not configured`, {
|
|
916
|
+
gateway: gatewayName
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
const instance = factory({
|
|
920
|
+
...this.config.http,
|
|
921
|
+
environment: this.config.environment ?? "sandbox",
|
|
922
|
+
...own
|
|
923
|
+
});
|
|
924
|
+
this.instances.set(gatewayName, instance);
|
|
925
|
+
return instance;
|
|
926
|
+
}
|
|
927
|
+
/** Register a custom gateway (or replace a built-in one). Returns `this` for chaining. */
|
|
928
|
+
extend(name, factory) {
|
|
929
|
+
this.factories.set(name, factory);
|
|
930
|
+
this.instances.delete(name);
|
|
931
|
+
return this;
|
|
932
|
+
}
|
|
933
|
+
defaultGateway() {
|
|
934
|
+
const name = this.config.default ?? this.configured[0];
|
|
935
|
+
if (name === void 0) throw new ConfigurationError("NepalPay: no gateway is configured");
|
|
936
|
+
return name;
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
function createNepalPayFromEnv(env = process.env, http = {}) {
|
|
940
|
+
const environment = env.NEPAL_PAY_ENV ?? "sandbox";
|
|
941
|
+
const gateways = {};
|
|
942
|
+
if (env.KHALTI_SECRET_KEY) {
|
|
943
|
+
gateways.khalti = {
|
|
944
|
+
secretKey: env.KHALTI_SECRET_KEY,
|
|
945
|
+
websiteUrl: env.KHALTI_WEBSITE_URL ?? ""
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
if (env.ESEWA_PRODUCT_CODE && env.ESEWA_SECRET_KEY || environment === "sandbox") {
|
|
949
|
+
gateways.esewa = {
|
|
950
|
+
...env.ESEWA_PRODUCT_CODE && { productCode: env.ESEWA_PRODUCT_CODE },
|
|
951
|
+
...env.ESEWA_SECRET_KEY && { secretKey: env.ESEWA_SECRET_KEY }
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
return new NepalPay({
|
|
955
|
+
environment,
|
|
956
|
+
http,
|
|
957
|
+
gateways,
|
|
958
|
+
...env.NEPAL_PAY_DEFAULT && { default: env.NEPAL_PAY_DEFAULT }
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// src/helpers/redirect-page.ts
|
|
963
|
+
var HTML_ESCAPES = {
|
|
964
|
+
"&": "&",
|
|
965
|
+
"<": "<",
|
|
966
|
+
">": ">",
|
|
967
|
+
'"': """,
|
|
968
|
+
"'": "'"
|
|
969
|
+
};
|
|
970
|
+
function escapeHtml(value) {
|
|
971
|
+
return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
|
|
972
|
+
}
|
|
973
|
+
function renderRedirectPage(redirect, options = {}) {
|
|
974
|
+
const title = escapeHtml(options.title ?? "Redirecting to payment\u2026");
|
|
975
|
+
const nonce = options.nonce ? ` nonce="${escapeHtml(options.nonce)}"` : "";
|
|
976
|
+
const url = escapeHtml(redirect.url);
|
|
977
|
+
if (redirect.method === "GET") {
|
|
978
|
+
return document(
|
|
979
|
+
title,
|
|
980
|
+
`<meta http-equiv="refresh" content="0;url=${url}">`,
|
|
981
|
+
`<p><a href="${url}">Continue to payment</a></p>`
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
const inputs = Object.entries(redirect.fields).map(
|
|
985
|
+
([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`
|
|
986
|
+
).join("\n ");
|
|
987
|
+
return document(
|
|
988
|
+
title,
|
|
989
|
+
"",
|
|
990
|
+
`<form id="nepal-pay-redirect" method="POST" action="${url}">
|
|
991
|
+
${inputs}
|
|
992
|
+
<noscript><button type="submit">Continue to payment</button></noscript>
|
|
993
|
+
</form>
|
|
994
|
+
<script${nonce}>document.getElementById('nepal-pay-redirect').submit();</script>`
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
function document(title, head, body) {
|
|
998
|
+
return `<!doctype html>
|
|
999
|
+
<html lang="en">
|
|
1000
|
+
<head>
|
|
1001
|
+
<meta charset="utf-8">
|
|
1002
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1003
|
+
<meta name="robots" content="noindex">
|
|
1004
|
+
<title>${title}</title>
|
|
1005
|
+
${head}
|
|
1006
|
+
</head>
|
|
1007
|
+
<body>
|
|
1008
|
+
${body}
|
|
1009
|
+
</body>
|
|
1010
|
+
</html>
|
|
1011
|
+
`;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
export { AuthenticationError, BaseGateway, ConfigurationError, ESEWA_SANDBOX_CREDENTIALS, ErrorCode, EsewaGateway, GatewayError, InvalidCallbackError, InvalidSignatureError, KHALTI_MIN_AMOUNT, KhaltiGateway, NepalPay, NepalPayError, NetworkError, PaymentMismatchError, PaymentStatus, ValidationError, createNepalPayFromEnv, isNepalPayError, paisaToRupeeString, parseRupees, renderRedirectPage };
|
|
1015
|
+
//# sourceMappingURL=index.js.map
|
|
1016
|
+
//# sourceMappingURL=index.js.map
|