@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.
@@ -0,0 +1,427 @@
1
+ /** Built-in gateway names. Custom gateways may use any other string. */
2
+ type BuiltInGateway = 'khalti' | 'esewa';
3
+ type Environment = 'sandbox' | 'production';
4
+ /** Amount in paisa (Rs 1 = 100 paisa). Always a positive integer — never a float. */
5
+ type Paisa = number;
6
+ declare const PaymentStatus: {
7
+ /** Money received. The only status that should fulfil an order. */
8
+ readonly COMPLETED: "completed";
9
+ readonly PENDING: "pending";
10
+ readonly INITIATED: "initiated";
11
+ readonly REFUNDED: "refunded";
12
+ readonly PARTIALLY_REFUNDED: "partially_refunded";
13
+ readonly EXPIRED: "expired";
14
+ readonly CANCELED: "canceled";
15
+ readonly FAILED: "failed";
16
+ /** eSewa: payment is in a halted state — hold the order and re-check later. */
17
+ readonly AMBIGUOUS: "ambiguous";
18
+ readonly NOT_FOUND: "not_found";
19
+ /** The gateway returned a status this library does not know; inspect `raw`. */
20
+ readonly UNKNOWN: "unknown";
21
+ };
22
+ type PaymentStatus = (typeof PaymentStatus)[keyof typeof PaymentStatus];
23
+ interface Customer {
24
+ name?: string;
25
+ email?: string;
26
+ phone?: string;
27
+ }
28
+ /** Parts of `amount` (all in paisa). The remainder of `amount` is the base price. */
29
+ interface AmountBreakdown {
30
+ tax?: Paisa;
31
+ serviceCharge?: Paisa;
32
+ deliveryCharge?: Paisa;
33
+ }
34
+ interface InitiatePaymentInput {
35
+ /** Total payable, in paisa. */
36
+ amount: Paisa;
37
+ /** Your ID for this payment attempt. Must be unique per attempt; letters, digits and `-` only. */
38
+ orderId: string;
39
+ /** Shown to the customer on the gateway's page. */
40
+ orderName: string;
41
+ /** Absolute URL the customer is sent back to after paying. */
42
+ returnUrl: string;
43
+ /** eSewa only: where to send the customer on failure. Defaults to `returnUrl`. */
44
+ failureUrl?: string;
45
+ customer?: Customer;
46
+ breakdown?: AmountBreakdown;
47
+ /** Extra key/value data passed through to the gateway (eSewa allows at most 3 keys). */
48
+ metadata?: Record<string, string>;
49
+ }
50
+ /** How to send the customer to the gateway. */
51
+ type RedirectInstruction = {
52
+ method: 'GET';
53
+ url: string;
54
+ } | {
55
+ method: 'POST';
56
+ url: string;
57
+ fields: Readonly<Record<string, string>>;
58
+ };
59
+ interface InitiatedPayment {
60
+ gateway: string;
61
+ /** Gateway-side reference (Khalti `pidx`, eSewa `transaction_uuid`). Persist it with your order. */
62
+ reference: string;
63
+ orderId: string;
64
+ amount: Paisa;
65
+ redirect: RedirectInstruction;
66
+ expiresAt: Date | null;
67
+ /** Raw gateway response, for debugging. */
68
+ raw: unknown;
69
+ }
70
+ /** Values you stored at initiate time. Passing them turns on amount/reference fraud checks. */
71
+ interface ExpectedPayment {
72
+ amount: Paisa;
73
+ reference?: string;
74
+ }
75
+ type CallbackParams = Readonly<Record<string, string | readonly string[] | undefined>>;
76
+ interface VerifyPaymentInput {
77
+ /** Query parameters of the return-URL request, e.g. `req.query` or `Object.fromEntries(url.searchParams)`. */
78
+ callback: CallbackParams;
79
+ expected?: ExpectedPayment;
80
+ }
81
+ interface LookupPaymentInput {
82
+ reference: string;
83
+ /** Required by eSewa (its status API is keyed on amount). */
84
+ amount?: Paisa;
85
+ }
86
+ interface PaymentResult {
87
+ gateway: string;
88
+ status: PaymentStatus;
89
+ /** `true` only when `status === 'completed'`. */
90
+ isPaid: boolean;
91
+ reference: string;
92
+ transactionId: string | null;
93
+ amount: Paisa;
94
+ /** Gateway fee in paisa, when the gateway reports it. */
95
+ fee: Paisa | null;
96
+ raw: unknown;
97
+ }
98
+ /** The contract every gateway implements. */
99
+ interface PaymentGateway {
100
+ readonly name: string;
101
+ readonly environment: Environment;
102
+ initiate(input: InitiatePaymentInput): Promise<InitiatedPayment>;
103
+ verify(input: VerifyPaymentInput): Promise<PaymentResult>;
104
+ lookup(input: LookupPaymentInput): Promise<PaymentResult>;
105
+ }
106
+ /** Minimal logger interface — compatible with `console`, pino and winston. */
107
+ interface Logger {
108
+ debug(message: string, context?: Record<string, unknown>): void;
109
+ warn(message: string, context?: Record<string, unknown>): void;
110
+ }
111
+
112
+ type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
113
+ /** Transport options shared by every gateway. */
114
+ interface HttpOptions {
115
+ /** Per-attempt timeout. Default 15 000 ms. */
116
+ timeoutMs?: number;
117
+ /** Extra attempts for idempotent reads (lookup/status) on network errors and 5xx. Default 2. */
118
+ retries?: number;
119
+ /** Base delay for exponential backoff (delay × 2^attempt). Default 200 ms. */
120
+ retryDelayMs?: number;
121
+ /** Custom fetch — for proxies, instrumentation or tests. Defaults to global `fetch`. */
122
+ fetch?: FetchLike;
123
+ logger?: Logger;
124
+ }
125
+ interface HttpRequest {
126
+ method: 'GET' | 'POST';
127
+ url: string;
128
+ headers?: Record<string, string>;
129
+ /** Serialised as JSON. */
130
+ json?: unknown;
131
+ /** Only idempotent requests are retried. Payment creation must never be. */
132
+ idempotent: boolean;
133
+ }
134
+ interface HttpResponse {
135
+ status: number;
136
+ /** Parsed JSON, or the raw text when the body is not JSON, or `null` when empty. */
137
+ body: unknown;
138
+ }
139
+ /**
140
+ * Thin fetch wrapper. It does not interpret HTTP status codes — gateways do, because
141
+ * each one encodes meaning differently (Khalti returns 400 for an expired payment).
142
+ */
143
+ declare class HttpClient {
144
+ private readonly gateway;
145
+ private readonly timeoutMs;
146
+ private readonly retries;
147
+ private readonly retryDelayMs;
148
+ private readonly fetchFn;
149
+ private readonly logger;
150
+ constructor(gateway: string, options?: HttpOptions);
151
+ send(request: HttpRequest): Promise<HttpResponse>;
152
+ private attempt;
153
+ /** Never includes headers or bodies — they carry secret keys and customer data. */
154
+ private logContext;
155
+ }
156
+
157
+ /** Options every gateway accepts in addition to its own credentials. */
158
+ interface BaseGatewayOptions extends HttpOptions {
159
+ /** Default `"sandbox"`. Production must be chosen explicitly. */
160
+ environment?: Environment;
161
+ }
162
+ /**
163
+ * Shared behaviour for gateways: environment handling, HTTP transport and the
164
+ * fraud checks that every `verify()` must apply. Subclasses only translate
165
+ * between the unified API and their gateway's wire format.
166
+ */
167
+ declare abstract class BaseGateway implements PaymentGateway {
168
+ abstract readonly name: string;
169
+ readonly environment: Environment;
170
+ protected readonly http: HttpClient;
171
+ protected constructor(gatewayName: string, options: BaseGatewayOptions);
172
+ abstract initiate(input: InitiatePaymentInput): Promise<InitiatedPayment>;
173
+ abstract verify(input: VerifyPaymentInput): Promise<PaymentResult>;
174
+ abstract lookup(input: LookupPaymentInput): Promise<PaymentResult>;
175
+ protected get isSandbox(): boolean;
176
+ /**
177
+ * Applies the expectations stored at initiate time.
178
+ * Reference is always checked; amount only matters once money has moved.
179
+ */
180
+ protected assertExpected(result: PaymentResult, expected: ExpectedPayment | undefined): PaymentResult;
181
+ protected result(fields: Omit<PaymentResult, 'gateway' | 'isPaid'>): PaymentResult;
182
+ }
183
+
184
+ /** Public UAT credentials published by eSewa. Used only when `environment` is `"sandbox"`. */
185
+ declare const ESEWA_SANDBOX_CREDENTIALS: {
186
+ readonly productCode: "EPAYTEST";
187
+ readonly secretKey: "8gBm/:&EnhH.1/q";
188
+ };
189
+ interface EsewaOptions extends BaseGatewayOptions {
190
+ /** Merchant/product code from eSewa. Defaults to `EPAYTEST` in sandbox. */
191
+ productCode?: string;
192
+ /** HMAC secret key from eSewa. Defaults to the public UAT key in sandbox. */
193
+ secretKey?: string;
194
+ /** Override the checkout form URL. */
195
+ formUrl?: string;
196
+ /** Override the transaction status API URL. */
197
+ statusUrl?: string;
198
+ }
199
+
200
+ /**
201
+ * eSewa ePay v2.
202
+ *
203
+ * Flow: `initiate()` returns a signed form → POST it from the browser → eSewa sends the
204
+ * customer to `returnUrl?data=<base64>` → `verify()` checks the signature, then confirms
205
+ * through the status API (the source of truth).
206
+ */
207
+ declare class EsewaGateway extends BaseGateway {
208
+ readonly name = "esewa";
209
+ private readonly productCode;
210
+ private readonly secretKey;
211
+ private readonly formUrl;
212
+ private readonly statusUrl;
213
+ constructor(options?: EsewaOptions);
214
+ initiate(input: InitiatePaymentInput): Promise<InitiatedPayment>;
215
+ verify({ callback, expected }: VerifyPaymentInput): Promise<PaymentResult>;
216
+ lookup({ reference, amount }: LookupPaymentInput): Promise<PaymentResult>;
217
+ private buildPayment;
218
+ private toResult;
219
+ }
220
+
221
+ /** Khalti rejects payments below Rs 10. */
222
+ declare const KHALTI_MIN_AMOUNT = 1000;
223
+ interface KhaltiOptions extends BaseGatewayOptions {
224
+ /** "Live secret key" from test-admin.khalti.com (sandbox) or admin.khalti.com (production). */
225
+ secretKey: string;
226
+ /** Your site's URL — Khalti requires it on every payment. */
227
+ websiteUrl: string;
228
+ /** Override the API base URL (proxies, mocks). Must end with `/`. */
229
+ baseUrl?: string;
230
+ }
231
+
232
+ /**
233
+ * Khalti KPG-2 web checkout.
234
+ *
235
+ * Flow: `initiate()` → redirect the customer (GET) → Khalti sends them to `returnUrl`
236
+ * with `?pidx=...` → `verify()` confirms through the lookup API (the source of truth).
237
+ */
238
+ declare class KhaltiGateway extends BaseGateway {
239
+ readonly name = "khalti";
240
+ private readonly secretKey;
241
+ private readonly websiteUrl;
242
+ private readonly baseUrl;
243
+ constructor(options: KhaltiOptions);
244
+ initiate(input: InitiatePaymentInput): Promise<InitiatedPayment>;
245
+ verify({ callback, expected }: VerifyPaymentInput): Promise<PaymentResult>;
246
+ lookup({ reference }: LookupPaymentInput): Promise<PaymentResult>;
247
+ private toResult;
248
+ private buildInitiateBody;
249
+ private authHeaders;
250
+ }
251
+
252
+ type WithoutShared<T> = Omit<T, 'environment' | keyof HttpOptions> & Partial<Pick<T, Extract<keyof T, 'environment' | keyof HttpOptions>>>;
253
+ interface NepalPayConfig {
254
+ /** Gateway used by `gateway()` with no name. Defaults to the first configured one. */
255
+ default?: string;
256
+ /** Applies to every gateway unless overridden per gateway. Default `"sandbox"`. */
257
+ environment?: Environment;
258
+ /** Shared transport options (timeout, retries, fetch, logger). */
259
+ http?: HttpOptions;
260
+ gateways: {
261
+ khalti?: WithoutShared<KhaltiOptions>;
262
+ esewa?: WithoutShared<EsewaOptions>;
263
+ /** Options for gateways registered with `extend()`. */
264
+ [custom: string]: Record<string, unknown> | undefined;
265
+ };
266
+ }
267
+ /** Shared settings handed to custom gateway factories, merged with that gateway's own options. */
268
+ type GatewayFactory = (options: Record<string, unknown> & {
269
+ environment: Environment;
270
+ } & HttpOptions) => PaymentGateway;
271
+ /**
272
+ * Registry of configured gateways. Instances are created lazily and cached,
273
+ * so configuration errors surface the first time a gateway is used.
274
+ *
275
+ * ```ts
276
+ * const pay = new NepalPay({ gateways: { khalti: { secretKey, websiteUrl }, esewa: {} } });
277
+ * await pay.gateway('khalti').initiate({ ... });
278
+ * ```
279
+ */
280
+ declare class NepalPay {
281
+ private readonly config;
282
+ private readonly factories;
283
+ private readonly instances;
284
+ constructor(config: NepalPayConfig);
285
+ /** Names of gateways that have configuration. */
286
+ get configured(): string[];
287
+ gateway(name: 'khalti'): KhaltiGateway;
288
+ gateway(name: 'esewa'): EsewaGateway;
289
+ gateway(name?: string): PaymentGateway;
290
+ /** Register a custom gateway (or replace a built-in one). Returns `this` for chaining. */
291
+ extend(name: string, factory: GatewayFactory): this;
292
+ private defaultGateway;
293
+ }
294
+ /**
295
+ * Builds a `NepalPay` from environment variables:
296
+ * `NEPAL_PAY_ENV`, `NEPAL_PAY_DEFAULT`, `KHALTI_SECRET_KEY`, `KHALTI_WEBSITE_URL`,
297
+ * `ESEWA_PRODUCT_CODE`, `ESEWA_SECRET_KEY`. Gateways without credentials are skipped
298
+ * (eSewa is always available in sandbox, using the public test credentials).
299
+ */
300
+ declare function createNepalPayFromEnv(env?: Readonly<Record<string, string | undefined>>, http?: HttpOptions): NepalPay;
301
+
302
+ /**
303
+ * Paisa → rupee string as eSewa expects it.
304
+ * `11000` → `"110"`, `11050` → `"110.50"`.
305
+ */
306
+ declare function paisaToRupeeString(paisa: Paisa): string;
307
+ /**
308
+ * Rupee amount from a gateway (`"1,000.0"`, `"110"`, `100.5`) → paisa.
309
+ * Throws when the value is not a non-negative decimal.
310
+ */
311
+ declare function parseRupees(value: unknown, field?: string): Paisa;
312
+
313
+ interface RedirectPageOptions {
314
+ /** Page title shown for the split second before the browser leaves. */
315
+ title?: string;
316
+ /** CSP nonce for the inline auto-submit script, if your site uses a strict CSP. */
317
+ nonce?: string;
318
+ }
319
+ /**
320
+ * A minimal HTML page that sends the browser to the gateway.
321
+ *
322
+ * Needed for eSewa, whose checkout starts with a form POST. Works without JavaScript
323
+ * (a "Continue" button), and every value is HTML-escaped.
324
+ *
325
+ * ```ts
326
+ * res.type('html').send(renderRedirectPage(payment.redirect));
327
+ * ```
328
+ */
329
+ declare function renderRedirectPage(redirect: RedirectInstruction, options?: RedirectPageOptions): string;
330
+
331
+ /**
332
+ * Stable, machine-readable error codes. Match on `error.code` (or use `instanceof`)
333
+ * instead of parsing messages — messages may change between releases.
334
+ */
335
+ declare const ErrorCode: {
336
+ readonly CONFIGURATION_ERROR: "CONFIGURATION_ERROR";
337
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
338
+ readonly AUTHENTICATION_FAILED: "AUTHENTICATION_FAILED";
339
+ readonly GATEWAY_ERROR: "GATEWAY_ERROR";
340
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
341
+ readonly TIMEOUT: "TIMEOUT";
342
+ readonly INVALID_CALLBACK: "INVALID_CALLBACK";
343
+ readonly INVALID_SIGNATURE: "INVALID_SIGNATURE";
344
+ readonly AMOUNT_MISMATCH: "AMOUNT_MISMATCH";
345
+ readonly REFERENCE_MISMATCH: "REFERENCE_MISMATCH";
346
+ };
347
+ type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
348
+ interface NepalPayErrorOptions {
349
+ gateway?: string | null;
350
+ details?: Record<string, unknown>;
351
+ cause?: unknown;
352
+ }
353
+ /**
354
+ * Base class for every error thrown by this library.
355
+ *
356
+ * Secrets are never placed in `message` or `details`, so errors are safe to log.
357
+ */
358
+ declare abstract class NepalPayError extends Error {
359
+ abstract readonly code: ErrorCode;
360
+ readonly gateway: string | null;
361
+ readonly details: Readonly<Record<string, unknown>>;
362
+ constructor(message: string, options?: NepalPayErrorOptions);
363
+ /** Plain-object form for structured logging / API error responses. */
364
+ toJSON(): Record<string, unknown>;
365
+ }
366
+
367
+ /** Missing or invalid configuration, or an unknown gateway name. Thrown at construction time. */
368
+ declare class ConfigurationError extends NepalPayError {
369
+ readonly code: "CONFIGURATION_ERROR";
370
+ }
371
+ /** Invalid input — either caught locally before any request, or rejected by the gateway (HTTP 400). */
372
+ declare class ValidationError extends NepalPayError {
373
+ readonly code: "VALIDATION_ERROR";
374
+ /** Field name → messages, e.g. `{ amount: ['must be an integer number of paisa'] }`. */
375
+ readonly fields: Readonly<Record<string, readonly string[]>>;
376
+ constructor(message: string, fields?: Record<string, string[]>, options?: NepalPayErrorOptions);
377
+ /** Build from a field map; the message summarises the first problem. */
378
+ static fromFields(fields: Record<string, string[]>, options?: NepalPayErrorOptions): ValidationError;
379
+ }
380
+ /** The gateway rejected the credentials (HTTP 401/403). Usually a wrong or wrong-environment secret key. */
381
+ declare class AuthenticationError extends NepalPayError {
382
+ readonly code: "AUTHENTICATION_FAILED";
383
+ }
384
+ interface GatewayErrorOptions extends NepalPayErrorOptions {
385
+ statusCode?: number | null;
386
+ responseBody?: unknown;
387
+ /** Override the default (`statusCode` is null or ≥ 500). */
388
+ retryable?: boolean;
389
+ }
390
+ /** The gateway answered with something unexpected: 5xx, unknown 4xx, or a malformed body. */
391
+ declare class GatewayError extends NepalPayError {
392
+ readonly code: "GATEWAY_ERROR";
393
+ readonly statusCode: number | null;
394
+ readonly responseBody: unknown;
395
+ /** True when trying again later may succeed (5xx, or the gateway says it is unavailable). */
396
+ readonly retryable: boolean;
397
+ constructor(message: string, options?: GatewayErrorOptions);
398
+ }
399
+ /** The request never got a response: DNS, connection reset, TLS failure or timeout. */
400
+ declare class NetworkError extends NepalPayError {
401
+ readonly code: typeof ErrorCode.NETWORK_ERROR | typeof ErrorCode.TIMEOUT;
402
+ constructor(message: string, options?: NepalPayErrorOptions & {
403
+ timeout?: boolean;
404
+ });
405
+ }
406
+ /** The return-URL callback is missing required parameters or cannot be decoded. */
407
+ declare class InvalidCallbackError extends NepalPayError {
408
+ readonly code: "INVALID_CALLBACK";
409
+ }
410
+ /** The callback's signature does not match — treat as tampering. */
411
+ declare class InvalidSignatureError extends NepalPayError {
412
+ readonly code: "INVALID_SIGNATURE";
413
+ }
414
+ /**
415
+ * The gateway confirmed a payment, but not the one you expected (different amount or reference).
416
+ * Treat as a fraud signal: do not fulfil the order.
417
+ */
418
+ declare class PaymentMismatchError extends NepalPayError {
419
+ readonly code: typeof ErrorCode.AMOUNT_MISMATCH | typeof ErrorCode.REFERENCE_MISMATCH;
420
+ readonly expected: string | number;
421
+ readonly actual: string | number;
422
+ constructor(code: typeof ErrorCode.AMOUNT_MISMATCH | typeof ErrorCode.REFERENCE_MISMATCH, expected: string | number, actual: string | number, options?: NepalPayErrorOptions);
423
+ }
424
+ /** Type guard for any error raised by this library. */
425
+ declare function isNepalPayError(error: unknown): error is NepalPayError;
426
+
427
+ export { type AmountBreakdown, AuthenticationError, BaseGateway, type BaseGatewayOptions, type BuiltInGateway, type CallbackParams, ConfigurationError, type Customer, ESEWA_SANDBOX_CREDENTIALS, type Environment, ErrorCode, EsewaGateway, type EsewaOptions, type ExpectedPayment, type FetchLike, GatewayError, type GatewayErrorOptions, type GatewayFactory, type HttpOptions, type InitiatePaymentInput, type InitiatedPayment, InvalidCallbackError, InvalidSignatureError, KHALTI_MIN_AMOUNT, KhaltiGateway, type KhaltiOptions, type Logger, type LookupPaymentInput, NepalPay, type NepalPayConfig, NepalPayError, type NepalPayErrorOptions, NetworkError, type Paisa, type PaymentGateway, PaymentMismatchError, type PaymentResult, PaymentStatus, type RedirectInstruction, type RedirectPageOptions, ValidationError, type VerifyPaymentInput, createNepalPayFromEnv, isNepalPayError, paisaToRupeeString, parseRupees, renderRedirectPage };