import { Auth } from 'firebase-admin/auth'; import { Firestore } from 'firebase-admin/firestore'; /** Firestore document shape — handlers treat data as generic records. Consumer's onPaymentSucceeded callback gets the full doc and can cast to its own typed Order. */ type FirestoreData = Record; /** Order shape the handler reads/writes. Permissive on purpose — consumer extends. */ interface MinimalOrder extends FirestoreData { id?: string; status?: string; userId?: string; items?: Array<{ productId: string; name: string; price: number; quantity: number; }>; total?: number; subtotal?: number; vat?: number; discount?: number; promotionId?: string; couponCode?: string; shippingAddress?: { fullName?: string; } & FirestoreData; /** Optional note shown to the customer post-purchase; echoed into the * confirmation email when present. */ postPurchaseNote?: string; /** Set by charge.ts when the user opted out of saving the card AND the order * enters an intermediate status (3ds-pending / otp-pending). The downstream * handler that finalizes the payment (3ds-complete, webhook BY_CRES) reads * these to call deleteCard on the SDK once the order transitions to paid. */ deleteCardAfterPayment?: boolean; /** Nuvei card token. Persisted alongside deleteCardAfterPayment so the * downstream handler can pass it to deleteCard(token, userId). */ paymentToken?: string; } /** Args passed to email.sendPaymentConfirmation. */ interface PaymentConfirmationArgs { to: string; customerName: string; orderId: string; transactionId: string; authorizationCode: string; items: MinimalOrder["items"]; subtotal: number; discount?: number; couponCode?: string; vat: number; total: number; postPurchaseNote?: string; } /** Args passed to email.sendPaymentFailed. `retryUrl` is optional — consumers' email templates typically have their own absolute default (e.g. `https://shop.example.com/checkout`). If the handler's `getRetryUrl` dep is not configured, this field is omitted and the template default applies. */ interface PaymentFailedArgs { to: string; customerName: string; orderId: string; errorMessage: string; items: MinimalOrder["items"]; total: number; retryUrl?: string; } /** Args passed to email.sendPaymentPending (webhook fallback when auth_code missing). */ interface PaymentPendingArgs { to: string; customerName: string; orderId: string; transactionId: string; items: MinimalOrder["items"]; subtotal: number; discount?: number; couponCode?: string; vat: number; total: number; } /** Email service contract — full surface used across all handlers. Each handler factory picks which methods it requires via Pick<>. */ interface EmailService { sendPaymentConfirmation: (args: PaymentConfirmationArgs) => Promise<{ success: boolean; }>; sendPaymentFailed: (args: PaymentFailedArgs) => Promise; sendPaymentPending: (args: PaymentPendingArgs) => Promise; } /** Firebase admin services the handler needs. */ interface FirebaseDeps { db: Firestore; auth: Auth; } /** Rate limit check. Returns true if allowed, false if rate-limited. */ type RateLimitFn = (key: string, limit: number, windowMs: number) => Promise; /** Turnstile (Cloudflare bot protection) verification. */ type TurnstileFn = (token: string, ip?: string) => Promise<{ success: boolean; }>; /** Pricing function — receives product data, returns the effective final subtotal. */ type GetPriceDisplayFn = (product: { price: number; autoDiscounts?: unknown; }) => { finalSubtotal: number; }; /** Custom order validation result. Used for non-standard order flows (paymentLinks, talleres). */ type CustomOrderValidationResult = { handled: false; } | { handled: true; valid: true; } | { handled: true; valid: false; error: string; status: number; }; /** Custom order validator. Receives the order doc + amount; returns whether this is a custom-flow order and whether it's valid. */ type ValidateCustomOrderFn = (args: { orderId: string; orderData: MinimalOrder; amount: number; /** uid of the verified session (cookie or Bearer). Compare it with `orderData.userId` to check the owner. */ userId: string; }) => Promise; /** * Optional hook, awaited right after a handler moves the order to `failed` (bank decline, 3DS rejected, * 3DS timeout). `reason` is the message shown to the customer. Errors are logged and never change the response. */ type PaymentFailedHook = (order: MinimalOrder & { id: string; }, reason: string) => Promise; /** Dependencies the charge handler factory needs. */ interface ChargeHandlerDeps { /** Firebase Admin services. Provided by the consumer (so the package never owns its own Firebase init). */ firebase: FirebaseDeps; /** Email service. Consumer wires up Resend (or any provider) with their own branding/templates. */ email: EmailService; /** Pricing function — receives product fields and returns the effective final subtotal. Consumer-specific because pricing rules vary per business. */ getPriceDisplay: GetPriceDisplayFn; /** Merchant name. Used as fallback for the Nuvei transaction description when the request body doesn't provide one (visible to the cardholder in their bank statement). */ merchantName: string; /** Optional rate limit check. If omitted, no rate limiting is applied. */ rateLimit?: RateLimitFn; /** Optional Turnstile (Cloudflare bot protection) verification. If omitted, the turnstileToken from the body is ignored. */ turnstile?: TurnstileFn; /** Optional Cloud Functions base URL for the 3DS challenge callback (termUrl). If omitted, falls back to `process.env.CLOUD_FUNCTIONS_BASE_URL`. */ cloudFunctionsBaseUrl?: string; /** Optional custom order validator — used for non-standard order flows (e.g. paymentLinks, taller-specific orders). If returned result is `{ handled: false }` the handler runs standard product/promotion validation. */ validateCustomOrder?: ValidateCustomOrderFn; /** Optional post-success hook — runs after the order is marked paid and the Firestore batch commits. Use this for course enrollment, paymentLink usage tracking, fulfillment triggers, etc. Errors are caught and logged but don't fail the response. */ onPaymentSucceeded?: (order: MinimalOrder & { id: string; }) => Promise; /** Optional retry URL builder for payment-failed emails. Receives the order, returns the URL the customer should be sent to. Default: `https://${request.host}/checkout`. */ getRetryUrl?: (order: MinimalOrder & { id: string; }) => string; /** Optional hook, awaited after a decline moves the order to `failed`. See `PaymentFailedHook`. */ onPaymentFailed?: PaymentFailedHook; /** Set `false` if your `onPaymentSucceeded` counts the coupon use itself: the package then leaves `promotions/{promotionId}` alone. Default `true`. */ countCouponUsage?: boolean; /** Optional logger (defaults to console). */ logger?: Pick; } /** * Creates a Next.js App Router POST handler for the `/api/payment/charge` endpoint. * * Performs: session verification, rate limiting, Turnstile, order/stock/price/coupon * validation, Nuvei debit call, 3DS/OTP handling, Firestore order updates, email * dispatch, and optional post-success side effects via `onPaymentSucceeded`. */ declare function createChargeHandler(deps: ChargeHandlerDeps): (request: Request) => Promise; interface NuveiWebhookPayload { transaction: { id: string; status: string; status_detail: number; /** Desenlace en texto: APPROVED, CANCELLED, EXPIRED, REJECTED o PENDING. */ current_status?: string; dev_reference: string; amount: number; authorization_code: string | null; message: string | null; carrier_code: string | null; }; user: { id: string; email: string; }; } /** Dependencies the webhook handler factory needs. */ interface WebhookHandlerDeps { firebase: FirebaseDeps; email: Pick; /** * Shared secret used to authenticate the incoming webhook. Paymentez/Nuvei * DMNs are NOT signed, so the only robust auth is a secret the merchant * embeds in the DMN URL configured in the Nuvei dashboard, e.g. * `https://shop.com/api/webhooks/nuvei?key=THE_SECRET` (also accepted as the * `x-webhook-key` header). Falls back to `process.env.NUVEI_WEBHOOK_SECRET`. * * If set, requests without a matching key are rejected with 401. If unset, * the handler logs a loud warning and processes anyway (the endpoint is then * forgeable — anyone who knows an orderId could fake a "paid" notification). * STRONGLY RECOMMENDED in production. */ webhookSecret?: string; /** `false` leaves `promotions/{promotionId}` alone on the verify-BY_CRES path (your `onPaymentSucceeded` counts the use). Default `true`. */ countCouponUsage?: boolean; /** Optional post-success hook. Fires when the webhook transitions an order to "paid" (either via direct status_detail=3 or via verify BY_CRES). Used for enrollment, fulfillment triggers, paymentLink usage tracking, etc. */ onPaymentSucceeded?: (order: MinimalOrder & { id: string; }) => Promise; /** Optional custom dev_reference handler. If the webhook's `transaction.dev_reference` matches a custom format (e.g. "pn_" for Plan Novios), the consumer returns a Response and the standard order flow is skipped. Return null to fall through to standard order processing. */ handleCustomDevReference?: (devReference: string, transaction: NuveiWebhookPayload["transaction"], payload: NuveiWebhookPayload) => Promise; logger?: Pick; } /** * Creates a Next.js App Router POST handler for the Nuvei webhook callback. * Reference: https://developers.paymentez.com/api/#webhook */ declare function createWebhookHandler(deps: WebhookHandlerDeps): (request: Request) => Promise; /** Dependencies the 3DS callback handler factory needs. */ interface ThreeDSCallbackHandlerDeps { firebase: { db: Firestore; }; logger?: Pick; /** * Opcionales, y solo para el caso en que el emisor rechaza la autenticación. * * Sin ellos el pedido igual se cierra —que es lo que importa— pero el cliente no recibe el * correo de pago fallido, y eso queda avisado en el log. Son opcionales a propósito: así una * web que ya monta esta ruta sigue funcionando al subir de versión sin tocar nada. */ email?: Pick; getRetryUrl?: (order: MinimalOrder & { id: string; }) => string; onPaymentFailed?: PaymentFailedHook; } /** * Creates the 3DS callback route handlers. Returns `{ POST, GET }` because the * ACS may call either depending on bank/issuer. * * Usage (Next.js): export const { POST, GET } = create3dsCallbackHandler({ firebase: { db } }); * Usage (Functions): const { POST } = create3dsCallbackHandler({ firebase: { db } }); * exports.threeDSCallback = onRequest({ cors: true }, toCloudFunction(POST)); */ declare function create3dsCallbackHandler(deps: ThreeDSCallbackHandlerDeps): { POST: (request: Request) => Promise; GET: (request: Request) => Promise; }; /** Dependencies the 3DS complete handler factory needs. */ interface ThreeDSCompleteHandlerDeps { firebase: FirebaseDeps; email: Pick; /** Optional post-success hook for consumer-specific side effects after verify succeeds. */ onPaymentSucceeded?: (order: MinimalOrder & { id: string; }) => Promise; /** Optional retry URL builder for payment-failed emails sent when 3DS verification fails or the auth status is rejected. If omitted, the consumer's email template default is used. */ getRetryUrl?: (order: MinimalOrder & { id: string; }) => string; /** Optional hook, awaited after the order moves to `failed`. See `PaymentFailedHook`. */ onPaymentFailed?: PaymentFailedHook; /** `false` leaves `promotions/{promotionId}` alone (your `onPaymentSucceeded` counts the use). Default `true`. */ countCouponUsage?: boolean; logger?: Pick; } /** * Creates a Next.js App Router POST handler for the 3DS complete endpoint. * Called by the client after challenge completion to finalize the payment. */ declare function create3dsCompleteHandler(deps: ThreeDSCompleteHandlerDeps): (request: Request) => Promise; /** Dependencies the 3DS timeout handler factory needs. */ interface ThreeDSTimeoutHandlerDeps { firebase: FirebaseDeps; email: Pick; /** Optional retry URL builder. Default: "/checkout". */ getRetryUrl?: (order: MinimalOrder & { id: string; }) => string; /** Optional hook, awaited after the order moves to `failed`. See `PaymentFailedHook`. */ onPaymentFailed?: PaymentFailedHook; logger?: Pick; } declare function create3dsTimeoutHandler(deps: ThreeDSTimeoutHandlerDeps): (request: Request) => Promise; /** Half an hour. Banks give the customer several minutes for their code; by thirty none is * still alive. Waiting too long only leaves the order in the dashboard a while longer; * waiting too little would close a payment the customer is in the middle of. */ declare const DEFAULT_SWEEP_AFTER_MS: number; interface ThreeDSSweepHandlerDeps { firebase: FirebaseDeps; email: Pick; /** Shared secret expected in the `x-cron-key` header. Without it the handler refuses every * request: an open sweep endpoint lets anyone cancel pending orders. */ cronSecret: string | undefined; /** How long an order may sit in `3ds-pending` before it is checked. Default: 30 minutes. */ sweepAfterMs?: number; /** How many orders to touch per run. Default: 50. */ limit?: number; getRetryUrl?: (order: MinimalOrder & { id: string; }) => string; /** Optional hook, awaited after an order moves to `failed`. See `PaymentFailedHook`. */ onPaymentFailed?: PaymentFailedHook; logger?: Pick; } interface ThreeDSSweepResult { checked: number; closed: number; /** Charged in Nuvei but still `3ds-pending` here. Left untouched, flagged for a human. */ paidNeedsReview: number; /** No transaction id or no user id — nothing to ask Nuvei about. Left untouched. */ missingData: number; /** Nuvei did not answer, answered with an HTTP error, or answered something that is not an * explicit rejection or expiry. Left untouched; the next run retries. */ errored: number; } declare function create3dsSweepHandler(deps: ThreeDSSweepHandlerDeps): (request: Request) => Promise; /** Dependencies the refund handler factory needs. */ interface RefundHandlerDeps { firebase: FirebaseDeps; /** Optional hook after a successful refund (e.g. revoke course access, send email). */ onRefundSucceeded?: (order: MinimalOrder & { id: string; }) => Promise; logger?: Pick; } declare function createRefundHandler(deps: RefundHandlerDeps): (request: Request) => Promise; /** Dependencies the init-checkout handler factory needs. */ interface InitCheckoutHandlerDeps { firebase: { auth: Auth; }; /** Default description shown to the customer in the Nuvei checkout if the request body doesn't provide one. Use the merchant name (e.g. "Pago Acme Shop"). */ defaultDescription: string; /** Theme colors for the Nuvei checkout modal. */ themeColors: { primary: string; secondary: string; }; logger?: Pick; } declare function createInitCheckoutHandler(deps: InitCheckoutHandlerDeps): (request: Request) => Promise; /** Dependencies the cards handler factory needs. */ interface CardsHandlerDeps { firebase: FirebaseDeps; /** Whether to consult users/{uid}/verifiedCards to upgrade "review" status to "valid" client-side. Defaults to true. Set false if your client doesn't use the Diners/Pichincha verify flow. */ enableVerifiedCardsTracking?: boolean; logger?: Pick; } /** * Creates a Next.js App Router route module for the cards endpoint. * Returns `{ GET, DELETE }` to be re-exported by the consumer's route.ts. * * Usage: * export const { GET, DELETE } = createCardsHandler({ firebase: { db, auth } }); */ declare function createCardsHandler(deps: CardsHandlerDeps): { GET: (request: Request) => Promise; DELETE: (request: Request) => Promise; }; /** Dependencies the verify handler factory needs. */ interface VerifyHandlerDeps { firebase: FirebaseDeps; /** Whether to persist verification in users/{uid}/verifiedCards/{token}. Defaults to true. */ enableVerifiedCardsTracking?: boolean; logger?: Pick; } declare function createVerifyHandler(deps: VerifyHandlerDeps): (request: Request) => Promise; /** Dependencies the test-charge handler factory needs. */ interface TestChargeHandlerDeps { firebase: { auth: Auth; }; /** Default description shown in Nuvei when the request body omits one. Defaults to "Test charge". */ defaultDescription?: string; logger?: Pick; } declare function createTestChargeHandler(deps: TestChargeHandlerDeps): (request: Request) => Promise; interface NuveiProxyHandlerDeps { logger?: Pick; } /** * Creates a Web-standard POST handler that forwards `{ path, method, body }` to * Nuvei's REST API, attaching the caller-supplied `x-nuvei-auth-token` as the * `Auth-Token` header and selecting prod/stg from `x-nuvei-env`. * * Usage (Next.js): export const POST = createNuveiProxyHandler(); * Usage (Functions): exports.nuveiProxy = onRequest({ cors: true }, * toCloudFunction(createNuveiProxyHandler())); */ declare function createNuveiProxyHandler(deps?: NuveiProxyHandlerDeps): (request: Request) => Promise; export { type CardsHandlerDeps, type ChargeHandlerDeps, type CustomOrderValidationResult, DEFAULT_SWEEP_AFTER_MS, type EmailService, type FirebaseDeps, type FirestoreData, type GetPriceDisplayFn, type InitCheckoutHandlerDeps, type MinimalOrder, type NuveiProxyHandlerDeps, type PaymentConfirmationArgs, type PaymentFailedArgs, type PaymentFailedHook, type PaymentPendingArgs, type RateLimitFn, type RefundHandlerDeps, type TestChargeHandlerDeps, type ThreeDSCallbackHandlerDeps, type ThreeDSCompleteHandlerDeps, type ThreeDSSweepHandlerDeps, type ThreeDSSweepResult, type ThreeDSTimeoutHandlerDeps, type TurnstileFn, type ValidateCustomOrderFn, type VerifyHandlerDeps, type WebhookHandlerDeps, create3dsCallbackHandler, create3dsCompleteHandler, create3dsSweepHandler, create3dsTimeoutHandler, createCardsHandler, createChargeHandler, createInitCheckoutHandler, createNuveiProxyHandler, createRefundHandler, createTestChargeHandler, createVerifyHandler, createWebhookHandler };