import Stripe from 'stripe';
import express from 'express';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const app = express();
app.post('/checkout', express.json(), async (req, res) => {
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: req.body.customerId,
line_items: [{
price: process.env.PRICE_ID!,
quantity: 1
}],
success_url: 'https://app.example.com/billing?ok=1'
}, {
idempotencyKey: `checkout-${req.body.orderId}`
});
res.json({
url: session.url
});
});
export const reportUsage = (customer: string, eventId: string, tokens:
number) =>
stripe.billing.meterEvents.create({
event_name: 'ai_tokens',
identifier: eventId,
payload: {
stripe_customer_id: customer,
value: String(tokens)
}
});
app.post('/webhook', express.raw({
type: 'application/json'
}), (req, res) => {
const event = stripe.webhooks.constructEvent(req.body, req.headers[
'stripe-signature'] !, process.env.WEBHOOK_SECRET!);
if (event.type === 'entitlements.active_entitlement_summary.updated') {
// enqueue: sync feature access for event.data.object.customer (dedupe on event.id)
}
res.sendStatus(200);
});