🎨 Vibe Coding Kit

Build a Stripe-Like Payment System (The Right Way™)

⚠️ Reality Check: Before You Build

Building a payment processor from scratch is dangerous. Here's why:

  • PCI DSS Compliance: You need Level 1 compliance (~$100K+ annually). Not a joke.
  • Security Risk: One bug = customer card data breaches = lawsuits + fines
  • Legal Liability: You become liable for fraud, chargebacks, and regulations (FCA, FinCEN, etc.)
  • Fraud Prevention: Building ML models for fraud detection takes months
  • Regulatory Burden: Banking regulations differ by country. You can't ignore them.

✅ When Building Makes Sense

That said, some use cases justify custom billing:

  • Internal Billing: Self-hosted for internal teams (no PCI burden on customers)
  • Crypto Payments: Blockchain-based, no credit card PCI needed
  • Non-Card Payments: ACH, bank transfers, specific regional methods
  • Complex Usage Billing: When Stripe's model doesn't fit (multi-dimensional usage)
  • Multi-Tenant Billing: SaaS with extreme customization needs

⚙️ If You Must Build - Tech Stack

DO NOT replace Stripe for card processing. Use Stripe for payments. Build the billing layer on top.

🏗️ Framework Next.js (App Router) + TypeScript
🗄️ Database PostgreSQL + Prisma ORM
💳 Payment Processing Stripe API (Payments + Webhooks)
🔐 Auth NextAuth.js or Auth0
📧 Email Resend + React Email
🔔 Events Bull + Redis (for job processing)
📊 Analytics PostHog or Mixpanel
🚀 Deployment Vercel (frontend) + Railway/Render (backend)

What You're Actually Building

  • Subscription Management: Plans, cycles, upgrades/downgrades
  • Billing Portal: Self-serve customer dashboard
  • Usage Tracking: Metered billing events from your app
  • Invoice Generation: PDFs with your branding
  • Webhook Handling: Sync Stripe events to your database
  • Dunning/Retry Logic: Failed payment recovery (critical for revenue)
  • Multi-Currency Support: Handle different regions

📋 Production-Ready Prompt

Use this to build a billing/subscription system on top of Stripe:

