Add Stripe billing integration + update free tier to 100 PDFs/mo

This commit is contained in:
DocFast Bot 2026-02-14 13:53:19 +00:00
parent facb8df8f4
commit c12c1176b0
7 changed files with 238 additions and 12 deletions

182
src/routes/billing.ts Normal file
View file

@ -0,0 +1,182 @@
import { Router, Request, Response } from "express";
import Stripe from "stripe";
import { nanoid } from "nanoid";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
apiVersion: "2025-01-27.acacia" as any,
});
const router = Router();
// In-memory store of customer → API key mappings
// In production, this would be a database
const customerKeys = new Map<string, string>();
// Create a Stripe Checkout session for Pro subscription
router.post("/checkout", async (_req: Request, res: Response) => {
try {
// Find or create the Pro plan product+price
const priceId = await getOrCreateProPrice();
const session = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.BASE_URL || "https://docfast.dev"}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.BASE_URL || "https://docfast.dev"}/pricing`,
});
res.json({ url: session.url });
} catch (err: any) {
console.error("Checkout error:", err.message);
res.status(500).json({ error: "Failed to create checkout session" });
}
});
// Success page — retrieve API key after checkout
router.get("/success", async (req: Request, res: Response) => {
const sessionId = req.query.session_id as string;
if (!sessionId) {
res.status(400).json({ error: "Missing session_id" });
return;
}
try {
const session = await stripe.checkout.sessions.retrieve(sessionId);
const customerId = session.customer as string;
if (!customerId) {
res.status(400).json({ error: "No customer found" });
return;
}
// Generate or retrieve API key for this customer
let apiKey = customerKeys.get(customerId);
if (!apiKey) {
apiKey = `df_pro_${nanoid(32)}`;
customerKeys.set(customerId, apiKey);
// Add to PRO_KEYS runtime set
addProKey(apiKey);
}
res.json({
message: "Welcome to DocFast Pro! 🎉",
apiKey,
docs: "/api",
note: "Save this API key — it won't be shown again.",
});
} catch (err: any) {
console.error("Success page error:", err.message);
res.status(500).json({ error: "Failed to retrieve session" });
}
});
// Stripe webhook for subscription lifecycle events
router.post(
"/webhook",
// Raw body needed for signature verification
async (req: Request, res: Response) => {
const sig = req.headers["stripe-signature"] as string;
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
let event: Stripe.Event;
if (webhookSecret && sig) {
try {
event = stripe.webhooks.constructEvent(
req.body,
sig,
webhookSecret
);
} catch (err: any) {
console.error("Webhook signature verification failed:", err.message);
res.status(400).json({ error: "Invalid signature" });
return;
}
} else {
// No webhook secret configured — accept all events (dev mode)
event = req.body as Stripe.Event;
}
switch (event.type) {
case "customer.subscription.deleted": {
const sub = event.data.object as Stripe.Subscription;
const customerId = sub.customer as string;
const key = customerKeys.get(customerId);
if (key) {
removeProKey(key);
customerKeys.delete(customerId);
console.log(`Subscription cancelled for ${customerId}, key revoked`);
}
break;
}
default:
// Ignore other events
break;
}
res.json({ received: true });
}
);
// --- Pro key management ---
// These integrate with the usage middleware's PRO_KEYS set
const runtimeProKeys = new Set<string>();
export function addProKey(key: string): void {
runtimeProKeys.add(key);
}
export function removeProKey(key: string): void {
runtimeProKeys.delete(key);
}
export function isProKey(key: string): boolean {
return runtimeProKeys.has(key);
}
// --- Price management ---
let cachedPriceId: string | null = null;
async function getOrCreateProPrice(): Promise<string> {
if (cachedPriceId) return cachedPriceId;
// Search for existing product
const products = await stripe.products.search({
query: "name:'DocFast Pro'",
});
let productId: string;
if (products.data.length > 0) {
productId = products.data[0].id;
// Find active price
const prices = await stripe.prices.list({
product: productId,
active: true,
limit: 1,
});
if (prices.data.length > 0) {
cachedPriceId = prices.data[0].id;
return cachedPriceId;
}
} else {
const product = await stripe.products.create({
name: "DocFast Pro",
description: "Unlimited PDF conversions via API. HTML, Markdown, and URL to PDF.",
});
productId = product.id;
}
const price = await stripe.prices.create({
product: productId,
unit_amount: 900, // $9.00
currency: "usd",
recurring: { interval: "month" },
});
cachedPriceId = price.id;
return cachedPriceId;
}
export { router as billingRouter };