nomadro/app/book/api/creem/webhook/route.ts
eric 9928c5185b Mount nav/book/community as native App Router routes in one Next process.
Replace reverse-proxy/iframe approach with @ebook/@community/@navmini imports under /nav /book /community so localhost:3000 serves all three products directly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:49:16 -05:00

89 lines
2.4 KiB
TypeScript

import { NextResponse } from 'next/server';
import { verifyCreemSignature } from '@ebook/lib/creem';
// Creem webhook payload shape per docs
// https://docs.creem.io/code/webhooks
type CreemCheckoutObject = {
id: string;
object: 'checkout';
request_id?: string;
status: string;
order?: {
id: string;
customer: string;
product: string;
amount: number;
currency: string;
status: string;
};
product?: { id: string; name: string };
customer?: { id: string; email: string; name?: string };
subscription?: { id: string; status: string };
metadata?: Record<string, string>;
};
type CreemWebhookEvent = {
id: string;
eventType: string;
created_at: number;
object: CreemCheckoutObject | Record<string, unknown>;
};
export async function POST(req: Request) {
const raw = await req.text();
// Creem always uses "creem-signature" header (HMAC-SHA256)
const signature = req.headers.get('creem-signature');
if (!verifyCreemSignature(raw, signature)) {
console.warn('Creem webhook: invalid signature');
return NextResponse.json({ ok: false }, { status: 401 });
}
let payload: CreemWebhookEvent;
try {
payload = JSON.parse(raw) as CreemWebhookEvent;
} catch {
return NextResponse.json({ ok: false }, { status: 400 });
}
const { eventType, object: obj } = payload;
const checkout = obj as CreemCheckoutObject;
console.info('Creem webhook received', {
id: payload.id,
eventType,
objectId: checkout.id,
status: checkout.status,
email: checkout.customer?.email,
orderId: checkout.order?.id,
amount: checkout.order?.amount,
currency: checkout.order?.currency,
});
switch (eventType) {
case 'checkout.completed':
// One-time ebook purchase confirmed — add post-purchase logic here
// e.g. send download email, unlock content, record in DB
console.info('Creem: checkout completed', {
checkoutId: checkout.id,
email: checkout.customer?.email,
orderId: checkout.order?.id,
});
break;
case 'refund.created':
console.info('Creem: refund created', { objectId: checkout.id });
break;
case 'dispute.created':
console.warn('Creem: dispute created', { objectId: checkout.id });
break;
default:
// subscription.* events — not relevant for one-time product, log and ignore
break;
}
return NextResponse.json({ ok: true });
}