SaaS Core/Documentation

Stripe Payment Configuration

This guide provides comprehensive instructions for configuring Stripe payment processing for SaaS Core, including account setup, product configuration, webhook setup, and security considerations.

๐Ÿ’ณ Stripe Account Setup

1. Create Stripe Account

  1. Visit Stripe website
  2. Click "Start now" to create an account
  3. Fill in business information and bank account details
  4. Complete identity verification process

2. Obtain API Keys

Test Environment Keys

  1. Log in to Stripe Dashboard
  2. Ensure "Test mode" is enabled (top left corner)
  3. Click "Developers" โ†’ "API keys" in the top menu
  4. Copy the following keys:
    • Publishable key: pk_test_...
    • Secret key: sk_test_...

Production Environment Keys

  1. Disable "Test mode" in Stripe Dashboard
  2. Repeat the above steps to get production keys:
    • Publishable key: pk_live_...
    • Secret key: sk_live_...

3. Environment Variables Configuration

Add the following configuration to your .env.local file:

# Stripe configuration
STRIPE_SECRET_KEY="sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxx"
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_xxxxxxxxxxxxxxxxxxxxxxxxxx"
STRIPE_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxxxxxxxxxxxxxxx"

# Product price IDs (configure later)
STRIPE_PRO_PRICE_ID="price_xxxxxxxxxxxxxxxxxx"
STRIPE_POINTS_STARTER_PRICE_ID="price_xxxxxxxxxxxxxxxxxx"
STRIPE_POINTS_POPULAR_PRICE_ID="price_xxxxxxxxxxxxxxxxxx"
STRIPE_POINTS_PREMIUM_PRICE_ID="price_xxxxxxxxxxxxxxxxxx"

๐Ÿ›๏ธ Product and Pricing Configuration

1. Create Subscription Products

Professional Plan Subscription

  1. In Stripe Dashboard, click "Products"

  2. Click "Add product"

  3. Fill in product information:

    • Name: Professional Plan
    • Description: SaaS Core Professional Plan Subscription
    • Image: Upload product image (optional)
  4. Configure pricing:

    • Pricing model: Standard pricing
    • Price: $9.99
    • Billing period: Monthly
    • Currency: USD
  5. Click "Save product"

  6. Copy the generated Price ID (format: price_xxxxx)

2. Create Points Purchase Products

Starter Package (5,000 points - $8)

Name: Points Package - Starter
Description: 5,000 points, perfect for new users
Price: $8.00
Type: One-time

Popular Package (10,000 points - $15)

Name: Points Package - Popular
Description: 10,000 points, most popular choice
Price: $15.00
Type: One-time

Premium Package (100,000 points - $150)

Name: Points Package - Premium
Description: 100,000 points, ideal for power users
Price: $150.00
Type: One-time

3. Update Environment Variables

Update the environment variables with the obtained Price IDs:

STRIPE_PRO_PRICE_ID="price_1234567890abcdef"
STRIPE_POINTS_STARTER_PRICE_ID="price_abcdef1234567890"
STRIPE_POINTS_POPULAR_PRICE_ID="price_fedcba0987654321"
STRIPE_POINTS_PREMIUM_PRICE_ID="price_1357924680acefbd"

๐Ÿ”— Webhook Configuration

1. Create Webhook Endpoint

  1. In Stripe Dashboard, click "Developers" โ†’ "Webhooks"
  2. Click "Add endpoint"
  3. Configure Webhook:
    • Endpoint URL: https://yourdomain.com/api/stripe/webhook
    • Description: SaaS Core Webhook

2. Select Events to Listen For

Select the following event types:

Subscription Events

  • customer.subscription.created
  • customer.subscription.updated
  • customer.subscription.deleted
  • invoice.payment_succeeded
  • invoice.payment_failed

Payment Events

  • checkout.session.completed
  • payment_intent.succeeded
  • payment_intent.payment_failed

Customer Events

  • customer.created
  • customer.updated
  • customer.deleted

3. Obtain Webhook Signing Secret

  1. After creating the webhook, click to view its details
  2. In the "Signing secret" section, click "Reveal"
  3. Copy the signing secret (format: whsec_xxxxx)
  4. Update environment variable:
STRIPE_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxxxxxxxxxxxxxxx"

4. Test Webhook

Use Stripe CLI to test webhook functionality:

# Install Stripe CLI
# macOS
brew install stripe/stripe-cli/stripe

# Login
stripe login

# Forward webhooks to local development
stripe listen --forward-to localhost:3000/api/stripe/webhook

