313 lines
12 KiB
TypeScript
313 lines
12 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
|
|
|
|
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
|
|
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_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(),
|
|
lagoCustomerId: z.string().nullable().optional(),
|
|
lagoSubscriptionId: z.string().nullable().optional(),
|
|
planCode: z.string().nullable().optional(),
|
|
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
|
|
})
|
|
.nullable()
|
|
.optional();
|
|
|
|
const molliePaymentSchema = z.object({
|
|
id: z.string(),
|
|
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(),
|
|
});
|
|
|
|
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
|
|
|
|
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
|
|
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<string, unknown>): 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<string, unknown>): Promise<PaymentGatewayPayment> {
|
|
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 PaymentGateway {
|
|
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 createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
|
|
validateCreatePaymentInput(input);
|
|
const response = await this.request("/payments", {
|
|
method: "POST",
|
|
body: {
|
|
amount: {
|
|
currency: input.currency.toUpperCase(),
|
|
value: centsToMollieValue(input.amountCents),
|
|
},
|
|
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
|
|
redirectUrl: input.redirectUrl,
|
|
webhookUrl: input.webhookUrl,
|
|
...(this.profileId ? { profileId: this.profileId } : {}),
|
|
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
|
|
metadata: {
|
|
tenantId: input.tenantId,
|
|
invoiceExternalId: input.invoiceExternalId,
|
|
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
|
|
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
|
|
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
|
|
...(input.planCode ? { planCode: input.planCode } : {}),
|
|
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
|
|
},
|
|
},
|
|
});
|
|
return toPayment(parseMollieResponse(response));
|
|
}
|
|
|
|
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
|
|
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 }): Promise<unknown | null> {
|
|
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" } : {}),
|
|
},
|
|
body: options.body ? JSON.stringify(options.body) : undefined,
|
|
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 response.json();
|
|
} catch (error) {
|
|
if (error instanceof MolliePaymentGatewayError) throw error;
|
|
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
}
|
|
|
|
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 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),
|
|
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,
|
|
lagoCustomerId: metadata.lagoCustomerId ?? null,
|
|
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
|
|
planCode: metadata.planCode ?? null,
|
|
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
|
|
},
|
|
};
|
|
}
|
|
|
|
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 validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
|
|
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");
|
|
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
|
|
throw new MolliePaymentGatewayError("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");
|
|
}
|
|
assertHttpUrl(input.redirectUrl, "Redirect URL");
|
|
assertHttpUrl(input.webhookUrl, "Webhook URL");
|
|
}
|
|
|
|
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 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): PaymentGatewayPaymentStatus {
|
|
const refundedCents = mollieValueToCents(refundedValue);
|
|
if (typeof refundedCents === "number" && refundedCents > 0) 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<string, unknown>, 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;
|
|
}
|