import { z } from "zod"; import { readBillingJsonResponse } from "./provider-http.js"; import { mollieLocales, mollieMandatePaymentMethods, molliePaymentMethodIds, mollieSepaFirstPaymentMethods, paymentBillingFlows, subscriptionProductKinds, } from "./types.js"; import type { ExhaustiveCustomerPaymentGateway, MollieLocale, MolliePaymentMethodId, MollieSepaFirstPaymentMethod, PaymentGateway, PaymentGatewayCreateCustomerInput, PaymentGatewayCreatePaymentInput, PaymentGatewayCustomer, PaymentGatewayListMethodsInput, PaymentGatewayMandate, PaymentGatewayPayment, PaymentGatewayPaymentMethod, PaymentGatewayPaymentStatus, PaymentBillingFlow, SubscriptionProductKind, } from "./types.js"; const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com"; const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000; const MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES = 1_000; export type MolliePaymentGatewayConfig = { apiKey: string; apiUrl?: string; profileId?: string | null; timeoutMs?: number; fetchImpl?: typeof fetch; }; export type MollieWebhookEvent = { providerPaymentId: string; }; export class MolliePaymentGatewayError extends Error { readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID" | "WEBHOOK_INVALID" | "WEBHOOK_PAYMENT_NOT_FOUND"; readonly status?: number; constructor(message: string, code: MolliePaymentGatewayError["code"], status?: number) { super(message); this.name = "MolliePaymentGatewayError"; this.code = code; this.status = status; } } const amountSchema = z.object({ currency: z.string().nullable().optional(), value: z.string().nullable().optional(), }); const metadataSchema = z .object({ tenantId: z.string().nullable().optional(), invoiceExternalId: z.string().nullable().optional(), paymentExternalId: z.string().nullable().optional(), mollieCustomerId: z.string().nullable().optional(), lagoCustomerId: z.string().nullable().optional(), lagoSubscriptionId: z.string().nullable().optional(), lagoProviderSubscriptionId: z.string().nullable().optional(), lagoPlanCode: z.string().nullable().optional(), planCode: z.string().nullable().optional(), subscriptionPriceId: z.string().nullable().optional(), seatQuantity: z.union([z.number(), z.string()]).nullable().optional(), officeSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(), fieldSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(), billingCadence: z.string().nullable().optional(), commitmentEndsAt: z.string().nullable().optional(), storageAddOnCodes: z.array(z.string()).nullable().optional(), trialEndsAt: z.string().nullable().optional(), changeEffectiveAt: z.string().nullable().optional(), changeEffectiveAtDate: z.string().nullable().optional(), billingFlow: z.string().nullable().optional(), productAcquisitionId: z.string().nullable().optional(), productKind: z.string().nullable().optional(), productScopeKey: z.string().nullable().optional(), subscriptionProductId: z.string().nullable().optional(), }) .nullable() .optional(); const molliePaymentSchema = z.object({ id: z.string(), customerId: z.string().nullable().optional(), status: z.string().nullable().optional(), amount: amountSchema.nullable().optional(), amountRefunded: amountSchema.nullable().optional(), amountRemaining: amountSchema.nullable().optional(), paidAt: z.string().nullable().optional(), expiresAt: z.string().nullable().optional(), metadata: metadataSchema, _links: z .object({ checkout: z .object({ href: z.string().nullable().optional(), }) .nullable() .optional(), }) .nullable() .optional(), }); const mollieCustomerSchema = z.object({ id: z.string(), name: z.string().nullable().optional(), email: z.string().nullable().optional(), locale: z.string().nullable().optional(), metadata: z .object({ tenantId: z.string().nullable().optional(), }) .nullable() .optional(), createdAt: z.string().nullable().optional(), }); const mollieCustomerPaymentsSchema = z.object({ _embedded: z.object({ payments: z.array(molliePaymentSchema) }), _links: z .object({ next: z .object({ href: z.string(), }) .nullable() .optional(), }) .nullable() .optional(), }); const mollieMethodSchema = z.object({ id: z.enum(molliePaymentMethodIds), description: z.string(), }); const mollieMethodsSchema = z.object({ _embedded: z.object({ methods: z.array(mollieMethodSchema), }), }); const mollieMandateSchema = z.object({ id: z.string(), status: z.enum(["valid", "pending", "invalid"]), method: z.enum(mollieMandatePaymentMethods), createdAt: z.string().nullable().optional(), }); const mollieMandatesSchema = z.object({ _embedded: z.object({ mandates: z.array(mollieMandateSchema), }), }); type MolliePaymentResponse = z.infer; type MollieCustomerResponse = z.infer; export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): ExhaustiveCustomerPaymentGateway { return new MolliePaymentGateway(config); } export function normalizeMollieApiUrl(apiUrl: string | undefined): string { const rawUrl = apiUrl?.trim() || DEFAULT_MOLLIE_API_URL; let url: URL; try { url = new URL(rawUrl); } catch { throw new MolliePaymentGatewayError("Mollie API URL must be an absolute URL.", "CONFIG_INVALID"); } if (url.protocol !== "http:" && url.protocol !== "https:") { throw new MolliePaymentGatewayError("Mollie API URL must use http or https.", "CONFIG_INVALID"); } url.pathname = url.pathname.replace(/\/+$/u, ""); return url.toString().replace(/\/$/u, ""); } export function redactMollieValue(value: string | null | undefined): string | null { if (!value) return null; if (value.length <= 8) return "[redacted]"; return `${value.slice(0, 4)}…${value.slice(-4)}`; } export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Record): MollieWebhookEvent { const id = getWebhookValue(input, "id")?.trim(); if (!id) { throw new MolliePaymentGatewayError("Mollie webhook is missing payment id.", "WEBHOOK_INVALID"); } return { providerPaymentId: id }; } export async function resolveMollieWebhookPayment( gateway: PaymentGateway, input: URLSearchParams | FormData | Record ): Promise { const event = parseMollieWebhookEvent(input); const payment = await gateway.getPayment(event.providerPaymentId); if (!payment) { throw new MolliePaymentGatewayError("Mollie webhook payment could not be verified.", "WEBHOOK_PAYMENT_NOT_FOUND", 404); } return payment; } class MolliePaymentGateway implements ExhaustiveCustomerPaymentGateway { private readonly apiUrl: string; private readonly apiKey: string; private readonly profileId: string | null; private readonly timeoutMs: number; private readonly fetchImpl: typeof fetch; constructor(config: MolliePaymentGatewayConfig) { this.apiUrl = normalizeMollieApiUrl(config.apiUrl); this.apiKey = config.apiKey.trim(); if (!this.apiKey) { throw new MolliePaymentGatewayError("Mollie API key is required.", "CONFIG_INVALID"); } this.profileId = config.profileId?.trim() || null; this.timeoutMs = normalizeTimeout(config.timeoutMs); this.fetchImpl = config.fetchImpl ?? fetch; } async createCustomer(input: PaymentGatewayCreateCustomerInput): Promise { const normalizedInput = validateCreateCustomerInput(input); const response = await this.request("/customers", { method: "POST", idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey), body: { name: normalizedInput.name, email: normalizedInput.email, ...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}), metadata: { tenantId: normalizedInput.tenantId, }, }, }); return toCustomer(parseMollieCustomerResponse(response)); } async createPayment(input: PaymentGatewayCreatePaymentInput): Promise { const normalizedInput = validateCreatePaymentInput(input); const response = await this.request("/payments", { method: "POST", idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey), body: { amount: { currency: input.currency.toUpperCase(), value: centsToMollieValue(input.amountCents), }, description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`, ...(input.redirectUrl ? { redirectUrl: input.redirectUrl } : {}), webhookUrl: input.webhookUrl, sequenceType: normalizedInput.sequenceType, ...(normalizedInput.method ? { method: normalizedInput.method } : {}), ...(normalizedInput.mandateId ? { mandateId: normalizedInput.mandateId } : {}), ...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}), ...(this.profileId ? { profileId: this.profileId } : {}), ...(normalizedInput.mollieCustomerId ? { customerId: normalizedInput.mollieCustomerId } : {}), metadata: { tenantId: input.tenantId, invoiceExternalId: input.invoiceExternalId, ...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}), ...(normalizedInput.mollieCustomerId ? { mollieCustomerId: normalizedInput.mollieCustomerId } : {}), ...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}), ...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}), ...(normalizedInput.lagoProviderSubscriptionId ? { lagoProviderSubscriptionId: normalizedInput.lagoProviderSubscriptionId } : {}), ...(normalizedInput.lagoPlanCode ? { lagoPlanCode: normalizedInput.lagoPlanCode } : {}), ...(input.planCode ? { planCode: input.planCode } : {}), ...(input.subscriptionPriceId ? { subscriptionPriceId: input.subscriptionPriceId } : {}), ...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}), ...(input.officeSeatQuantity !== null && input.officeSeatQuantity !== undefined ? { officeSeatQuantity: input.officeSeatQuantity } : {}), ...(input.fieldSeatQuantity !== null && input.fieldSeatQuantity !== undefined ? { fieldSeatQuantity: input.fieldSeatQuantity } : {}), ...(input.billingCadence ? { billingCadence: input.billingCadence } : {}), ...(normalizedInput.commitmentEndsAt ? { commitmentEndsAt: normalizedInput.commitmentEndsAt } : {}), ...(normalizedInput.storageAddOnCodes.length > 0 ? { storageAddOnCodes: normalizedInput.storageAddOnCodes } : {}), ...(normalizedInput.trialEndsAt ? { trialEndsAt: normalizedInput.trialEndsAt } : {}), ...(normalizedInput.changeEffectiveAt ? { changeEffectiveAt: normalizedInput.changeEffectiveAt } : {}), ...(normalizedInput.changeEffectiveAtDate ? { changeEffectiveAtDate: normalizedInput.changeEffectiveAtDate } : {}), ...(normalizedInput.billingFlow ? { billingFlow: normalizedInput.billingFlow } : {}), ...(normalizedInput.productAcquisitionId ? { productAcquisitionId: normalizedInput.productAcquisitionId } : {}), ...(normalizedInput.productKind ? { productKind: normalizedInput.productKind } : {}), ...(normalizedInput.productScopeKey ? { productScopeKey: normalizedInput.productScopeKey } : {}), ...(normalizedInput.subscriptionProductId ? { subscriptionProductId: normalizedInput.subscriptionProductId } : {}), }, }, }); return toPayment(parseMollieResponse(response)); } async listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise { const normalized = validateListPaymentMethodsInput(input); const query = new URLSearchParams({ sequenceType: normalized.sequenceType }); if (normalized.locale) query.set("locale", normalized.locale); if (normalized.amountCents !== null) { query.set("amount[value]", centsToMollieValue(normalized.amountCents)); query.set("amount[currency]", normalized.currency); } if (this.profileId) query.set("profileId", this.profileId); const response = await this.request(`/methods?${query.toString()}`, { method: "GET" }); const parsed = mollieMethodsSchema.safeParse(response); if (!parsed.success) { throw new MolliePaymentGatewayError("Mollie payment methods response shape is invalid.", "RESPONSE_INVALID"); } const ids = parsed.data._embedded.methods.map((method) => method.id); if (new Set(ids).size !== ids.length || parsed.data._embedded.methods.some((method) => !method.description.trim())) { throw new MolliePaymentGatewayError("Mollie payment methods response is ambiguous.", "RESPONSE_INVALID"); } return parsed.data._embedded.methods.map((method) => ({ provider: "mollie", id: method.id, description: method.description.trim(), })); } async listCustomerMandates(mollieCustomerId: string): Promise { const customerId = mollieCustomerId.trim(); if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID"); const response = await this.request(`/customers/${encodeURIComponent(customerId)}/mandates?limit=250`, { method: "GET" }); const parsed = mollieMandatesSchema.safeParse(response); if (!parsed.success) { throw new MolliePaymentGatewayError("Mollie mandates response shape is invalid.", "RESPONSE_INVALID"); } const ids = parsed.data._embedded.mandates.map((mandate) => mandate.id); if (new Set(ids).size !== ids.length || ids.some((id) => !/^mdt_.+/u.test(id))) { throw new MolliePaymentGatewayError("Mollie mandates response is ambiguous.", "RESPONSE_INVALID"); } return parsed.data._embedded.mandates.map((mandate) => ({ provider: "mollie", providerMandateId: mandate.id, status: mandate.status, method: mandate.method, createdAt: normalizeProviderTimestamp(mandate.createdAt), })); } async findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise { const customerId = mollieCustomerId.trim(); const externalId = paymentExternalId.trim(); if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID"); if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID"); const response = await this.request(`/customers/${encodeURIComponent(customerId)}/payments?limit=250&sort=desc`, { method: "GET" }); const parsed = mollieCustomerPaymentsSchema.safeParse(response); if (!parsed.success) throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID"); const payment = parsed.data._embedded.payments.find((candidate) => { const metadata = candidate.metadata ?? {}; return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId; }); return payment ? toPayment(payment) : null; } async findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise { const customerId = mollieCustomerId.trim(); const externalId = paymentExternalId.trim(); if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID"); if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID"); const expectedPathPrefix = `/customers/${encodeURIComponent(customerId)}/payments`; let path = `${expectedPathPrefix}?limit=250&sort=desc`; const visited = new Set(); for (let page = 0; page < MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES; page += 1) { if (visited.has(path)) { throw new MolliePaymentGatewayError("Mollie customer payments pagination looped.", "RESPONSE_INVALID"); } visited.add(path); const response = await this.request(path, { method: "GET" }); const parsed = mollieCustomerPaymentsSchema.safeParse(response); if (!parsed.success) { throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID"); } const payment = parsed.data._embedded.payments.find((candidate) => { const metadata = candidate.metadata ?? {}; return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId; }); if (payment) return toPayment(payment); const nextHref = parsed.data._links?.next?.href; if (!nextHref) return null; path = normalizeMollieCustomerPaymentsNextPath(nextHref, this.apiUrl, expectedPathPrefix); } throw new MolliePaymentGatewayError("Mollie customer payments pagination exceeded its safety bound.", "RESPONSE_INVALID"); } async getPayment(providerPaymentId: string): Promise { const id = providerPaymentId.trim(); if (!id) { throw new MolliePaymentGatewayError("Mollie payment id is required.", "CONFIG_INVALID"); } const response = await this.request(`/payments/${encodeURIComponent(id)}`, { method: "GET", allowNotFound: true }); return response === null ? null : toPayment(parseMollieResponse(response)); } private async request( path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean; idempotencyKey?: string | null } ): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), this.timeoutMs); try { const response = await this.fetchImpl(`${this.apiUrl}/v2${path}`, { method: options.method, headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json", ...(options.body ? { "content-type": "application/json" } : {}), ...(options.method === "POST" && options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}), }, body: options.body ? JSON.stringify(options.body) : undefined, redirect: "error", signal: controller.signal, }); if (response.status === 404 && options.allowNotFound) { return null; } if (!response.ok) { throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status); } return await readBillingJsonResponse(response); } catch (error) { if (error instanceof MolliePaymentGatewayError) throw error; throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED"); } finally { clearTimeout(timeout); } } } function normalizeMollieCustomerPaymentsNextPath(href: string, apiUrl: string, expectedPathPrefix: string): string { let next: URL; try { next = new URL(href, `${apiUrl}/v2/`); } catch { throw new MolliePaymentGatewayError("Mollie customer payments next link is invalid.", "RESPONSE_INVALID"); } const base = new URL(apiUrl); const expectedPath = `/v2${expectedPathPrefix}`; if (next.origin !== base.origin || next.pathname !== expectedPath) { throw new MolliePaymentGatewayError("Mollie customer payments next link is outside the requested collection.", "RESPONSE_INVALID"); } return `${expectedPathPrefix}${next.search}`; } function parseMollieResponse(response: unknown): MolliePaymentResponse { const result = molliePaymentSchema.safeParse(response); if (!result.success) { throw new MolliePaymentGatewayError("Mollie response shape is invalid.", "RESPONSE_INVALID"); } return result.data; } function parseMollieCustomerResponse(response: unknown): MollieCustomerResponse { const result = mollieCustomerSchema.safeParse(response); if (!result.success) { throw new MolliePaymentGatewayError("Mollie customer response shape is invalid.", "RESPONSE_INVALID"); } return result.data; } function toCustomer(customer: MollieCustomerResponse): PaymentGatewayCustomer { return { provider: "mollie", providerCustomerId: customer.id, tenantId: customer.metadata?.tenantId ?? null, name: customer.name ?? null, email: customer.email ?? null, locale: customer.locale ?? null, createdAt: customer.createdAt ?? null, }; } function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment { const metadata = payment.metadata ?? {}; return { provider: "mollie", providerPaymentId: payment.id, externalId: metadata.paymentExternalId ?? null, status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value, payment.amount?.value), amountCents: mollieValueToCents(payment.amount?.value), amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value), amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value), currency: payment.amount?.currency ?? null, checkoutUrl: payment._links?.checkout?.href ?? null, paidAt: payment.paidAt ?? null, expiresAt: payment.expiresAt ?? null, metadata: { tenantId: metadata.tenantId ?? null, invoiceExternalId: metadata.invoiceExternalId ?? null, paymentExternalId: metadata.paymentExternalId ?? null, mollieCustomerId: normalizeMetadataString(payment.customerId) ?? normalizeMetadataString(metadata.mollieCustomerId), lagoCustomerId: metadata.lagoCustomerId ?? null, lagoSubscriptionId: metadata.lagoSubscriptionId ?? null, lagoProviderSubscriptionId: normalizeMetadataString(metadata.lagoProviderSubscriptionId), lagoPlanCode: normalizeMetadataString(metadata.lagoPlanCode), planCode: metadata.planCode ?? null, subscriptionPriceId: normalizeMetadataString(metadata.subscriptionPriceId), seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity), officeSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.officeSeatQuantity), fieldSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.fieldSeatQuantity), billingCadence: normalizeMetadataString(metadata.billingCadence), commitmentEndsAt: normalizeMetadataIsoTimestamp(metadata.commitmentEndsAt), storageAddOnCodes: [...new Set((metadata.storageAddOnCodes ?? []).map((code) => code.trim()).filter(Boolean))], trialEndsAt: normalizeMetadataIsoTimestamp(metadata.trialEndsAt), changeEffectiveAt: normalizeChangeEffectiveAt(metadata.changeEffectiveAt), changeEffectiveAtDate: normalizeMetadataIsoTimestamp(metadata.changeEffectiveAtDate), billingFlow: normalizeBillingFlow(metadata.billingFlow), productAcquisitionId: normalizeMetadataString(metadata.productAcquisitionId), productKind: normalizeProductKind(metadata.productKind), productScopeKey: normalizeMetadataString(metadata.productScopeKey), subscriptionProductId: normalizeMetadataString(metadata.subscriptionProductId), }, }; } function normalizeMetadataSeatQuantity(value: string | number | null | undefined): number | null { if (typeof value === "number" && Number.isFinite(value)) { const normalized = Math.trunc(value); return normalized > 0 ? normalized : null; } if (typeof value === "string" && value.trim()) { const normalized = Number.parseInt(value, 10); return Number.isFinite(normalized) && normalized > 0 ? normalized : null; } return null; } function normalizeMetadataNonNegativeSeatQuantity(value: string | number | null | undefined): number | null { if (typeof value === "number" && Number.isFinite(value)) { const normalized = Math.trunc(value); return normalized >= 0 ? normalized : null; } if (typeof value === "string" && value.trim()) { const normalized = Number.parseInt(value, 10); return Number.isFinite(normalized) && normalized >= 0 ? normalized : null; } return null; } function validateCreateCustomerInput(input: PaymentGatewayCreateCustomerInput): { tenantId: string; name: string; email: string; locale: string | null; } { const tenantId = input.tenantId.trim(); const name = input.name.trim(); const email = input.email.trim(); const locale = input.locale?.trim() || null; if (!tenantId) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID"); if (!name) throw new MolliePaymentGatewayError("Customer name is required.", "CONFIG_INVALID"); if (!z.string().email().safeParse(email).success) { throw new MolliePaymentGatewayError("Customer email must be valid.", "CONFIG_INVALID"); } return { tenantId, name, email, locale }; } function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): { sequenceType: "oneoff" | "first" | "recurring"; method: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null; locale: MollieLocale | null; mollieCustomerId: string | null; mandateId: string | null; trialEndsAt: string | null; commitmentEndsAt: string | null; storageAddOnCodes: readonly string[]; changeEffectiveAt: "immediate" | "period_end" | null; changeEffectiveAtDate: string | null; billingFlow: PaymentBillingFlow | null; productAcquisitionId: string | null; productKind: SubscriptionProductKind | null; productScopeKey: string | null; subscriptionProductId: string | null; lagoProviderSubscriptionId: string | null; lagoPlanCode: string | null; } { if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID"); if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID"); const sequenceType = input.sequenceType ?? "oneoff"; if (sequenceType !== "oneoff" && sequenceType !== "first" && sequenceType !== "recurring") { throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID"); } if (!Number.isInteger(input.amountCents) || input.amountCents < 0 || (input.amountCents === 0 && sequenceType !== "first")) { throw new MolliePaymentGatewayError( sequenceType === "first" ? "Amount must be a non-negative cent integer." : "Amount must be a positive cent integer.", "CONFIG_INVALID" ); } if (!/^[A-Za-z]{3}$/u.test(input.currency)) { throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID"); } const mollieCustomerId = input.mollieCustomerId?.trim() || null; if ((sequenceType === "first" || sequenceType === "recurring") && !mollieCustomerId) { throw new MolliePaymentGatewayError("Mollie customer id is required for first and recurring payments.", "CONFIG_INVALID"); } const changeEffectiveAt = input.changeEffectiveAt ?? null; if (changeEffectiveAt !== null && changeEffectiveAt !== "immediate" && changeEffectiveAt !== "period_end") { throw new MolliePaymentGatewayError("Change effective mode is invalid.", "CONFIG_INVALID"); } if (sequenceType === "recurring") { if (input.redirectUrl) assertHttpUrl(input.redirectUrl, "Redirect URL"); } else { if (!input.redirectUrl) { throw new MolliePaymentGatewayError("Redirect URL is required.", "CONFIG_INVALID"); } assertHttpUrl(input.redirectUrl, "Redirect URL"); } assertHttpUrl(input.webhookUrl, "Webhook URL"); const billingFlow = normalizeBillingFlow(input.billingFlow); const productAcquisitionId = normalizeMetadataString(input.productAcquisitionId); const productKind = normalizeProductKind(input.productKind); const productScopeKey = normalizeMetadataString(input.productScopeKey); const subscriptionProductId = normalizeMetadataString(input.subscriptionProductId); const lagoProviderSubscriptionId = normalizeMetadataString(input.lagoProviderSubscriptionId); const lagoPlanCode = normalizeMetadataString(input.lagoPlanCode); const method = normalizePaymentMethod(input.method, sequenceType); const mandateId = normalizeMandateId(input.mandateId, sequenceType); if (sequenceType === "recurring" && !mandateId) { throw new MolliePaymentGatewayError("Mollie mandate id is required for recurring payments.", "CONFIG_INVALID"); } const storageAddOnCodes = (input.storageAddOnCodes ?? []).map((code) => normalizeMetadataString(code)); if (storageAddOnCodes.some((code) => code === null) || new Set(storageAddOnCodes).size !== storageAddOnCodes.length) { throw new MolliePaymentGatewayError("Storage add-on metadata is invalid.", "CONFIG_INVALID"); } if (billingFlow === "product_acquisition") { if (!productAcquisitionId || !productKind || !productScopeKey || !subscriptionProductId || !input.subscriptionPriceId?.trim()) { throw new MolliePaymentGatewayError("Product acquisition metadata is incomplete.", "CONFIG_INVALID"); } if (productKind === "base_plan" || productKind === "contract_override") { throw new MolliePaymentGatewayError("Product acquisition kind is not payable.", "CONFIG_INVALID"); } } return { sequenceType, method, locale: normalizeLocale(input.locale), mollieCustomerId, mandateId, trialEndsAt: normalizeIsoTimestamp(input.trialEndsAt, "Trial end"), commitmentEndsAt: normalizeIsoTimestamp(input.commitmentEndsAt, "Commitment end"), storageAddOnCodes: storageAddOnCodes as string[], changeEffectiveAt, changeEffectiveAtDate: normalizeIsoTimestamp(input.changeEffectiveAtDate, "Change effective date"), billingFlow, productAcquisitionId, productKind, productScopeKey, subscriptionProductId, lagoProviderSubscriptionId, lagoPlanCode, }; } function normalizePaymentMethod( value: PaymentGatewayCreatePaymentInput["method"], sequenceType: "oneoff" | "first" | "recurring" ): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null { if (value === null || value === undefined) return null; if (typeof value === "string") { if (!molliePaymentMethodIds.includes(value as MolliePaymentMethodId)) { throw new MolliePaymentGatewayError("Payment method is invalid.", "CONFIG_INVALID"); } if (sequenceType === "recurring" && value !== "directdebit" && value !== "creditcard" && value !== "paypal") { throw new MolliePaymentGatewayError("Recurring collection method is invalid.", "CONFIG_INVALID"); } if (sequenceType !== "recurring" && value === "directdebit") { throw new MolliePaymentGatewayError("Direct debit is valid only for recurring collection payments.", "CONFIG_INVALID"); } return value as MolliePaymentMethodId; } if (sequenceType !== "first" || value.length === 0) { throw new MolliePaymentGatewayError("SEPA authorization methods are valid only for first payments.", "CONFIG_INVALID"); } const allowed = new Set(mollieSepaFirstPaymentMethods); if (value.some((method) => !allowed.has(method)) || new Set(value).size !== value.length) { throw new MolliePaymentGatewayError("SEPA authorization payment methods are invalid.", "CONFIG_INVALID"); } return [...value]; } function normalizeMandateId(value: string | null | undefined, sequenceType: "oneoff" | "first" | "recurring"): string | null { if (value === null || value === undefined) return null; const mandateId = value.trim(); if (sequenceType !== "recurring" || !/^mdt_[A-Za-z0-9]+$/u.test(mandateId)) { throw new MolliePaymentGatewayError("Mollie mandate id is invalid.", "CONFIG_INVALID"); } return mandateId; } function normalizeProviderTimestamp(value: string | null | undefined): string | null { if (!value) return null; const parsed = new Date(value); return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString(); } function normalizeLocale(value: MollieLocale | null | undefined): MollieLocale | null { if (value === null || value === undefined) return null; if (!mollieLocales.includes(value)) { throw new MolliePaymentGatewayError("Mollie locale is invalid.", "CONFIG_INVALID"); } return value; } function validateListPaymentMethodsInput(input: PaymentGatewayListMethodsInput): { amountCents: number | null; currency: string; sequenceType: "oneoff" | "first" | "recurring"; locale: MollieLocale | null; } { const currency = input.currency.trim().toUpperCase(); if (!/^[A-Z]{3}$/u.test(currency)) { throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID"); } if (input.sequenceType !== "oneoff" && input.sequenceType !== "first" && input.sequenceType !== "recurring") { throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID"); } const amountCents = input.amountCents === null || input.amountCents === undefined ? null : input.amountCents; if (amountCents !== null && (!Number.isSafeInteger(amountCents) || amountCents < 0)) { throw new MolliePaymentGatewayError("Amount must be a non-negative cent integer.", "CONFIG_INVALID"); } return { amountCents, currency, sequenceType: input.sequenceType, locale: normalizeLocale(input.locale), }; } function normalizeBillingFlow(value: string | null | undefined): PaymentBillingFlow | null { return paymentBillingFlows.includes(value as PaymentBillingFlow) ? (value as PaymentBillingFlow) : null; } function normalizeProductKind(value: string | null | undefined): SubscriptionProductKind | null { return subscriptionProductKinds.includes(value as SubscriptionProductKind) ? (value as SubscriptionProductKind) : null; } function normalizeIsoTimestamp(value: string | null | undefined, label: string): string | null { if (value === null || value === undefined) return null; const normalized = value.trim(); if (!z.string().datetime({ offset: true }).safeParse(normalized).success) { throw new MolliePaymentGatewayError(`${label} must be an ISO timestamp with timezone.`, "CONFIG_INVALID"); } return new Date(normalized).toISOString(); } function normalizeChangeEffectiveAt(value: string | null | undefined): "immediate" | "period_end" | null { return value === "immediate" || value === "period_end" ? value : null; } function normalizeMetadataString(value: string | null | undefined): string | null { return value?.trim() || null; } function normalizeMetadataIsoTimestamp(value: string | null | undefined): string | null { const normalized = normalizeMetadataString(value); if (!normalized || !z.string().datetime({ offset: true }).safeParse(normalized).success) return null; return new Date(normalized).toISOString(); } function assertHttpUrl(value: string, label: string): void { let url: URL; try { url = new URL(value); } catch { throw new MolliePaymentGatewayError(`${label} must be an absolute URL.`, "CONFIG_INVALID"); } if (url.protocol !== "http:" && url.protocol !== "https:") { throw new MolliePaymentGatewayError(`${label} must use http or https.`, "CONFIG_INVALID"); } } function normalizeTimeout(timeoutMs: number | undefined): number { return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS; } function normalizeIdempotencyKey(value: string | null | undefined): string | null { if (value === null || value === undefined) return null; const key = value.trim(); if (!key || key.length > 255 || !/^[\x21-\x7e]+$/u.test(key)) { throw new MolliePaymentGatewayError("Idempotency key must contain 1 to 255 visible ASCII characters.", "CONFIG_INVALID"); } return key; } function centsToMollieValue(amountCents: number): string { return (amountCents / 100).toFixed(2); } function mollieValueToCents(value: string | null | undefined): number | null { if (!value) return null; const normalized = value.trim(); if (!/^-?\d+(\.\d{1,2})?$/u.test(normalized)) return null; return Math.round(Number(normalized) * 100); } function normalizePaymentStatus( status: string | null | undefined, refundedValue: string | null | undefined, originalValue: string | null | undefined ): PaymentGatewayPaymentStatus { const refundedCents = mollieValueToCents(refundedValue); const originalCents = mollieValueToCents(originalValue); // Mollie exposes partial and full refunds through the same amountRefunded // field. Only a full refund is a terminal payment state; a partial refund // keeps the provider status (normally `paid`) so the product ledger can // quarantine it for operator reconciliation without revoking the complete // entitlement. if (typeof refundedCents === "number" && typeof originalCents === "number" && originalCents > 0 && refundedCents >= originalCents) { return "refunded"; } if ( status === "open" || status === "pending" || status === "authorized" || status === "paid" || status === "failed" || status === "expired" || status === "canceled" ) { return status; } if (status === "charged_back") return "charged_back"; return "unknown"; } function getWebhookValue(input: URLSearchParams | FormData | Record, key: string): string | null { if (input instanceof URLSearchParams || input instanceof FormData) { const value = input.get(key); return typeof value === "string" ? value : null; } const value = input[key]; return typeof value === "string" ? value : null; }