Sir Chargly - Testing & Troubleshooting Guide
Comprehensive guide for testing the onboarding flow and troubleshooting common issues.
Table of Contents
Testing Onboarding Flow
Complete Onboarding Test
Follow these steps to test the complete onboarding wizard:
Step 1: Create Test Account
- Email: test+${Date.now()}@sirchargly.com
- Password: password123
- Name: Test Merchant
/onboardingStep 2: Welcome Screen
- "Welcome to Sir Chargly, Test Merchant!" heading
- 4 value proposition cards
- "What's Next?" section with 5 steps
- "Let's Get Started →" button
Step 3: Stripe Connect
Note: This requires Stripe OAuth setup. If not configured, you'll see an error.
With Stripe OAuth Configured:
?stripe_connected=trueWithout Stripe OAuth (Skip for Testing):
```javascript
db.merchants.updateOne(
{ email: "your-test-email@example.com" },
{
$set: {
"stripeConnect": {
accountId: "acct_test_123",
type: "standard",
status: "active",
connectedAt: new Date()
}
}
}
);
```
Step 4: Earnings Analysis
- "Current Earnings" (gray)
- "With Sir Chargly" (green with border)
- Average Transaction amount
- Total Transactions count
- Numbers should count up from 0
- Bars should fill from left to right
What to Check:
Step 5: Fee Configuration
- Drag from 0% to 5%
- Expected: Revenue number updates in real-time
- Expected: Example calculation updates
- Drag from $0.00 to $2.00
- Expected: Revenue number updates immediately
- Expected: Example shows new flat fee
- Base Amount: $100.00
- Percentage: (matches slider)
- Flat Fee: (matches slider)
- Total Convenience Fee: (sum of above)
What to Check:
Step 6: API Key Generation
- Publishable Key (starts with pk_dev_sirchargly_)
- Secret Key (starts with sk_dev_sirchargly_, initially hidden)
- Click eye icon on secret key
- Expected: Key becomes visible
- Click eye icon again
- Expected: Key is hidden again
- 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
What to Check:
Step 7: Integration Guide
- Installation command
- Client-side integration
- Server-side integration
- Webhook setup
- "Go to Dashboard" (internal link)
- "Read the Docs" (external link)
What to Check:
Step 8: Dashboard Redirect
/dashboard- Environment toggle (Dev mode selected)
- Navigation items
- Current page highlighted
What to Check:
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:
Causes:
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:
Solution:
Chrome/Edge:
Firefox:
Safari:
Universal Solution:
# Force reload without cache
Mac: Cmd + Shift + R
Windows/Linux: Ctrl + Shift + R
Issue: useSearchParams() Error
Symptoms:
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:
Causes:
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:
Causes:
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:
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
next-auth.session-token3. 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:
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)
Issue: Duplicate Key Error
Symptoms:
Causes:
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:
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:
Causes:
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
https://sirchargly.com/api/v1/stripe/connect/callback3. 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:
Solution:
Check server logs for the specific error:
# Look for errors like:
# - Invalid client_id
# - Invalid authorization code
# - Code already used
Common fixes:
Performance Issues
Issue: Slow Page Loads
Symptoms:
Causes:
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:
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
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:
Application Tab:
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:
Database Debugging
MongoDB Compass:
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:
- Full error text
- Stack trace
- Request ID (if available)
- Operating system
- Node.js version
- Browser and version
- Development or production
- What you were doing
- What you expected
- What actually happened
- Server logs (last 50 lines)
- Browser console errors
- Network tab for failed requests
- .env.local (remove sensitive values)
- package.json dependencies
Support Channels
Internal:
External:
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
Authentication
API Functionality
Dashboard
This completes the Testing & Troubleshooting Guide! 🔍
For additional help, refer to other documentation: