Back to Documentation

Sir Chargly - Testing & Troubleshooting Guide

Comprehensive guide for testing the onboarding flow and troubleshooting common issues.

Table of Contents

  • Testing Onboarding Flow
  • API Testing
  • Common Issues
  • Browser Issues
  • Authentication Issues
  • Database Issues
  • Stripe Integration Issues
  • Performance Issues
  • Debugging Tools
  • Getting Help

  • Testing Onboarding Flow

    Complete Onboarding Test

    Follow these steps to test the complete onboarding wizard:

    Step 1: Create Test Account

  • Navigate to https://sirchargly.com
  • Click "Sign up" link
  • Fill in signup form:
  • - Email: test+${Date.now()}@sirchargly.com

    - Password: password123

    - Name: Test Merchant

  • Submit form
  • Expected: Redirect to /onboarding
  • Step 2: Welcome Screen

  • Expected: See welcome screen with:
  • - "Welcome to Sir Chargly, Test Merchant!" heading

    - 4 value proposition cards

    - "What's Next?" section with 5 steps

    - "Let's Get Started →" button

  • Click "Let's Get Started →"
  • Expected: Progress bar shows "Step 1 of 6"
  • Expected: Advance to Stripe Connect step
  • Step 3: Stripe Connect

    Note: This requires Stripe OAuth setup. If not configured, you'll see an error.

    With Stripe OAuth Configured:

  • Expected: See "Connect Your Stripe Account" heading
  • Expected: Three sections explaining permissions
  • Click "Connect with Stripe"
  • Expected: Redirect to Stripe OAuth page
  • Authorize the connection
  • Expected: Redirect back to onboarding with ?stripe_connected=true
  • Without Stripe OAuth (Skip for Testing):

  • Manually update database to mark Stripe as connected:
  • ```javascript

    db.merchants.updateOne(

    { email: "your-test-email@example.com" },

    {

    $set: {

    "stripeConnect": {

    accountId: "acct_test_123",

    type: "standard",

    status: "active",

    connectedAt: new Date()

    }

    }

    }

    );

    ```

  • Refresh the onboarding page
  • Expected: See "Stripe Already Connected!" message
  • Click "Continue to Analysis →"
  • Step 4: Earnings Analysis

  • Expected: See "Your Earning Potential" heading
  • Expected: Large animated number showing additional revenue (e.g., "+$1,247")
  • Expected: Two comparison cards:
  • - "Current Earnings" (gray)

    - "With Sir Chargly" (green with border)

  • Expected: 30-Day Comparison bar chart (two bars)
  • Expected: Stats showing:
  • - Average Transaction amount

    - Total Transactions count

  • Watch the animation:
  • - Numbers should count up from 0

    - Bars should fill from left to right

  • Click "Configure My Fees →"
  • What to Check:

  • Numbers are realistic (based on mock data)
  • Animation is smooth
  • Percentage increase is calculated correctly
  • Stats make sense
  • Step 5: Fee Configuration

  • Expected: See "Configure Your Convenience Fees" heading
  • Expected: Large revenue projection at top (animated)
  • Test percentage slider:
  • - Drag from 0% to 5%

    - Expected: Revenue number updates in real-time

    - Expected: Example calculation updates

  • Test flat fee slider:
  • - Drag from $0.00 to $2.00

    - Expected: Revenue number updates immediately

    - Expected: Example shows new flat fee

  • Expected: Example calculation for $100 transaction:
  • - Base Amount: $100.00

    - Percentage: (matches slider)

    - Flat Fee: (matches slider)

    - Total Convenience Fee: (sum of above)

  • Set fees to: 2.9% + $0.30
  • Click "Save & Continue →"
  • What to Check:

  • Sliders are responsive
  • Numbers update immediately (no lag)
  • Calculations are accurate
  • Revenue projection is reasonable
  • Step 6: API Key Generation

  • Expected: See "Generate Your First API Key" heading
  • Expected: Three information bullets about keys
  • Click "Generate My API Key →"
  • Expected: Button shows "Generating..." (brief moment)
  • Expected: Screen changes to "Your API Keys Are Ready!"
  • Expected: Red warning text: "⚠️ Copy these now - the secret key will never be shown again!"
  • Expected: Two key displays:
  • - Publishable Key (starts with pk_dev_sirchargly_)

    - Secret Key (starts with sk_dev_sirchargly_, initially hidden)

  • Test key visibility:
  • - Click eye icon on secret key

    - Expected: Key becomes visible

    - Click eye icon again

    - Expected: Key is hidden again

  • Test copy functionality:
  • - Click copy icon for publishable key

    - Expected: Icon changes to checkmark briefly

    - Paste into text editor

    - Expected: Full publishable key is copied

    - Repeat for secret key

  • Click "I've Saved My Keys →"
  • What to Check:

  • Keys are generated with correct prefixes
  • Secret key is hidden by default
  • Copy functionality works for both keys
  • Warning messages are prominent
  • Keys are unique (not same as previous test)
  • Step 7: Integration Guide

  • Expected: See "You're All Set!" heading
  • Expected: Quick reference section with both keys (partially hidden)
  • Expected: Four code examples:
  • - Installation command

    - Client-side integration

    - Server-side integration

    - Webhook setup

  • Test copy functionality on all code blocks
  • Expected: Two "Next Steps" cards:
  • - "Go to Dashboard" (internal link)

    - "Read the Docs" (external link)

  • Click "Complete Setup & Go to Dashboard →"
  • What to Check:

  • Code examples show your actual API keys
  • Copy buttons work on all code blocks
  • Syntax highlighting is correct
  • Links are functional
  • Step 8: Dashboard Redirect

  • Expected: Redirect to /dashboard
  • Expected: Dashboard loads successfully
  • Expected: No errors in console
  • Expected: Sidebar shows:
  • - Environment toggle (Dev mode selected)

    - Navigation items

    - Current page highlighted

  • Expected: Dashboard shows metrics and charts
  • What to Check:

  • Smooth redirect (no flash)
  • Dashboard loads without errors
  • Data is populated
  • Navigation works

  • API Testing

    Test API Key Authentication

    # Test with your generated development key
    curl -X POST https://api.sirchargly.com/v1/estimates \
      -H "Authorization: Bearer sk_dev_sirchargly_YOUR_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "amount": 10000,
        "currency": "usd",
        "region": "US-CA",
        "cardType": "credit"
      }'
    

    Expected Response:

    {
      "baseAmount": 10000,
      "convenienceFee": 320,
      "totalAmount": 10320,
      "feeBreakdown": {
        "percentage": 290,
        "flatFee": 30
      },
      "compliant": true,
      "region": "US-CA"
    }
    

    Test Invalid API Key

    curl -X POST https://api.sirchargly.com/v1/estimates \
      -H "Authorization: Bearer sk_dev_sirchargly_invalid" \
      -H "Content-Type: application/json" \
      -d '{"amount": 10000, "currency": "usd"}'
    

    Expected Response:

    {
      "error": {
        "type": "authentication_error",
        "message": "Invalid API key"
      }
    }
    

    Test Environment Detection

    # Development key should work with /api/v1 endpoints
    curl https://api.sirchargly.com/v1/fee-configs \
      -H "Authorization: Bearer sk_dev_sirchargly_YOUR_KEY"
    
    # Production key should be rejected in dev environment
    # (or work but show different data if env switching is enabled)
    

    Common Issues

    Issue: Internal Server Error on All Pages

    Symptoms:

  • Every page shows "Internal Server Error"
  • Console shows no specific error
  • Happens after making code changes
  • Causes:

  • Corrupted Next.js cache
  • TypeScript compilation errors
  • Missing environment variables
  • Database connection issues
  • Solutions:

    1. Clear Next.js Cache

    rm -rf .next
    npm run dev
    

    2. Check for TypeScript Errors

    npx tsc --noEmit
    

    3. Verify Environment Variables

    # Check .env.local exists
    ls -la .env.local
    
    # Verify required variables are set
    cat .env.local | grep -E "MONGODB_URI|NEXTAUTH_SECRET"
    

    4. Check Database Connection

    # Test MongoDB connection
    mongo $MONGODB_URI --eval "db.version()"
    

    Browser Issues

    Issue: Cached Error Pages

    Symptoms:

  • Pages show old errors even after fixes
  • Hard refresh doesn't help
  • Works in incognito mode
  • Solution:

    Chrome/Edge:

  • Open DevTools (F12)
  • Go to Application tab
  • Click "Clear site data"
  • Check all boxes
  • Click "Clear site data"
  • Close and reopen tab
  • Firefox:

  • Open DevTools (F12)
  • Go to Storage tab
  • Right-click on sirchargly.com
  • Select "Delete All"
  • Close and reopen tab
  • Safari:

  • Develop menu → Empty Caches
  • Or: Safari → Clear History → All History
  • Universal Solution:

    # Force reload without cache
    Mac: Cmd + Shift + R
    Windows/Linux: Ctrl + Shift + R
    

    Issue: useSearchParams() Error

    Symptoms:

  • Error: "useSearchParams() should be wrapped in a suspense boundary"
  • Happens on pages using search params
  • Build fails
  • Solution:

    Wrap the component in Suspense:

    import { Suspense } from 'react';
    
    export default function Page() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <PageContent />
        </Suspense>
      );
    }
    
    function PageContent() {
      const searchParams = useSearchParams();
      // ... rest of component
    }
    

    Authentication Issues

    Issue: CSRF Token Missing

    Symptoms:

  • Error: "MissingCSRF: CSRF token was missing"
  • Login fails
  • Happens after code changes to auth
  • Causes:

  • NextAuth type mismatch
  • Session type incorrectly defined
  • Auth configuration issue
  • Solution:

    Check lib/auth.ts:

    // ✅ Correct - use any for session parameter
    export async function getMerchantFromSession(
      session: any
    ): Promise<IMerchant | null> {
      if (!session?.user?.id) {
        return null;
      }
      // ...
    }
    
    // ❌ Wrong - importing Session type can cause issues
    import { Session } from 'next-auth';
    export async function getMerchantFromSession(
      session: Session | null
    ): Promise<IMerchant | null> {
      // This can cause CSRF validation to fail
    }
    

    Issue: Session Not Persisting

    Symptoms:

  • User logs in successfully
  • Redirect happens
  • But user appears logged out on next page
  • Causes:

  • NEXTAUTH_URL mismatch
  • Cookie domain issues
  • Secure cookie in development
  • Solution:

    Check .env.local:

    # Must match your deployment URL exactly
    NEXTAUTH_URL=https://sirchargly.com
    
    # Use https in production
    # NO trailing slash
    

    Restart server after changing.

    Issue: Can't Access Protected Routes

    Symptoms:

  • Redirected to /login even when logged in
  • Session appears valid in one tab but not another
  • Solution:

    1. Check Auth Middleware

    // app/dashboard/page.tsx
    const session = await auth();
    
    if (!session) {
      redirect('/login'); // ✅ Good
    }
    
    const merchant = await getMerchantFromSession(session);
    
    if (!merchant) {
      redirect('/login'); // ✅ Good
    }
    

    2. Verify Session Cookie

  • Open DevTools → Application → Cookies
  • Look for next-auth.session-token
  • Check it's set for your domain (sirchargly.com)
  • Check expiration is in the future
  • 3. Clear All Sessions

    # Delete all session cookies
    # In browser: DevTools → Application → Cookies → Delete All
    
    # Or restart fresh
    rm -rf .next
    npm run dev
    

    Database Issues

    Issue: MongoServerError: Authentication Failed

    Symptoms:

  • Error connecting to MongoDB
  • "Authentication failed" in logs
  • Solution:

    1. Check Connection String

    # Format should be:
    mongodb://username:password@host:port/database
    
    # For Atlas:
    mongodb+srv://username:password@cluster.mongodb.net/database
    

    2. Verify Credentials

    # Test with mongo CLI
    mongo "mongodb://username:password@host:port/database"
    

    3. Check IP Whitelist (MongoDB Atlas)

  • Go to Atlas dashboard
  • Network Access
  • Add your IP or 0.0.0.0/0 (for testing)
  • Issue: Duplicate Key Error

    Symptoms:

  • Error: "E11000 duplicate key error"
  • Can't create merchants or API keys
  • Causes:

  • Unique index violation
  • Trying to create duplicate email/API key
  • Solution:

    1. Check for Existing Data

    // In MongoDB shell or MongoDB Compass
    db.merchants.find({ email: "test@example.com" });
    

    2. Remove Duplicate

    db.merchants.deleteOne({ email: "test@example.com" });
    

    3. Reset Database

    npm run db:reset
    npm run seed:dev
    

    Issue: Connection Timeout

    Symptoms:

  • "MongoServerError: connection timed out"
  • Slow page loads
  • Intermittent failures
  • Solution:

    1. Check MongoDB is Running

    # Check process
    ps aux | grep mongod
    
    # Check port
    lsof -i :27017
    

    2. Restart MongoDB

    # Docker
    docker restart sirchargly-mongo
    
    # Homebrew (macOS)
    brew services restart mongodb-community
    
    # systemd (Linux)
    sudo systemctl restart mongod
    

    3. Increase Timeout

    // lib/mongodb.ts
    const options = {
      serverSelectionTimeoutMS: 10000, // 10 seconds
      socketTimeoutMS: 45000, // 45 seconds
    };
    

    Stripe Integration Issues

    Issue: Stripe OAuth Redirect Fails

    Symptoms:

  • Click "Connect with Stripe" does nothing
  • Or redirects but shows error
  • Or redirects back but not connected
  • Causes:

  • Missing STRIPE_CONNECT_CLIENT_ID
  • Wrong redirect URI
  • Stripe test/live mode mismatch
  • Solution:

    1. Verify Environment Variables

    cat .env.local | grep STRIPE
    

    Should have:

    STRIPE_SECRET_KEY=sk_test_...
    STRIPE_PUBLISHABLE_KEY=pk_test_...
    STRIPE_CONNECT_CLIENT_ID=ca_...
    

    2. Check Redirect URI in Stripe Dashboard

  • Go to https://dashboard.stripe.com/settings/applications
  • Check redirect URI matches: https://sirchargly.com/api/v1/stripe/connect/callback
  • Add if missing
  • 3. Test OAuth URL Generation

    curl -X POST https://sirchargly.com/api/v1/stripe/connect/oauth-url \
      -H "Content-Type: application/json" \
      -d '{"merchantId": "YOUR_MERCHANT_ID"}' \
      -H "Cookie: your-session-cookie"
    

    Issue: Stripe Connect Token Exchange Fails

    Symptoms:

  • OAuth redirect succeeds
  • But merchant not marked as connected
  • Error in server logs
  • Solution:

    Check server logs for the specific error:

    # Look for errors like:
    # - Invalid client_id
    # - Invalid authorization code
    # - Code already used
    

    Common fixes:

  • Ensure using correct Stripe API version
  • Check authorization code hasn't expired
  • Verify client ID matches environment (test/live)

  • Performance Issues

    Issue: Slow Page Loads

    Symptoms:

  • Pages take 5+ seconds to load
  • Dashboard is slow
  • API requests timeout
  • Causes:

  • Database queries not optimized
  • Large payload sizes
  • No caching
  • Missing indexes
  • Solutions:

    1. Check Database Indexes

    // In MongoDB shell
    db.feecharges.getIndexes();
    db.merchants.getIndexes();
    
    // Add missing indexes
    db.feecharges.createIndex({ merchantId: 1, createdAt: -1 });
    db.merchants.createIndex({ email: 1 }, { unique: true });
    

    2. Enable Query Logging

    // lib/mongodb.ts
    mongoose.set('debug', true); // Log all queries
    

    3. Add Caching

    // Example: Cache fee config
    const cacheKey = `fee-config:${merchantId}`;
    let config = await cache.get(cacheKey);
    
    if (!config) {
      config = await FeeConfig.findOne({ merchantId });
      await cache.set(cacheKey, config, 300); // 5 minutes
    }
    

    Issue: Memory Leaks

    Symptoms:

  • Dev server becomes slow over time
  • Need to restart frequently
  • High memory usage
  • Solution:

    1. Check for Unclosed Connections

    // ❌ Bad - connection not closed
    const merchant = await Merchant.findById(id);
    // ... do something
    
    // ✅ Good - explicit cleanup
    try {
      const merchant = await Merchant.findById(id);
      // ... do something
    } finally {
      // Cleanup if needed
    }
    

    2. Use Next.js Fast Refresh Wisely

  • Don't keep dev server running for days
  • Restart after major changes
  • Clear .next folder periodically

  • Debugging Tools

    Browser DevTools

    Console Tab:

    // Check for errors
    console.error('Something went wrong');
    
    // Log API responses
    console.log('API response:', await response.json());
    
    // Debug state
    console.log('Current state:', { user, session, merchant });
    

    Network Tab:

  • Filter by "Fetch/XHR" to see API calls
  • Check request headers (Authorization)
  • Check response status codes
  • Check response payloads
  • Look for failed requests (red)
  • Application Tab:

  • Check cookies (next-auth.session-token)
  • Check localStorage (sirchargly_environment)
  • Clear site data when needed
  • Server-Side Debugging

    Add Debug Logging:

    // In API routes
    console.log('[DEBUG] Request:', {
      method: request.method,
      url: request.url,
      headers: Object.fromEntries(request.headers),
    });
    
    console.log('[DEBUG] Response:', {
      status: response.status,
      data: await response.json(),
    });
    

    VS Code Debugger:

  • Add breakpoints in code
  • Run "Next.js: debug server-side" configuration
  • Step through code
  • Inspect variables
  • Database Debugging

    MongoDB Compass:

  • Visual interface for MongoDB
  • Browse collections
  • Run queries
  • View indexes
  • Performance insights
  • Command Line:

    # Connect to MongoDB
    mongo $MONGODB_URI
    
    # Check merchants
    db.merchants.find().pretty();
    
    # Check API keys
    db.merchants.find({}, { apiKeys: 1, email: 1 }).pretty();
    
    # Check recent charges
    db.feecharges.find().sort({ createdAt: -1 }).limit(10).pretty();
    

    Getting Help

    Before Asking for Help

    Collect this information:

  • Error Message
  • - Full error text

    - Stack trace

    - Request ID (if available)

  • Environment
  • - Operating system

    - Node.js version

    - Browser and version

    - Development or production

  • Steps to Reproduce
  • - What you were doing

    - What you expected

    - What actually happened

  • Logs
  • - Server logs (last 50 lines)

    - Browser console errors

    - Network tab for failed requests

  • Configuration
  • - .env.local (remove sensitive values)

    - package.json dependencies

    Support Channels

    Internal:

  • Slack: #engineering
  • Email: dev@sirchargly.com
  • Wiki: https://wiki.sirchargly.com
  • External:

  • GitHub Issues: https://github.com/sirchargly/platform/issues
  • Community: https://community.sirchargly.com
  • Docs: https://docs.sirchargly.com
  • Filing a Bug Report

    Good Bug Report:

    ## Bug Description
    The onboarding wizard crashes at step 4 (Fee Configuration) when adjusting the percentage slider.
    
    ## Environment
    - OS: macOS 14.1
    - Node.js: v18.17.0
    - Browser: Chrome 120.0.6099.109
    
    ## Steps to Reproduce
    1. Complete signup
    2. Navigate through steps 1-3
    3. On step 4, drag percentage slider to 5%
    4. Page crashes with "Cannot read property 'toFixed' of undefined"
    
    ## Expected Behavior
    Slider should update revenue projection smoothly
    
    ## Actual Behavior
    Page crashes, console shows error:
    

    TypeError: Cannot read property 'toFixed' of undefined

    at FeeConfigurationStep (FeeConfigurationStep.tsx:28)

    
    ## Additional Context
    - Happens consistently
    - Only with percentage slider, not flat fee slider
    - Started after upgrading to Next.js 14.1
    

    Testing Checklist

    Use this checklist for thorough testing:

    Onboarding Flow

  • [ ] Sign up creates new merchant
  • [ ] Welcome step displays correctly
  • [ ] Stripe Connect works (or can be skipped)
  • [ ] Earnings analysis shows data
  • [ ] Earnings animation is smooth
  • [ ] Fee configuration sliders work
  • [ ] Revenue updates in real-time
  • [ ] API keys are generated
  • [ ] Keys can be copied
  • [ ] Secret key is hidden by default
  • [ ] Integration guide shows code
  • [ ] Redirect to dashboard works
  • Authentication

  • [ ] Login with correct credentials works
  • [ ] Login with wrong credentials fails
  • [ ] Session persists across tabs
  • [ ] Logout works correctly
  • [ ] Protected routes require auth
  • [ ] Public routes are accessible
  • API Functionality

  • [ ] Development keys authenticate
  • [ ] Invalid keys are rejected
  • [ ] Environment is detected correctly
  • [ ] Fee calculation is accurate
  • [ ] Regional compliance works
  • [ ] Error responses are formatted correctly
  • Dashboard

  • [ ] Loads without errors
  • [ ] Metrics display correctly
  • [ ] Environment toggle works
  • [ ] Navigation works
  • [ ] API keys can be managed
  • [ ] Fee config can be updated

  • This completes the Testing & Troubleshooting Guide! 🔍

    For additional help, refer to other documentation:

  • User Onboarding Guide
  • API Integration Guide
  • Developer Setup
  • Ready to start charging convenience fees?

    Create your account and complete onboarding in minutes.

    No credit card required • 5-minute setup