/** The amount fields eSewa expects, all in **rupees** (not paisa). */ interface AmountFields { /** Base product amount. */ amount: number; /** Tax amount. Default 0. */ taxAmount?: number; /** Product service charge. Default 0. */ productServiceCharge?: number; /** Product delivery charge. Default 0. */ productDeliveryCharge?: number; /** * Grand total. If omitted, no equality check is performed and only the * component fields are range-checked (mirrors `buildForm`, which derives the * total when it isn't given). */ totalAmount?: number; } /** Result of {@link validateAmounts}. */ interface AmountValidation { ok: boolean; /** Human-readable reason when `ok` is `false`. */ reason?: string; } /** * Validate that the eSewa amount fields are internally consistent: every * component is a finite non-negative number, and — when `totalAmount` is given — * `amount + taxAmount + productServiceCharge + productDeliveryCharge` equals it. * Pure, offline, never throws. * * A tiny epsilon (1e-6) absorbs binary floating-point drift (e.g. `0.1 + 0.2`). * * @example * validateAmounts({ amount: 100, taxAmount: 13, totalAmount: 113 }); // { ok: true } * validateAmounts({ amount: 100, taxAmount: 13, totalAmount: 120 }); * // { ok: false, reason: "total_amount 120 ≠ amount+tax+service+delivery (113)" } */ declare function validateAmounts(fields: AmountFields): AmountValidation; /** * `true` if `uuid` is a well-formed eSewa `transaction_uuid`: 1–64 chars, only * ASCII letters, digits and single hyphens (not leading/trailing/doubled). Pure. */ declare function isValidTransactionUuid(uuid: string): boolean; /** * Generate a valid, unique eSewa `transaction_uuid` using the platform CSPRNG. * The result is `[A-Za-z0-9]` with an optional caller `prefix` joined by a * hyphen, and always passes {@link isValidTransactionUuid}. * * @param opts.length number of random chars (default 20, clamped to 1–63). * @param opts.prefix optional prefix (e.g. an order id); stripped to the safe * charset. The final length still respects the 64-char cap. * * @example * generateTransactionUuid(); // "k3Zq9RtA1bVn7cPmLxQw" * generateTransactionUuid({ prefix: "240" }); // "240-Xq7…" */ declare function generateTransactionUuid(opts?: { length?: number; prefix?: string; }): string; /** The status values eSewa's transaction-status API can return. */ type EsewaStatus = "COMPLETE" | "PENDING" | "FULL_REFUND" | "PARTIAL_REFUND" | "AMBIGUOUS" | "NOT_FOUND" | "CANCELED" | "ERROR"; /** Params for a transaction-status lookup. */ interface StatusRequestParams { product_code: string; total_amount: string | number; transaction_uuid: string; } /** A fully-built status request, ready to hand to any `fetch`. */ interface StatusRequest { url: string; method: "GET"; /** The query params, pre-stringified, in eSewa's order. */ params: Record; } /** * Build the eSewa transaction-status-check request purely — the status endpoint * URL with `product_code`, `total_amount` and `transaction_uuid` as query * params. No network. Feed `request.url` to your own `fetch`/cache. * * @example * const { url } = buildStatusRequest( * { product_code: "EPAYTEST", total_amount: 100, transaction_uuid: "tx-1" }, * { env: "test" }, * ); */ declare function buildStatusRequest(params: StatusRequestParams, opts?: { env?: EsewaEnv; }): StatusRequest; /** The parsed, typed shape of an eSewa transaction-status response. */ interface StatusResponse { product_code?: string; transaction_uuid?: string; total_amount?: number; /** Normalised to an {@link EsewaStatus} when recognised, else the raw string. */ status: EsewaStatus | string; /** eSewa reference id (present once settled). */ ref_id?: string; /** The original, untouched payload. */ raw: Record; } /** `true` if `status` is one of eSewa's documented status values. */ declare function isEsewaStatus(status: unknown): status is EsewaStatus; /** * Parse/narrow the untyped JSON returned by the status API (or `checkStatus`) * into a typed {@link StatusResponse}. Tolerant: unknown/missing `status` * becomes `"ERROR"`, `total_amount` is coerced to a number when it parses, and * the original payload is preserved on `.raw`. Pure, never throws. * * @example * const parsed = parseStatusResponse(await res.json()); * if (parsed.status === "COMPLETE") fulfilOrder(parsed.transaction_uuid!); */ declare function parseStatusResponse(input: unknown): StatusResponse; /** The typed shape of the decoded eSewa success `data` payload. */ interface EsewaSuccessData { transaction_code?: string; status?: EsewaStatus | string; total_amount?: string; transaction_uuid?: string; product_code?: string; signed_field_names?: string; signature?: string; /** Any other fields eSewa includes. */ [key: string]: unknown; } /** * Decode the base64 `data` payload eSewa posts to your success URL into a typed * {@link EsewaSuccessData} — WITHOUT checking the signature. Returns `null` when * the blob isn't valid base64 JSON. Pure, never throws. * * Use this only to read fields; to trust them, use {@link verifyDecodedResponse} * or the existing `verifyResponse`. * * @example * const data = decodeResponse(url.searchParams.get("data")!); * console.log(data?.status, data?.transaction_uuid); // untrusted until verified */ declare function decodeResponse(base64Data: string): EsewaSuccessData | null; /** Result of {@link verifyDecodedResponse}. */ interface VerifyDecodedResult { valid: boolean; /** The decoded payload, typed as {@link EsewaSuccessData}. */ data: EsewaSuccessData; } /** * Decode the base64 success payload into a typed object AND verify it, by * COMPOSING the existing `verifyResponse` (the signature logic is unchanged — * this only narrows the returned `data` type). Never throws. * * @example * const { valid, data } = await verifyDecodedResponse(rawData, secret); * if (valid && data.status === "COMPLETE") fulfilOrder(data.transaction_uuid!); */ declare function verifyDecodedResponse(base64Data: string, secret: string): Promise; /** * @lacspace/esewa * * eSewa ePay v2 (Nepal) — the correct, tiny way to integrate Nepal's most-used * payment gateway. Handles the three things every integration re-implements: * * 1. **Signing** — the HMAC-SHA256 signature eSewa requires on the checkout * form, computed over `total_amount,transaction_uuid,product_code` in the * exact order of `signed_field_names`, base64-encoded. * 2. **Form building** — a ready-to-POST `{ action, method, fields }` object * with every field eSewa expects, including a valid `signature`. * 3. **Verification & status** — decode and verify the signed base64 `data` * payload eSewa returns on success (timing-safe), and query the * transaction-status API. * * Built on Web Crypto (`globalThis.crypto.subtle`) — never hand-rolled * cryptography. Isomorphic: Node 20+, edge runtimes and browsers. Zero deps. */ type EsewaEnv = "test" | "prod"; /** eSewa checkout form endpoints (the URL you POST the form to). */ declare const ESEWA_FORM_URLS: Record; /** eSewa transaction-status API endpoints. */ declare const ESEWA_STATUS_URLS: Record; /** eSewa-published sandbox secret key (test environment only). */ declare const ESEWA_TEST_SECRET = "8gBm/:&EnhH.1/q@K@"; /** eSewa-published sandbox merchant/product code (test environment only). */ declare const ESEWA_TEST_PRODUCT_CODE = "EPAYTEST"; /** The fields eSewa signs, in the required order. */ declare const ESEWA_SIGNED_FIELD_NAMES = "total_amount,transaction_uuid,product_code"; interface SignFields { total_amount: string | number; transaction_uuid: string; product_code: string; } /** * Compute the eSewa signature for the required signed fields. The message is * `total_amount=,transaction_uuid=,product_code=` (the exact order of * `signed_field_names`), HMAC-SHA256'd with the merchant secret and returned as * standard base64. * * @example * const sig = await signPayment( * { total_amount: 100, transaction_uuid: "11-201", product_code: "EPAYTEST" }, * ESEWA_TEST_SECRET, * ); */ declare function signPayment(fields: SignFields, secret: string): Promise; /** * Convert integer paisa (minor units — as used across the @lacspace commerce * packages: cart, order, tax, invoice, money…) to rupees for eSewa's amount * fields. `paisaToRupees(12345)` → `123.45`. * * eSewa expects amounts in **rupees**, while the rest of the suite stores * **paisa** — convert at this boundary so a Rs 123.45 order isn't charged as * Rs 12,345. */ declare function paisaToRupees(paisa: number): number; interface BuildFormInput { /** * Base product amount, **in rupees** — eSewa's unit, NOT paisa. If you keep * integer minor units (paisa) like the other @lacspace commerce packages, * convert here with `paisaToRupees(paisa)`. Passing paisa overcharges 100×. */ amount: number; /** Tax amount, in rupees (see `amount`). Default 0. */ taxAmount?: number; /** Grand total, in rupees (see `amount`). Defaults to amount + tax + service + delivery. */ totalAmount?: number; /** Unique transaction id you generate. */ transactionUuid: string; /** Merchant product code (e.g. "EPAYTEST" in test). */ productCode: string; /** Where eSewa redirects on success. */ successUrl: string; /** Where eSewa redirects on failure. */ failureUrl: string; /** Product service charge. Default 0. */ productServiceCharge?: number; /** Product delivery charge. Default 0. */ productDeliveryCharge?: number; } interface EsewaForm { /** URL to POST the form to. */ action: string; method: "POST"; /** All fields eSewa expects, as strings ready for form inputs. */ fields: Record; } /** * Build a ready-to-POST eSewa checkout form: `{ action, method, fields }`. The * `total_amount` defaults to `amount + taxAmount + serviceCharge + deliveryCharge`, * and a valid `signature` is computed for you. * * @example * const form = await buildForm( * { amount: 100, transactionUuid: "11-201", productCode: ESEWA_TEST_PRODUCT_CODE, * successUrl: "https://me/ok", failureUrl: "https://me/fail" }, * { secret: ESEWA_TEST_SECRET, env: "test" }, * ); * // render form.fields as hidden inputs and auto-submit to form.action */ declare function buildForm(input: BuildFormInput, opts: { secret: string; env?: EsewaEnv; }): Promise; interface VerifyResult { valid: boolean; /** The decoded response fields. */ data: Record; } /** * Verify the signed base64 `data` payload eSewa appends to the success redirect. * Decodes the JSON, recomputes the signature over the fields named in its own * `signed_field_names`, and compares (timing-safe) against its `signature`. * Never throws — returns `{ valid, data }`. * * @example * const { valid, data } = await verifyResponse(url.searchParams.get("data")!, secret); * if (valid && data.status === "COMPLETE") fulfilOrder(data.transaction_uuid); */ declare function verifyResponse(base64Data: string, secret: string): Promise; interface StatusParams { product_code: string; total_amount: string | number; transaction_uuid: string; } /** * Query the eSewa transaction-status API. GETs the status endpoint with * `product_code`, `total_amount` and `transaction_uuid` as query params and * returns the parsed JSON. Inject a custom `fetch` for tests or non-global * runtimes. * * @example * const status = await checkStatus( * { product_code: "EPAYTEST", total_amount: 100, transaction_uuid: "11-201" }, * { env: "test" }, * ); */ declare function checkStatus(params: StatusParams, opts?: { env?: EsewaEnv; fetch?: typeof fetch; }): Promise; export { type AmountFields, type AmountValidation, type BuildFormInput, ESEWA_FORM_URLS, ESEWA_SIGNED_FIELD_NAMES, ESEWA_STATUS_URLS, ESEWA_TEST_PRODUCT_CODE, ESEWA_TEST_SECRET, type EsewaEnv, type EsewaForm, type EsewaStatus, type EsewaSuccessData, type SignFields, type StatusParams, type StatusRequest, type StatusRequestParams, type StatusResponse, type VerifyDecodedResult, type VerifyResult, buildForm, buildStatusRequest, checkStatus, decodeResponse, generateTransactionUuid, isEsewaStatus, isValidTransactionUuid, paisaToRupees, parseStatusResponse, signPayment, validateAmounts, verifyDecodedResponse, verifyResponse };