You are building a production-grade billing and subscription management system for a SaaS platform. This system sits on TOP of Stripe (you do not replace Stripe), handling business logic, user experience, and custom billing workflows. CORE RESPONSIBILITIES: 1. Subscription Management - Create, update, cancel subscriptions tied to Stripe subscription objects - Handle plan changes (upgrades/downgrades, prorations) - Track billing cycles, renewal dates, and trial periods - Support annual, monthly, and custom billing intervals 2. Usage-Based Billing - Accept metered usage events from your application - Aggregate usage per billing cycle - Sync aggregated usage to Stripe for prorated charges - Support tiered pricing (e.g., $0.10 per unit for first 1000, $0.08 after) - Real-time usage dashboards for customers 3. Customer Billing Portal - Self-serve dashboard showing current plan, usage, and costs - Ability to upgrade/downgrade plans - Manage payment methods - View invoice history and download PDFs - Usage breakdown by feature/dimension - Billing settings (email, tax ID, address) 4. Invoice & Billing Management - Generate branded invoices (PDF with company logo, terms, tax info) - Send invoice emails automatically after payment success - Custom invoice numbering and metadata - Support tax rates/GST/VAT (country-specific) - Partial refunds and credit memos - Line-item detail matching customer's actual usage 5. Webhook Handling & Sync - Listen to Stripe webhooks: invoice.payment_succeeded, invoice.payment_failed, customer.subscription.deleted, charge.refunded - Update local database to reflect Stripe state (invoice status, subscription status) - Handle race conditions (webhook arrives before API call returns) - Retry failed webhook processing with exponential backoff - Webhook signature verification (Stripe-Signature header) 6. Dunning & Failed Payment Recovery - Track payment failures and retry attempts - Send reminder emails after failed payment (Day 1, Day 4, Day 7) - Auto-retry failed payments using Stripe's retry rules - Pause/downgrade service gracefully if dunning exhausted - Offer payment method update flow before service suspension - Log all dunning actions for troubleshooting 7. Reporting & Analytics - MRR (Monthly Recurring Revenue) by plan/customer - Churn rate and reasons (voluntary, payment failure, etc.) - LTV (Lifetime Value) calculation - Expansion revenue (upgrades, additional products) - Customer segmentation (by plan, usage, region) - Cohort analysis for retention TECH STACK: - Framework: Next.js with App Router (TypeScript) - Database: PostgreSQL with Prisma ORM - Payment Processor: Stripe API (Python SDK or Node SDK) - Job Queue: Bull (Redis backend) for async tasks - Auth: NextAuth.js for customer accounts - Email: Resend for transactional emails - API: RESTful endpoints at /api/billing/* DATABASE SCHEMA (Prisma): ``` model Customer { id String @id @default(cuid()) userId String @unique stripeCustomerId String @unique email String name String createdAt DateTime @default(now()) subscriptions Subscription[] invoices Invoice[] usageEvents UsageEvent[] } model Subscription { id String @id @default(cuid()) customerId String customer Customer @relation(fields: [customerId], references: [id]) stripeSubscriptionId String @unique planId String status String // active, past_due, canceled, unpaid currentPeriodStart DateTime currentPeriodEnd DateTime canceledAt DateTime? trialEndsAt DateTime? createdAt DateTime @default(now()) invoices Invoice[] } model Invoice { id String @id @default(cuid()) customerId String customer Customer @relation(fields: [customerId], references: [id]) stripeInvoiceId String @unique subscriptionId String subscription Subscription @relation(fields: [subscriptionId], references: [id]) status String // draft, open, paid, void, uncollectible amount Int currency String paidAt DateTime? failedAt DateTime? dueDate DateTime createdAt DateTime @default(now()) } model UsageEvent { id String @id @default(cuid()) customerId String customer Customer @relation(fields: [customerId], references: [id]) dimension String // "seats", "requests", "storage_gb" quantity Float timestamp DateTime @default(now()) @@index([customerId, dimension, timestamp]) } ``` KEY ENDPOINTS: - POST /api/billing/subscriptions - Create subscription (after Stripe charges succeeds) - GET /api/billing/subscriptions/:id - Get subscription details - POST /api/billing/subscriptions/:id/upgrade - Change plan - POST /api/billing/subscriptions/:id/cancel - Cancel subscription - POST /api/billing/usage - Track usage event (internal API) - GET /api/billing/invoices - List invoices for customer - GET /api/billing/portal-session - Generate Stripe Billing Portal link - POST /api/billing/webhooks/stripe - Stripe webhook receiver WEBHOOK PROCESSING: - Validate Stripe signature on every webhook - Parse event type and data - Atomically update database (subscription status, invoice state, etc.) - Send confirmation emails (invoice paid, subscription canceled, etc.) - Log all events for audit trail - Return 200 immediately; do heavy lifting asynchronously with Bull jobs DUNNING WORKFLOW: 1. Invoice payment fails → Set invoice.status = "open" 2. Wait 1 day → Send first reminder email 3. Day 4: Auto-retry via Stripe 4. If still failed: Send second reminder + payment method update link 5. Day 7: Final notice + offer to downgrade/pause 6. Day 10: Suspend service/downgrade plan ERROR HANDLING: - Catch Stripe API errors (rate limits, invalid params, auth failures) - Log errors with context (customer ID, subscription ID, attempted action) - Retry transient failures (network timeouts, 500s) with exponential backoff - Alert on critical failures (webhook processing errors, sync issues) - Provide clear error messages to users (e.g., "Payment method declined. Update here.") TESTING: - Unit tests for business logic (proration math, dunning rules, usage aggregation) - Integration tests against Stripe test mode - End-to-end tests for subscription lifecycle (create → upgrade → cancel) - Webhook testing using Stripe CLI - Load testing for metered event ingestion (simulate high-volume customers) This system will be production-ready, scalable to thousands of customers, and fully compliant with Stripe's best practices. Focus on data consistency, error resilience, and delightful customer experience.

📅 4-Week Build Timeline

Week 1: Foundation & Core Models

  • Set up Next.js + Prisma + PostgreSQL
  • Design database schema (Customer, Subscription, Invoice, UsageEvent)
  • Set up Stripe test mode account & API keys
  • Implement authentication (NextAuth.js)
  • Create /api/billing/* folder structure
  • Write database seed script for test data

Week 2: Stripe Integration & Webhooks

  • Implement POST /api/billing/subscriptions (create subscription after Stripe charge)
  • Set up Stripe webhook listener at /api/billing/webhooks/stripe
  • Implement webhook signature verification
  • Handle key webhook events (invoice.payment_succeeded, subscription.deleted)
  • Build webhook retry/queue logic with Bull + Redis
  • Log all webhook events for debugging
  • Test end-to-end: Create Stripe checkout → receive webhook → create subscription

Week 3: Billing Portal & Self-Service

  • Build customer dashboard (current plan, renewal date, usage)
  • Implement plan upgrade/downgrade logic with proration
  • Add cancel subscription endpoint with confirmation emails
  • Integrate Stripe Billing Portal (generate portal session link)
  • Build usage tracking endpoint (POST /api/billing/usage)
  • Create usage visualization (charts, graphs)
  • Add invoice listing and PDF download
  • Test multi-plan scenarios (free → pro → enterprise)

Week 4: Dunning, Email, & Polish

  • Implement dunning workflow (failed payment retry, email reminders)
  • Set up Resend for transactional emails
  • Build email templates (invoice paid, subscription renewed, payment failed)
  • Add payment method update flow
  • Implement analytics (MRR, churn, LTV calculations)
  • Write comprehensive error handling & logging
  • Load test usage event ingestion
  • Deploy to production (Vercel + Railway)
  • Final security audit (PCI considerations, data encryption)

🔓 Open Source Alternatives (Consider First)

Before building from scratch, evaluate these battle-tested solutions:

🌊 Lago

Best for: Usage-based billing, metered subscriptions, SaaS

Open-source billing platform for complex, usage-based pricing. Handles meter aggregation, invoicing, and integration with payment processors.

  • • Metered billing native
  • • Pricing engine
  • • API-first
  • • Stripe integration
→ github.com/getlago/lago

⚔️ Kill Bill

Best for: Enterprise subscriptions, complex workflows

Mature open-source subscription & billing platform. Handles subscriptions, invoicing, dunning, and payments. Java-based, battle-tested.

  • • Enterprise features
  • • Multi-tenant
  • • Plugin system
  • • Robust dunning
→ killbill.io

🌺 Lotus

Best for: Pricing pages, plan management, experimentation

Open-source pricing & packaging engine. Helps design and test pricing models before building billing infrastructure.

  • • Pricing pages
  • • A/B testing
  • • Plan templates
  • • Customer segmentation
→ github.com/uselotus/lotus

✨ When Custom Billing Makes Sense

🎯 Complex Usage-Based Pricing

Your pricing depends on multiple dimensions (seats × storage × compute hours). Off-the-shelf solutions don't fit your model. You need custom aggregation logic.

🏢 Multi-Tenant Billing

You're a platform (Shopify, Zapier-style). Each tenant has their own customers and billing structure. You need white-label invoicing and per-tenant customization.

⚙️ Specific Compliance Needs

Your region/industry has unique requirements (GST India, SEPA Europe, specific audit trails). You need full control over data flow.

🔗 Deep Integration

Billing is core to your product (e.g., marketplace takes commission, on-demand resource billing). You need real-time sync with operational metrics.

🌍 Cryptocurrency Payments

You accept stablecoins, crypto, or custom blockchain transactions. Card payments via Stripe aren't your primary flow.

🔐 Data Sovereignty

Regulations (GDPR, HIPAA) require customer billing data on self-hosted infrastructure. You can't use cloud billing providers.

✅ Pre-Build Checklist

  • Have you considered using Stripe Billing directly? (It handles subscriptions + invoicing)
  • Did you evaluate Lago, Kill Bill, or other open-source solutions?
  • Do you have budget for security audit + ongoing PCI compliance?
  • Have you consulted with your legal/compliance team about liability?
  • Can you dedicate 2+ engineers for 4+ weeks to build this right?
  • Do you have a plan for payment reconciliation & fraud detection?
  • Will you use Stripe for actual card processing (not building your own payment processor)?
  • Can you handle webhook delivery at scale (100s/second during peak)?
  • Do you have monitoring, alerting, and on-call rotation planned?
  • Will invoices + dunning emails be legally reviewed before launch?

Pro Tip: Start with Stripe Billing + Stripe Invoicing. Only build custom if those don't fit your needs. 80% of SaaS companies never need to build custom billing.