feat:mollie and footer

This commit is contained in:
2026-03-05 16:08:33 +01:00
parent 835f0941dc
commit 3f5bb61e35
15 changed files with 580 additions and 293 deletions

View File

@@ -1,4 +1,4 @@
import { createHmac, randomUUID } from "node:crypto";
import { randomUUID } from "node:crypto";
import { creditRegistrationToAccount } from "@kk/api/routers/index";
import { db } from "@kk/db";
import { drinkkaart, drinkkaartTopup, registration } from "@kk/db/schema";
@@ -7,102 +7,106 @@ import { env } from "@kk/env/server";
import { createFileRoute } from "@tanstack/react-router";
import { and, eq } from "drizzle-orm";
// Webhook payload types
interface LemonSqueezyWebhookPayload {
meta: {
event_name: string;
custom_data?: {
registration_token?: string;
type?: string;
drinkkaartId?: string;
userId?: string;
};
};
data: {
id: string;
type: string;
attributes: {
customer_id: number;
order_number: number;
status: string;
total: number;
};
// Mollie payment object (relevant fields only)
interface MolliePayment {
id: string;
status: string;
amount: { value: string; currency: string };
customerId?: string;
metadata?: {
registration_token?: string;
type?: string;
drinkkaartId?: string;
userId?: string;
};
}
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string,
): boolean {
const hmac = createHmac("sha256", secret);
hmac.update(payload);
const digest = hmac.digest("hex");
return signature === digest;
async function fetchMolliePayment(paymentId: string): Promise<MolliePayment> {
const response = await fetch(
`https://api.mollie.com/v2/payments/${paymentId}`,
{
headers: {
Authorization: `Bearer ${env.MOLLIE_API_KEY}`,
},
},
);
if (!response.ok) {
throw new Error(
`Failed to fetch Mollie payment ${paymentId}: ${response.status}`,
);
}
return response.json() as Promise<MolliePayment>;
}
async function handleWebhook({ request }: { request: Request }) {
// Get the raw body as text for signature verification
const payload = await request.text();
const signature = request.headers.get("X-Signature");
if (!signature) {
return new Response("Missing signature", { status: 401 });
if (!env.MOLLIE_API_KEY) {
console.error("MOLLIE_API_KEY not configured");
return new Response("Payment provider not configured", { status: 500 });
}
if (!env.LEMON_SQUEEZY_WEBHOOK_SECRET) {
console.error("LEMON_SQUEEZY_WEBHOOK_SECRET not configured");
return new Response("Webhook secret not configured", { status: 500 });
// Mollie sends application/x-www-form-urlencoded with a single "id" field
let paymentId: string | null = null;
try {
const body = await request.text();
const params = new URLSearchParams(body);
paymentId = params.get("id");
} catch {
return new Response("Invalid request body", { status: 400 });
}
// Verify the signature
if (
!verifyWebhookSignature(
payload,
signature,
env.LEMON_SQUEEZY_WEBHOOK_SECRET,
)
) {
return new Response("Invalid signature", { status: 401 });
if (!paymentId) {
return new Response("Missing payment id", { status: 400 });
}
// Fetch-to-verify: retrieve the actual payment from Mollie to confirm its
// status. A malicious webhook cannot fake a paid status this way.
let payment: MolliePayment;
try {
payment = await fetchMolliePayment(paymentId);
} catch (err) {
console.error("Failed to fetch Mollie payment:", err);
return new Response("Failed to fetch payment", { status: 500 });
}
// Only process paid payments
if (payment.status !== "paid") {
return new Response("Payment status ignored", { status: 200 });
}
const metadata = payment.metadata;
try {
const event: LemonSqueezyWebhookPayload = JSON.parse(payload);
// Only handle order_created events
if (event.meta.event_name !== "order_created") {
return new Response("Event ignored", { status: 200 });
}
const customData = event.meta.custom_data;
// ---------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Branch: Drinkkaart top-up
// ---------------------------------------------------------------------------
if (customData?.type === "drinkkaart_topup") {
const { drinkkaartId, userId } = customData;
// -------------------------------------------------------------------------
if (metadata?.type === "drinkkaart_topup") {
const { drinkkaartId, userId } = metadata;
if (!drinkkaartId || !userId) {
console.error(
"Missing drinkkaartId or userId in drinkkaart_topup webhook",
"Missing drinkkaartId or userId in drinkkaart_topup payment metadata",
);
return new Response("Missing drinkkaart data", { status: 400 });
}
const orderId = event.data.id;
const customerId = String(event.data.attributes.customer_id);
// Use Lemon Squeezy's confirmed total (in cents)
const amountCents = event.data.attributes.total;
// Amount in cents — Mollie returns e.g. "10.00"; parse to integer cents
const amountCents = Math.round(
Number.parseFloat(payment.amount.value) * 100,
);
// Idempotency: skip if already processed
const existing = await db
.select({ id: drinkkaartTopup.id })
.from(drinkkaartTopup)
.where(eq(drinkkaartTopup.lemonsqueezyOrderId, orderId))
.where(eq(drinkkaartTopup.molliePaymentId, payment.id))
.limit(1)
.then((r) => r[0]);
if (existing) {
console.log(`Drinkkaart topup already processed for order ${orderId}`);
console.log(
`Drinkkaart topup already processed for payment ${payment.id}`,
);
return new Response("OK", { status: 200 });
}
@@ -137,7 +141,7 @@ async function handleWebhook({ request }: { request: Request }) {
);
if (result.rowsAffected === 0) {
// Return 500 so Lemon Squeezy retries; idempotency check prevents double-credit
// Return 500 so Mollie retries; idempotency check prevents double-credit
console.error(
`Drinkkaart optimistic lock conflict for ${drinkkaartId}`,
);
@@ -152,33 +156,29 @@ async function handleWebhook({ request }: { request: Request }) {
balanceBefore,
balanceAfter,
type: "payment",
lemonsqueezyOrderId: orderId,
lemonsqueezyCustomerId: customerId,
molliePaymentId: payment.id,
adminId: null,
reason: null,
paidAt: new Date(),
});
console.log(
`Drinkkaart topup successful: drinkkaart=${drinkkaartId}, amount=${amountCents}c, order=${orderId}`,
`Drinkkaart topup successful: drinkkaart=${drinkkaartId}, amount=${amountCents}c, payment=${payment.id}`,
);
return new Response("OK", { status: 200 });
}
// ---------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Branch: Registration payment
// ---------------------------------------------------------------------------
const registrationToken = customData?.registration_token;
// -------------------------------------------------------------------------
const registrationToken = metadata?.registration_token;
if (!registrationToken) {
console.error("No registration token in webhook payload");
console.error("No registration token in payment metadata");
return new Response("Missing registration token", { status: 400 });
}
const orderId = event.data.id;
const customerId = String(event.data.attributes.customer_id);
// Fetch the registration row first so we can use its email + drinkCardValue.
// Fetch the registration row
const regRow = await db
.select()
.from(registration)
@@ -191,30 +191,27 @@ async function handleWebhook({ request }: { request: Request }) {
return new Response("Registration not found", { status: 404 });
}
// Mark the registration as paid. Covers both "pending" (initial payment) and
// "extra_payment_pending" (delta after adding guests).
// Mark the registration as paid
await db
.update(registration)
.set({
paymentStatus: "paid",
paymentAmount: 0, // delta has been settled
lemonsqueezyOrderId: orderId,
lemonsqueezyCustomerId: customerId,
paymentAmount: 0,
molliePaymentId: payment.id,
paidAt: new Date(),
})
.where(eq(registration.managementToken, registrationToken));
console.log(
`Payment successful for registration ${registrationToken}, order ${orderId}`,
`Payment successful for registration ${registrationToken}, payment ${payment.id}`,
);
// If this is a watcher with a drink card value, try to credit their drinkkaart
// immediately — but only if they already have an account.
// If this is a watcher with a drink card value, try to credit their
// drinkkaart immediately — but only if they already have an account.
if (
regRow.registrationType === "watcher" &&
(regRow.drinkCardValue ?? 0) > 0
) {
// Look up user account by email
const accountUser = await db
.select({ id: user.id })
.from(user)
@@ -244,8 +241,6 @@ async function handleWebhook({ request }: { request: Request }) {
);
}
} else {
// No account yet — credit will be applied when the user signs up via
// claimRegistrationCredit.
console.log(
`No account for ${regRow.email} — drinkkaart credit deferred until signup`,
);
@@ -259,7 +254,7 @@ async function handleWebhook({ request }: { request: Request }) {
}
}
export const Route = createFileRoute("/api/webhook/lemonsqueezy")({
export const Route = createFileRoute("/api/webhook/mollie")({
server: {
handlers: {
POST: handleWebhook,

View File

@@ -53,6 +53,28 @@ function ContactPage() {
</p>
</section>
<section className="rounded-lg bg-white/5 p-6">
<h3 className="mb-4 text-white text-xl">Partners</h3>
<div className="flex flex-col gap-3 sm:flex-row sm:gap-6">
<a
href="https://ejv.be"
target="_blank"
rel="noopener noreferrer"
className="link-hover text-white/80 hover:text-white"
>
Evangelisch Jeugdverbond (EJV.be)
</a>
<a
href="https://www.vlaanderen.be/cjm/nl"
target="_blank"
rel="noopener noreferrer"
className="link-hover text-white/80 hover:text-white"
>
Vlaanderen Cultuur, Jeugd & Media
</a>
</div>
</section>
<section className="mt-8">
<p className="text-sm text-white/60">
We proberen je e-mail binnen 48 uur te beantwoorden.