# Trigger test events
stripe trigger checkout.session.completed

๐Ÿงช Testing Payment Flow

1. Test Card Numbers

Stripe provides the following test card numbers:

# Successful payments
4242 4242 4242 4242  # Visa
4000 0566 5566 5556  # Visa (debit)
5555 5555 5555 4444  # Mastercard

# Failed payments
4000 0000 0000 0002  # Card declined
4000 0000 0000 9995  # Insufficient funds
4000 0000 0000 9987  # Card lost
4000 0000 0000 9979  # Card stolen

# 3D Secure verification
4000 0027 6000 3184  # Requires verification
4000 0082 6000 3178  # Verification failed

2. Test Information

# Any future date
Expiry: 12/34

# Any 3-digit number
CVC: 123

# Any postal code
ZIP: 12345

3. Test Script

You can create a test script to verify your configuration:

# Create test file (optional)
cat > scripts/test-stripe.js << 'EOF'
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

async function testStripeConfig() {
  try {
    // Test API connection
    const balance = await stripe.balance.retrieve();
    console.log('โœ… Stripe API connection successful');
    console.log('Account balance:', balance);

    // Test product listing
    const products = await stripe.products.list({ limit: 10 });
    console.log('โœ… Product listing successful');
    console.log('Number of products:', products.data.length);

    // Test price listing
    const prices = await stripe.prices.list({ limit: 10 });
    console.log('โœ… Price listing successful');
    console.log('Number of prices:', prices.data.length);

  } catch (error) {
    console.error('โŒ Stripe configuration test failed:', error.message);
  }
}

testStripeConfig();
EOF

# Run test
node scripts/test-stripe.js

๐Ÿ” Security Configuration

1. Webhook Security Verification

Ensure your webhook handler verifies signatures:

// app/api/stripe/webhook/route.ts
import { headers } from 'next/headers'
import { stripe } from '@/lib/stripe'

export async function POST(req: Request) {
  const body = await req.text()
  const signature = headers().get('stripe-signature')!

  let event
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    )
  } catch (err) {
    console.error('Webhook signature verification failed:', err)
    return new Response('Webhook signature verification failed', { status: 400 })
  }

  // Handle event...
}

2. API Key Security

  • Never expose Secret Key in client-side code
  • Use environment variables to store sensitive information
  • Regularly rotate API keys
  • Use different keys for different environments

3. Amount Validation

Validate payment amounts on the server side:

// Verify payment amount
const expectedAmount = calculateExpectedAmount(productId)
if (session.amount_total !== expectedAmount) {
  throw new Error('Payment amount mismatch')
}

๐Ÿ“Š Monitoring and Analytics

1. Stripe Dashboard Monitoring

In Stripe Dashboard you can monitor:

  • Payment success rate
  • Refund rate
  • Dispute rate
  • Revenue trends
  • Customer lifetime value

2. Custom Analytics

Implement custom analytics tracking:

// Record analytics data after successful payment
await db.insert(analytics).values({
  event: 'payment_succeeded',
  userId: session.metadata.userId,
  amount: session.amount_total,
  currency: session.currency,
  productId: session.metadata.productId,
  timestamp: new Date()
})

๐Ÿšจ Troubleshooting

1. Webhook Receiving Failure

Problem: Webhook events are not being processed correctly Solution:

  • Check if Webhook URL is accessible
  • Verify signing secret is correct
  • Check Webhook logs in Stripe Dashboard

2. Payment Failure

Problem: Customers encounter errors during payment Solution:

  • Check product and price configuration
  • Verify API key permissions
  • Check Stripe logs for specific errors

3. Subscription Status Sync Issues

Problem: Subscription status in database doesn't match Stripe Solution:

  • Ensure webhooks handle all subscription events correctly
  • Implement periodic sync mechanism
  • Add error retry logic

๐ŸŒ International Payments

Supported Payment Methods

  • Credit/Debit cards
  • Apple Pay / Google Pay
  • Bank transfers (selected regions)
  • Digital wallets (PayPal, Alipay, etc.)

Multi-Currency Support

// Set currency based on user region
const currency = getUserCurrency(userCountry)
const session = await stripe.checkout.sessions.create({
  // ...
  currency: currency, // 'usd', 'eur', 'cny', etc.
})

Tax Configuration

// Configure tax calculation
const session = await stripe.checkout.sessions.create({
  // ...
  automatic_tax: { enabled: true },
  tax_id_collection: { enabled: true }
})

๐Ÿ“ž Need Help?

If you encounter issues during configuration, consult the Stripe official documentation or contact technical support.