๐Ÿ’ณ

Stripe Payment System

Complete technical guide to secure payment processing and subscription management

๐Ÿ“… Published on November 21, 2025

๐Ÿค What is Stripe Integration?

A Stripe Payment System is a comprehensive payment infrastructure that handles subscription billing, webhook processing, and database synchronization. It creates a seamless bridge between payment processing and application access control.

Payment Formula: Stripe API + Webhooks + Database Sync + Access Control = Complete SaaS Billing

โš—๏ธ Why Choose Stripe?

๐Ÿ”’

Enterprise Security

PCI DSS Level 1 certified infrastructure

๐ŸŒ

Global Reach

Support for 135+ currencies and payment methods

โš™๏ธ

Developer Experience

Comprehensive APIs and webhook system

๐Ÿ“Š

Analytics & Reporting

Real-time payment analytics and insights

๐Ÿง Technical Architecture

Core Technology Stack

  • Payment Processor: Stripe API v3
  • Webhooks: Real-time event processing
  • Database: MySQL with transaction safety
  • Authentication: NextAuth.js integration
  • Frontend: React components with Stripe Elements
  • Security: Environment-based configuration

๐Ÿ“Š Payment Flow Architecture

User Selects Plan
โ†“
Stripe Checkout Session
โ†“
Payment Processing
โ†“
Webhook Event Triggered
โ†“
Database Update
โ†“
Access Control Applied

๐Ÿ’ฐ Subscription Models

๐ŸŽ†

Free Tier

Credits: 2 stock analyses

Duration: Permanent access

Features: Basic portfolio analysis

// Free tier initialization const freeTierAccess = { maxAnalyses: 2, hasAccess: true, subscriptionType: 'free' }
๐Ÿ“‹

Quantity Subscriptions

Model: Credit-based recurring billing

Plans: 5, 10, 20, 50, 100 analyses/month

Billing: Monthly or yearly cycles

// Quantity subscription structure const quantityPriceMap = { 'price_monthly_5': 5, 'price_monthly_10': 10, 'price_yearly_20': 20 * 12 }
โš™๏ธ

Dynamic Pricing

Strategy: Volume-based degressive pricing

Discounts: Yearly plans (12x monthly)

Flexibility: Upgrade/downgrade anytime

// Price calculation logic const calculatePrice = (quantity, isYearly) => { const basePrice = getBasePrice(quantity) return isYearly ? basePrice * 10 : basePrice }

๐Ÿ”„ Webhook System

๐Ÿ“ก Critical Webhook Events

invoice.paid

Handles both new subscriptions and renewals

