Add subscription support + license extension on renewal
This commit is contained in:
+174
-15
@@ -2,8 +2,13 @@ import express from 'express';
|
||||
import { config } from './config.js';
|
||||
import { getPlan, listPlans, PREMIUM_FEATURES } from './plans.js';
|
||||
import { getStripe } from './stripe.js';
|
||||
import { getStoreSnapshot, upsertCustomer, upsertSubscription } from './store.js';
|
||||
import { syncLicenseFromSubscription, validateLicense, deactivateLicense } from './licenseLogic.js';
|
||||
import { getStoreSnapshot, upsertCustomer, upsertSubscription, findLicenseByCustomerId } from './store.js';
|
||||
import {
|
||||
syncLicenseFromSubscription,
|
||||
grantOneTimeLicense,
|
||||
validateLicense,
|
||||
deactivateLicense
|
||||
} from './licenseLogic.js';
|
||||
|
||||
const app = express();
|
||||
app.use('/api/stripe/webhook', express.raw({ type: 'application/json' }));
|
||||
@@ -14,7 +19,11 @@ app.get('/health', (_req, res) => {
|
||||
});
|
||||
|
||||
app.get('/api/public/config', (_req, res) => {
|
||||
res.json({ ok: true, publishableKeyPresent: Boolean(config.stripePublishableKey), websiteUrl: config.websiteUrl });
|
||||
res.json({
|
||||
ok: true,
|
||||
publishableKey: config.stripePublishableKey || null,
|
||||
websiteUrl: config.websiteUrl
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/public/plans', (_req, res) => {
|
||||
@@ -25,7 +34,12 @@ app.get('/api/admin/debug/store', (_req, res) => {
|
||||
res.json({ ok: true, store: getStoreSnapshot() });
|
||||
});
|
||||
|
||||
app.post('/api/checkout/session', async (req, res) => {
|
||||
/**
|
||||
* Subscription checkout. Customer subscribes and is auto-renewed on the
|
||||
* plan's interval. The license is created on the first webhook event and
|
||||
* extended on every renewal.
|
||||
*/
|
||||
app.post('/api/checkout/subscription', async (req, res) => {
|
||||
try {
|
||||
const { planCode, customerEmail } = req.body || {};
|
||||
const plan = getPlan(planCode);
|
||||
@@ -44,22 +58,113 @@ app.post('/api/checkout/session', async (req, res) => {
|
||||
},
|
||||
quantity: 1
|
||||
}],
|
||||
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
|
||||
cancel_url: `${config.websiteUrl}/pricing`,
|
||||
allow_promotion_codes: true,
|
||||
billing_address_collection: 'required',
|
||||
customer_email: customerEmail || undefined,
|
||||
metadata: { source: 'dashcaddy.net', planCode: plan.code, tier: plan.tier },
|
||||
subscription_data: { metadata: { source: 'dashcaddy.net', planCode: plan.code, tier: plan.tier } }
|
||||
metadata: {
|
||||
source: 'dashcaddy.net',
|
||||
planCode: plan.code,
|
||||
tier: plan.tier,
|
||||
mode: 'subscription',
|
||||
// Bake the email into session metadata so the webhook can find
|
||||
// the existing license without a Stripe API call.
|
||||
customerEmail: customerEmail || ''
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
source: 'dashcaddy.net',
|
||||
planCode: plan.code,
|
||||
tier: plan.tier,
|
||||
customerEmail: customerEmail || ''
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return res.json({ ok: true, url: session.url, sessionId: session.id });
|
||||
} catch (error) {
|
||||
console.error('Checkout session error:', error);
|
||||
console.error('Subscription checkout error:', error);
|
||||
return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* One-time purchase checkout. Customer pays once for a license of the
|
||||
* plan duration. If they buy again, time is added to their existing license.
|
||||
*/
|
||||
app.post('/api/checkout/one-time', async (req, res) => {
|
||||
try {
|
||||
const { planCode, customerEmail } = req.body || {};
|
||||
const plan = getPlan(planCode);
|
||||
if (!plan) return res.status(400).json({ ok: false, error: 'Invalid planCode' });
|
||||
|
||||
const stripe = getStripe();
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: 'payment',
|
||||
payment_method_types: ['card'],
|
||||
line_items: [{
|
||||
price_data: {
|
||||
currency: 'usd',
|
||||
product_data: { name: plan.label, description: 'DashCaddy Premium one-time license' },
|
||||
unit_amount: plan.amountUsd * 100
|
||||
},
|
||||
quantity: 1
|
||||
}],
|
||||
success_url: `${config.websiteUrl}/success?session_id={CHECKOUT_SESSION_ID}&tier=premium`,
|
||||
cancel_url: `${config.websiteUrl}/pricing`,
|
||||
allow_promotion_codes: true,
|
||||
billing_address_collection: 'required',
|
||||
customer_email: customerEmail || undefined,
|
||||
metadata: {
|
||||
source: 'dashcaddy.net',
|
||||
planCode: plan.code,
|
||||
tier: plan.tier,
|
||||
mode: 'one-time',
|
||||
durationDays: String(plan.durationDays),
|
||||
customerEmail: customerEmail || ''
|
||||
},
|
||||
payment_intent_data: {
|
||||
metadata: {
|
||||
source: 'dashcaddy.net',
|
||||
planCode: plan.code,
|
||||
tier: plan.tier,
|
||||
mode: 'one-time',
|
||||
durationDays: String(plan.durationDays),
|
||||
customerEmail: customerEmail || ''
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return res.json({ ok: true, url: session.url, sessionId: session.id });
|
||||
} catch (error) {
|
||||
console.error('One-time checkout error:', error);
|
||||
return res.status(500).json({ ok: false, error: error.message || 'Checkout failed' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Look up an existing license for a customer. Tries customerId first,
|
||||
* then falls back to email. Returns null if no active license exists.
|
||||
*/
|
||||
function findCustomersLicense(customerId, customerEmail) {
|
||||
if (customerId) {
|
||||
const byCustomer = findLicenseByCustomerId(customerId);
|
||||
if (byCustomer) return byCustomer;
|
||||
}
|
||||
if (customerEmail) {
|
||||
const { findActiveLicenseByCustomerEmail } = require('./store.js');
|
||||
const byEmail = findActiveLicenseByCustomerEmail(customerEmail);
|
||||
if (byEmail) return byEmail;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe webhook endpoint. Handles subscription lifecycle events AND
|
||||
* one-time payment completion events. The same handler routes based on
|
||||
* event type and updates the customer's license accordingly.
|
||||
*/
|
||||
app.post('/api/stripe/webhook', async (req, res) => {
|
||||
try {
|
||||
if (!config.stripeWebhookSecret) {
|
||||
@@ -77,19 +182,54 @@ app.post('/api/stripe/webhook', async (req, res) => {
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object;
|
||||
if (session.customer) {
|
||||
upsertCustomer({ id: String(session.customer), email: session.customer_email || null, checkoutSessionId: session.id });
|
||||
const planCode = session.metadata?.planCode;
|
||||
const mode = session.metadata?.mode || 'subscription';
|
||||
const customerId = typeof session.customer === 'string' ? session.customer : session.customer?.id;
|
||||
// Email resolution: session metadata (baked at creation) > session.customer_email > session.customer_details.email
|
||||
const customerEmail = session.metadata?.customerEmail || session.customer_email || session.customer_details?.email || null;
|
||||
|
||||
if (customerId) {
|
||||
upsertCustomer({ id: String(customerId), email: customerEmail, checkoutSessionId: session.id });
|
||||
}
|
||||
|
||||
// For one-time payments, generate the license on checkout.session.completed
|
||||
if (mode === 'one-time' && planCode) {
|
||||
const plan = getPlan(planCode);
|
||||
if (plan) {
|
||||
const license = grantOneTimeLicense({
|
||||
paymentIntentId: typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent?.id,
|
||||
customerId,
|
||||
customerEmail,
|
||||
planCode,
|
||||
durationDays: plan.durationDays
|
||||
});
|
||||
console.log('One-time license granted', {
|
||||
sessionId: session.id,
|
||||
licenseKey: license.key,
|
||||
customerEmail,
|
||||
extended: license.extended || false,
|
||||
addedDays: license.addedDays || plan.durationDays
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.created':
|
||||
case 'customer.subscription.updated':
|
||||
case 'customer.subscription.deleted': {
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object;
|
||||
const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer?.id;
|
||||
const customerEmail = subscription.customer_email || null;
|
||||
const planCode = subscription.metadata?.planCode || 'premium_1m';
|
||||
// Email resolution: subscription metadata (baked at creation) > fetch from Stripe if missing
|
||||
let customerEmail = subscription.metadata?.customerEmail || null;
|
||||
if (!customerEmail && customerId) {
|
||||
try {
|
||||
const customer = await stripe.customers.retrieve(customerId);
|
||||
customerEmail = customer.email || null;
|
||||
} catch (err) {
|
||||
console.warn('Failed to fetch customer email', { customerId, error: err.message });
|
||||
}
|
||||
}
|
||||
const planCode = subscription.metadata?.planCode || 'premium_30d';
|
||||
const currentPeriodEnd = subscription.current_period_end
|
||||
? new Date(subscription.current_period_end * 1000).toISOString()
|
||||
: null;
|
||||
@@ -112,7 +252,26 @@ app.post('/api/stripe/webhook', async (req, res) => {
|
||||
currentPeriodEnd
|
||||
});
|
||||
|
||||
console.log('License synced from subscription', { subscriptionId: subscription.id, licenseKey: license.key, status: license.status });
|
||||
console.log('Subscription license synced', {
|
||||
subscriptionId: subscription.id,
|
||||
licenseKey: license.key,
|
||||
status: license.status,
|
||||
expiresAt: license.expiresAt,
|
||||
customerEmail
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.deleted': {
|
||||
const subscription = event.data.object;
|
||||
// Mark the subscription cancelled. License remains active until
|
||||
// currentPeriodEnd (Stripe handles non-renewal automatically).
|
||||
upsertSubscription({
|
||||
id: subscription.id,
|
||||
status: 'canceled',
|
||||
cancelAtPeriodEnd: true
|
||||
});
|
||||
console.log('Subscription cancelled', { subscriptionId: subscription.id });
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user