# Stripe Connect Setup Guide This guide walks you through setting up Stripe Connect onboarding for organizations using Firebase Cloud Functions. ## Architecture Overview - **Frontend**: React components for Stripe Connect UI - **Backend**: Firebase Cloud Functions handling Stripe API calls - **Database**: Firestore with organization payment data - **Security**: No secrets stored client-side, only in Functions environment ## Prerequisites 1. Firebase project with Functions enabled 2. Stripe account with Connect enabled 3. Node.js 20+ for Cloud Functions ## Quick Start ### 1. Install Dependencies ```bash # Install Firebase CLI globally npm install -g firebase-tools # Install Functions dependencies cd functions npm install ``` ### 2. Configure Firebase ```bash # Login to Firebase firebase login # Initialize project (if not already done) firebase init # Select: # - Functions: Configure and deploy Cloud Functions # - Firestore: Deploy database rules # - Hosting: Configure files for Firebase Hosting (optional) ``` ### 3. Set Environment Variables ```bash # Set Stripe secret key in Functions config firebase functions:config:set stripe.secret_key="sk_test_your_stripe_secret_key" # Set webhook secret firebase functions:config:set stripe.webhook_secret="whsec_your_webhook_secret" # Set app URL for redirect links firebase functions:config:set app.url="https://your-app-domain.com" # For local development, create functions/.runtimeconfig.json: cd functions echo '{ "stripe": { "secret_key": "sk_test_your_stripe_secret_key", "webhook_secret": "whsec_your_webhook_secret" }, "app": { "url": "http://localhost:5173" } }' > .runtimeconfig.json ``` ### 4. Deploy Functions ```bash # Build and deploy all functions firebase deploy --only functions # Or deploy individual functions firebase deploy --only functions:stripeConnectStart firebase deploy --only functions:stripeConnectStatus firebase deploy --only functions:stripeWebhook ``` ### 5. Configure Stripe Webhooks 1. Go to your [Stripe Dashboard](https://dashboard.stripe.com/webhooks) 2. Click "Add endpoint" 3. Set endpoint URL: `https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/stripeWebhook` 4. Select events: `account.updated` 5. Copy the webhook secret and update your Functions config ## Frontend Integration ### Using the Hook ```tsx import { useStripeConnect } from './hooks/useStripeConnect'; function PaymentSettings({ orgId }: { orgId: string }) { const { startOnboarding, checkStatus, isLoading, error, paymentData } = useStripeConnect(orgId); const handleConnect = async () => { await startOnboarding('/settings?tab=payments'); }; return (
{paymentData?.connected ? (

✅ Stripe account connected!

) : ( )}
); } ``` ### Using Components ```tsx import { StripeConnectStatus, PaymentSettings } from './components/billing'; function SettingsPage() { const orgId = 'your-org-id'; return (

Settings

{/* Or use individual components */} console.log('Updated:', data)} />
); } ``` ## Firestore Schema The system stores payment data in the organization document: ```typescript // /orgs/{orgId} interface Organization { id: string; name: string; // ... other fields payment?: { provider: 'stripe'; connected: boolean; stripe: { accountId: string; detailsSubmitted: boolean; chargesEnabled: boolean; businessName: string; }; }; } ``` ## API Endpoints ### POST /api/stripe/connect/start Starts Stripe Connect onboarding flow. **Request:** ```json { "orgId": "org_12345", "returnTo": "/settings?tab=payments" // optional } ``` **Response:** ```json { "url": "https://connect.stripe.com/setup/e/acct_..." } ``` ### GET /api/stripe/connect/status Gets current Stripe Connect status. **Query Params:** - `orgId`: Organization ID **Response:** ```json { "payment": { "provider": "stripe", "connected": true, "stripe": { "accountId": "acct_12345", "detailsSubmitted": true, "chargesEnabled": true, "businessName": "Example Business" } } } ``` ### POST /api/stripe/webhook Handles Stripe platform webhooks. **Supported Events:** - `account.updated`: Updates organization payment status ## Development ### Local Testing 1. Start Firebase emulators: ```bash firebase emulators:start --only functions,firestore ``` 2. Update frontend API URL to use emulator: ```typescript // In useStripeConnect.ts const getApiUrl = (): string => { if (import.meta.env.DEV) { return 'http://localhost:5001/YOUR_PROJECT_ID/us-central1'; } return 'https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net'; }; ``` 3. Test webhook locally using Stripe CLI: ```bash stripe listen --forward-to localhost:5001/YOUR_PROJECT_ID/us-central1/stripeWebhook ``` ### Testing Flow 1. **Start Onboarding**: Call `/api/stripe/connect/start` 2. **Complete Stripe Onboarding**: Follow Stripe's onboarding flow 3. **Return to App**: User is redirected back with status 4. **Check Status**: Call `/api/stripe/connect/status` 5. **Webhook Updates**: Stripe sends `account.updated` webhooks ## Security Considerations - ✅ **No secrets in frontend**: All Stripe API calls happen server-side - ✅ **Webhook verification**: All webhooks are verified with signatures - ✅ **CORS protection**: Functions have restricted CORS policies - ✅ **Firestore rules**: Database access controlled by authentication - ✅ **Environment isolation**: Dev/staging/prod environment separation ## Troubleshooting ### Common Issues 1. **CORS errors**: Check that your domain is in the CORS configuration 2. **Webhook failures**: Verify webhook secret matches Stripe dashboard 3. **Permission errors**: Ensure Firestore rules allow organization access 4. **Environment variables**: Check Functions config with `firebase functions:config:get` ### Debugging ```bash # View function logs firebase functions:log # Check Functions config firebase functions:config:get # Test Functions locally cd functions npm run serve ``` ### Error Codes - `400`: Missing or invalid request parameters - `404`: Organization or Stripe account not found - `405`: HTTP method not allowed - `500`: Internal server error (check logs) ## Production Checklist - [ ] Stripe secret keys configured in Functions - [ ] Webhook endpoint configured in Stripe Dashboard - [ ] Firestore security rules deployed - [ ] Frontend API URLs point to production Functions - [ ] CORS policies configured for production domain - [ ] Error monitoring enabled (Sentry/Cloud Logging) - [ ] Rate limiting configured if needed ## Next Steps After setup, you can extend the system with: 1. **Payment Processing**: Create payment intents with connected accounts 2. **Payouts**: Configure automatic payouts to connected accounts 3. **Fees**: Implement application fees on transactions 4. **Dashboard**: Show earnings and transaction history 5. **Compliance**: Add tax reporting and regulatory features