case 'invoice.paid': { const invoice = data.object const subscriptionId = invoice.subscription // Add credits to user account await updateUserCredits(userId, addedQuantity) // Grant access await grantAccess(userId) }

customer.subscription.deleted

Manages subscription cancellations and access revocation

case 'customer.subscription.deleted': { // Check remaining credits const remainingCredits = await getRemainingCredits(userId) if (remainingCredits === 0) { await revokeAccess(userId) } }

invoice.payment_failed

Handles failed payments and retry logic

case 'invoice.payment_failed': { await updateSubscriptionStatus(subscriptionId, 'past_due') // Notify user via email await sendPaymentFailureNotification(userEmail) }

๐Ÿ—„๏ธ Database Integration

๐Ÿ“Š Database Schema Overview

Core Tables Architecture

// User Management users: { id, email, name, stripeCustomerId, hasAccess, created_at, updated_at } // Subscription Tracking subscriptions: { id, userId, customerId, status, priceId, quantity, currentPeriodStart, currentPeriodEnd } // Access Control service_access: { userId, resourceId, status, start_date, end_date }

Key Relationships

The database maintains referential integrity through foreign key constraints linking users to their subscriptions and access permissions. Each subscription tracks credit usage and billing periods, while access control tables manage feature-specific permissions.

Data Flow Pattern

Webhook โ†’ Database Update โ†’ Access Calculation โ†’ User Experience

Stripe events trigger database updates that immediately recalculate user access permissions, ensuring real-time synchronization between payment status and application features.

๐Ÿšซ Access Restrictions

๐ŸŽฏ Access Control Logic

1

Credit Verification

System checks available credits before allowing stock analysis

const remainingCredits = await connection.execute( 'SELECT SUM(GREATEST(quantity - COALESCE(quantityused,0), 0)) as credits FROM subscriptions WHERE userId = ? AND type = "Quantity"', [userId] )
2

Active Stock Tracking

Monitor stocks with active analysis periods

const activeStocks = await connection.execute( 'SELECT COUNT(*) as count FROM quantity_subscription_stocks WHERE userId = ? AND status = "online" AND (end_date IS NULL OR end_date > NOW())', [userId] )
3

Access Decision Matrix

  • Has Credits OR Active Stocks: โœ… Grant Access
  • No Credits AND No Active Stocks: โŒ Deny Access
  • Free Tier (2 analyses): โœ… Always Grant Access
  • Subscription Canceled: Check remaining resources

๐Ÿ“ Restriction Examples

๐ŸŽ† Free User

Scenario: User with no subscription

Access: 2 stock analyses maximum

Restriction: Cannot add more stocks after limit

๐Ÿ’ณ Premium User

Scenario: Active subscription with 15 credits

Access: Can analyze stocks until credits depleted

Tracking: Credits decremented per analysis

โŒ Canceled User

Scenario: Subscription canceled, 5 active stocks, 0 credits

Access: Retains access due to active stock periods

Future: Access revoked when all stocks expire

๐Ÿ”’ Security Measures

๐Ÿ”

Webhook Verification

Cryptographic signature validation for all webhook events

๐ŸŒ

Environment Isolation

Separate test and production Stripe keys and endpoints

๐Ÿ“‹

Transaction Logging

Comprehensive audit trail for all payment events

โšก

Idempotency

Duplicate event protection and safe retry mechanisms

๐Ÿ”ง Security Implementation

Webhook Signature Verification

// Verify webhook authenticity const signature = headers().get('stripe-signature') const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET try { event = stripe.webhooks.constructEvent( rawBody, signature, webhookSecret ) } catch (err) { return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) }

Database Transaction Safety

// Atomic database operations const connection = await mysql.createConnection(config) try { await connection.beginTransaction() await connection.execute(updateQuery, params) await connection.execute(logQuery, logParams) await connection.commit() } catch (error) { await connection.rollback() throw error } finally { await connection.end() }

๐Ÿงช Testing Guide

๐Ÿ’ป Local Development Testing

1

Environment Configuration

# Environment variables setup STRIPE_SECRET_KEY=sk_test_[your_test_key] STRIPE_WEBHOOK_SECRET=whsec_[webhook_secret] STRIPE_PUBLISHABLE_KEY=pk_test_[your_public_key] # Configure test price identifiers PRICE_ID_MONTHLY=price_test_[monthly_id] PRICE_ID_YEARLY=price_test_[yearly_id]
2

Development Server

npm run dev

Start your development environment with proper environment variables loaded

3

Webhook Testing

stripe listen --forward-to localhost:PORT/api/webhooks/stripe

Configure webhook forwarding to your local webhook endpoint

4

Payment Flow Testing

  1. Navigate to your pricing page
  2. Select a subscription tier
  3. Use Stripe test cards (e.g., 4242 4242 4242 4242)
  4. Complete the checkout flow
  5. Monitor webhook events in console
  6. Verify database state changes
5

Access Control Validation

// Verify user access logic const userAccess = await checkUserAccess(userId) const remainingCredits = await getCreditBalance(userId) const activeResources = await getActiveResources(userId) // Test access decision matrix const hasAccess = (remainingCredits > 0) || (activeResources.length > 0)

๐Ÿš€ Pre-Production Verification

โœ… Payment Testing

  • Test all subscription tiers
  • Verify monthly/yearly billing
  • Test payment failures
  • Validate upgrade/downgrade flows

โœ… Webhook Integration

  • Verify signature validation
  • Test all event types
  • Check error handling
  • Validate retry logic

โœ… Database Consistency

  • Verify credit calculations
  • Test access restrictions
  • Check data integrity
  • Validate cleanup processes

โœ… Security Validation

  • Environment variable isolation
  • Webhook endpoint protection
  • User data encryption
  • Access control enforcement

๐ŸŽฏ Conclusion

The Stripe Payment System represents a enterprise-grade billing infrastructure that seamlessly integrates payment processing with application access control. By combining secure webhooks, robust database design, and intelligent access restrictions, it creates a reliable foundation for SaaS subscription management that scales with business growth. ๐Ÿš€๐Ÿ’ณ