Elffuss BraidHub

kikocis/clonagent public

main · 7.1 KiBRawPermalink
1// Stripe billing: checkout, customer portal, webhook.
2const express = require('express');
3const { getStripe } = require('../lib/stripe-client');
4const users = require('../lib/users');
5const { getPlan, allPlans } = require('../lib/plans');
6const { sendUpgradeConfirmation } = require('../lib/mailer');
7
8const router = express.Router();
9
10const PUBLIC_URL = () => process.env.PUBLIC_URL || 'https://clonagent.utopiaia.com';
11
12// ── GET /api/billing/plans ──────────────────────────────────────────────────
13router.get('/plans', (req, res) => {
14 res.json(allPlans().map(p => ({
15 id: p.id,
16 name: p.name,
17 price: p.price,
18 maxAgents: p.maxAgents,
19 maxRunsPerMonth: p.maxRunsPerMonth === Infinity ? null : p.maxRunsPerMonth,
20 stripePriceId: !!p.stripePriceId, // just expose whether it's configured
21 })));
22});
23
24// ── GET /api/billing/me ─────────────────────────────────────────────────────
25router.get('/me', (req, res) => {
26 if (!req.session?.user) return res.status(401).json({ error: 'auth required' });
27 const u = users.findUser(req.session.user.sub);
28 if (!u) return res.status(404).json({ error: 'user not found' });
29 const plan = getPlan(u.plan || 'free');
30 res.json({
31 plan: plan.id,
32 planName: plan.name,
33 maxAgents: plan.maxAgents,
34 maxRunsPerMonth: plan.maxRunsPerMonth === Infinity ? null : plan.maxRunsPerMonth,
35 stripeCustomerId: u.stripeCustomerId || null,
36 subscriptionStatus: u.subscriptionStatus || (plan.id === 'free' ? 'free' : 'active'),
37 planExpiresAt: u.planExpiresAt || null,
38 });
39});
40
41// ── POST /api/billing/checkout ──────────────────────────────────────────────
42router.post('/checkout', async (req, res) => {
43 if (!req.session?.user) return res.status(401).json({ error: 'auth required' });
44 const stripe = getStripe();
45 if (!stripe) return res.status(503).json({ error: 'Stripe not configured — add STRIPE_SECRET_KEY' });
46
47 const { planId } = req.body || {};
48 const plan = getPlan(planId);
49 if (!plan.stripePriceId) return res.status(400).json({ error: `No Stripe price configured for plan "${planId}"` });
50
51 const u = users.findUser(req.session.user.sub);
52 if (!u) return res.status(404).json({ error: 'user not found' });
53
54 try {
55 const session = await stripe.checkout.sessions.create({
56 mode: 'subscription',
57 line_items: [{ price: plan.stripePriceId, quantity: 1 }],
58 customer_email: u.email || undefined,
59 metadata: { username: u.username, planId: plan.id },
60 success_url: `${PUBLIC_URL()}/billing?session_id={CHECKOUT_SESSION_ID}&success=1`,
61 cancel_url: `${PUBLIC_URL()}/billing?canceled=1`,
62 subscription_data: { metadata: { username: u.username, planId: plan.id } },
63 });
64 res.json({ url: session.url });
65 } catch (e) {
66 res.status(500).json({ error: e.message });
67 }
68});
69
70// ── POST /api/billing/portal ────────────────────────────────────────────────
71router.post('/portal', async (req, res) => {
72 if (!req.session?.user) return res.status(401).json({ error: 'auth required' });
73 const stripe = getStripe();
74 if (!stripe) return res.status(503).json({ error: 'Stripe not configured' });
75
76 const u = users.findUser(req.session.user.sub);
77 if (!u?.stripeCustomerId) return res.status(400).json({ error: 'no Stripe customer linked — subscribe first' });
78
79 try {
80 const session = await stripe.billingPortal.sessions.create({
81 customer: u.stripeCustomerId,
82 return_url: `${PUBLIC_URL()}/billing`,
83 });
84 res.json({ url: session.url });
85 } catch (e) {
86 res.status(500).json({ error: e.message });
87 }
88});
89
90// ── POST /api/billing/webhook ───────────────────────────────────────────────
91// The raw body handler is exported separately and mounted BEFORE express.json()
92// in index.js. The route below is a no-op placeholder so the router is consistent.
93router.post('/webhook', (req, res) => res.sendStatus(200));
94
95async function handleStripeEvent(event) {
96 const stripe = getStripe();
97
98 if (event.type === 'checkout.session.completed') {
99 const session = event.data.object;
100 const username = session.metadata?.username;
101 const planId = session.metadata?.planId;
102 if (!username || !planId) return;
103
104 const subId = session.subscription;
105 const sub = subId ? await stripe.subscriptions.retrieve(subId) : null;
106
107 users.updateUserPlan(username, {
108 plan: planId,
109 stripeCustomerId: session.customer,
110 stripeSubscriptionId: subId || '',
111 subscriptionStatus: sub?.status || 'active',
112 planExpiresAt: sub?.current_period_end
113 ? new Date(sub.current_period_end * 1000).toISOString()
114 : null,
115 });
116
117 const u = users.findUser(username);
118 if (u?.email) {
119 await sendUpgradeConfirmation({ to: u.email, name: u.name, plan: getPlan(planId).name }).catch(() => {});
120 }
121 console.log(`[billing] ${username} upgraded to ${planId}`);
122 }
123
124 if (event.type === 'customer.subscription.updated') {
125 const sub = event.data.object;
126 const username = sub.metadata?.username;
127 if (!username) return;
128 const planId = getPlanIdByStripePrice(sub.items?.data?.[0]?.price?.id);
129 users.updateUserPlan(username, {
130 plan: planId || 'free',
131 subscriptionStatus: sub.status,
132 planExpiresAt: new Date(sub.current_period_end * 1000).toISOString(),
133 });
134 }
135
136 if (event.type === 'customer.subscription.deleted') {
137 const sub = event.data.object;
138 const username = sub.metadata?.username;
139 if (!username) return;
140 users.updateUserPlan(username, {
141 plan: 'free',
142 subscriptionStatus: 'canceled',
143 planExpiresAt: null,
144 });
145 console.log(`[billing] ${username} subscription canceled → free`);
146 }
147}
148
149function getPlanIdByStripePrice(priceId) {
150 if (!priceId) return null;
151 const { PLANS } = require('../lib/plans');
152 return Object.values(PLANS).find(p => p.stripePriceId === priceId)?.id || null;
153}
154
155// Standalone webhook handler — mounted before express.json() in index.js
156async function webhookHandler(req, res) {
157 const stripe = getStripe();
158 if (!stripe) return res.sendStatus(200);
159
160 const sig = req.headers['stripe-signature'];
161 const secret = process.env.STRIPE_WEBHOOK_SECRET;
162
163 let event;
164 try {
165 event = secret
166 ? stripe.webhooks.constructEvent(req.body, sig, secret)
167 : JSON.parse(req.body.toString());
168 } catch (e) {
169 return res.status(400).send(`Webhook error: ${e.message}`);
170 }
171
172 try { await handleStripeEvent(event); }
173 catch (e) { console.error('[billing webhook]', e.message); }
174
175 res.sendStatus(200);
176}
177
178module.exports = router;
179module.exports.webhookHandler = webhookHandler;