|
| 1 | +# Payment & Subscription Setup Guide (SSC-16) |
| 2 | + |
| 3 | +This guide explains how to set up and configure the payment processing and subscription management system for StudySync. |
| 4 | + |
| 5 | +## 🎯 Overview |
| 6 | + |
| 7 | +StudySync uses **Stripe** for payment processing and subscription management. The system supports: |
| 8 | + |
| 9 | +- ✅ Multiple subscription tiers (FREE, PREMIUM, STUDENT_PLUS, UNIVERSITY) |
| 10 | +- ✅ Monthly and yearly billing options |
| 11 | +- ✅ Free trials (7 days for Student Plus) |
| 12 | +- ✅ Student discounts (20% off for .edu emails) |
| 13 | +- ✅ Stripe Checkout for payment collection |
| 14 | +- ✅ Stripe Customer Portal for billing management |
| 15 | +- ✅ Webhooks for automatic subscription updates |
| 16 | +- ✅ Invoice history and payment tracking |
| 17 | +- ✅ Feature gating based on subscription tier |
| 18 | +- ✅ Usage limits enforcement |
| 19 | + |
| 20 | +## 📋 Prerequisites |
| 21 | + |
| 22 | +- Stripe account (sign up at https://stripe.com) |
| 23 | +- PostgreSQL database (for storing subscription data) |
| 24 | +- Node.js 18+ and npm |
| 25 | +- Access to the StudySync codebase |
| 26 | + |
| 27 | +## 🔧 Setup Instructions |
| 28 | + |
| 29 | +### 1. Create Stripe Account |
| 30 | + |
| 31 | +1. Go to https://stripe.com and create an account |
| 32 | +2. Complete the onboarding process |
| 33 | +3. Access your Dashboard at https://dashboard.stripe.com |
| 34 | + |
| 35 | +### 2. Get API Keys |
| 36 | + |
| 37 | +1. In Stripe Dashboard, go to **Developers** → **API Keys** |
| 38 | +2. Copy your **Publishable key** (starts with `pk_test_` or `pk_live_`) |
| 39 | +3. Copy your **Secret key** (starts with `sk_test_` or `sk_live_`) |
| 40 | +4. Keep these keys secure! |
| 41 | + |
| 42 | +### 3. Create Products and Prices |
| 43 | + |
| 44 | +#### Premium Plan |
| 45 | + |
| 46 | +1. Go to **Products** → **Add Product** |
| 47 | +2. Name: "StudySync Premium" |
| 48 | +3. Description: "Unlimited courses and advanced features" |
| 49 | +4. Create two prices: |
| 50 | + - **Monthly**: $9.99/month (recurring) |
| 51 | + - **Yearly**: $99.99/year (recurring) |
| 52 | +5. Copy the Price IDs (start with `price_`) |
| 53 | + |
| 54 | +#### Student Plus Plan |
| 55 | + |
| 56 | +1. Go to **Products** → **Add Product** |
| 57 | +2. Name: "StudySync Student Plus" |
| 58 | +3. Description: "All Premium features plus AI tutoring and exam prediction" |
| 59 | +4. Create two prices: |
| 60 | + - **Monthly**: $14.99/month (recurring) |
| 61 | + - **Yearly**: $149.99/year (recurring) |
| 62 | +5. Add a 7-day free trial to monthly pricing |
| 63 | +6. Copy the Price IDs |
| 64 | + |
| 65 | +### 4. Set Up Webhooks |
| 66 | + |
| 67 | +1. Go to **Developers** → **Webhooks** |
| 68 | +2. Click **Add endpoint** |
| 69 | +3. Endpoint URL: `https://yourdomain.com/api/subscriptions/webhook` |
| 70 | + - For local development: Use ngrok or expose.dev to create a public URL |
| 71 | + - Example: `https://abc123.ngrok.io/api/subscriptions/webhook` |
| 72 | +4. Select events to listen for: |
| 73 | + - `customer.subscription.created` |
| 74 | + - `customer.subscription.updated` |
| 75 | + - `customer.subscription.deleted` |
| 76 | + - `invoice.paid` |
| 77 | + - `invoice.payment_failed` |
| 78 | + - `customer.created` |
| 79 | + - `customer.updated` |
| 80 | + - `payment_intent.succeeded` |
| 81 | + - `payment_intent.payment_failed` |
| 82 | +5. Copy the **Signing secret** (starts with `whsec_`) |
| 83 | + |
| 84 | +### 5. Configure Environment Variables |
| 85 | + |
| 86 | +Update your `.env` file in the root directory: |
| 87 | + |
| 88 | +```bash |
| 89 | +# Stripe Configuration |
| 90 | +STRIPE_SECRET_KEY="sk_test_your_secret_key_here" |
| 91 | +STRIPE_WEBHOOK_SECRET="whsec_your_webhook_secret_here" |
| 92 | +NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_your_publishable_key_here" |
| 93 | + |
| 94 | +# Stripe Price IDs |
| 95 | +STRIPE_PRICE_PREMIUM_MONTHLY="price_xxx" |
| 96 | +STRIPE_PRICE_PREMIUM_YEARLY="price_xxx" |
| 97 | +STRIPE_PRICE_STUDENT_PLUS_MONTHLY="price_xxx" |
| 98 | +STRIPE_PRICE_STUDENT_PLUS_YEARLY="price_xxx" |
| 99 | + |
| 100 | +# Application URLs |
| 101 | +FRONTEND_URL="http://localhost:3000" |
| 102 | +NEXT_PUBLIC_API_URL="http://localhost:3001" |
| 103 | +``` |
| 104 | + |
| 105 | +### 6. Run Database Migrations |
| 106 | + |
| 107 | +Apply the payment-related schema changes: |
| 108 | + |
| 109 | +```bash |
| 110 | +npm run db:push |
| 111 | +# or |
| 112 | +npm run db:migrate |
| 113 | +``` |
| 114 | + |
| 115 | +This will create the following tables: |
| 116 | +- `Subscription` - Subscription history |
| 117 | +- `Payment` - Payment transactions |
| 118 | +- `Invoice` - Invoice records |
| 119 | + |
| 120 | +### 7. Start the Application |
| 121 | + |
| 122 | +```bash |
| 123 | +# Start all services |
| 124 | +npm run dev |
| 125 | + |
| 126 | +# Or start individually |
| 127 | +npm run dev --workspace=@studysync/web # Frontend |
| 128 | +npm run dev --workspace=@studysync/api # Backend |
| 129 | +``` |
| 130 | + |
| 131 | +## 🧪 Testing |
| 132 | + |
| 133 | +### Test Mode |
| 134 | + |
| 135 | +Stripe provides test mode for development: |
| 136 | + |
| 137 | +1. Use test API keys (starting with `sk_test_` and `pk_test_`) |
| 138 | +2. Use test card numbers: |
| 139 | + - **Success**: 4242 4242 4242 4242 |
| 140 | + - **Decline**: 4000 0000 0000 0002 |
| 141 | + - **3D Secure**: 4000 0025 0000 3155 |
| 142 | + - **Insufficient funds**: 4000 0000 0000 9995 |
| 143 | +3. Use any future expiry date (e.g., 12/34) |
| 144 | +4. Use any 3-digit CVC (e.g., 123) |
| 145 | +5. Use any ZIP code (e.g., 12345) |
| 146 | + |
| 147 | +### Testing Workflow |
| 148 | + |
| 149 | +1. **Create Subscription**: |
| 150 | + - Go to http://localhost:3000/pricing |
| 151 | + - Click "Start Free Trial" on Premium or Student Plus |
| 152 | + - Use test card: 4242 4242 4242 4242 |
| 153 | + - Complete checkout |
| 154 | + |
| 155 | +2. **Verify Subscription**: |
| 156 | + - Check http://localhost:3000/subscription |
| 157 | + - Should show "Active" status |
| 158 | + - Should display correct billing cycle |
| 159 | + |
| 160 | +3. **Test Webhooks**: |
| 161 | + - Make a change in Stripe Dashboard |
| 162 | + - Webhook should automatically update the database |
| 163 | + - Check API logs for webhook events |
| 164 | + |
| 165 | +4. **Test Cancellation**: |
| 166 | + - Click "Manage Billing" on subscription page |
| 167 | + - Cancel subscription in Stripe portal |
| 168 | + - Verify status updates to "Canceled" |
| 169 | + |
| 170 | +5. **Test Feature Gating**: |
| 171 | + - Try accessing premium features |
| 172 | + - Should show upgrade prompt for FREE tier users |
| 173 | + - Should allow access for PREMIUM/STUDENT_PLUS users |
| 174 | + |
| 175 | +## 🎛️ Configuration |
| 176 | + |
| 177 | +### Subscription Tiers |
| 178 | + |
| 179 | +Edit `apps/api/src/config/pricing.ts` to modify: |
| 180 | + |
| 181 | +- Pricing amounts |
| 182 | +- Feature limits |
| 183 | +- Trial periods |
| 184 | +- Student discount percentage |
| 185 | + |
| 186 | +### Feature Limits |
| 187 | + |
| 188 | +Current limits per tier: |
| 189 | + |
| 190 | +**FREE**: |
| 191 | +- 1 course |
| 192 | +- 3 flashcard sets |
| 193 | +- 5 quizzes |
| 194 | +- No knowledge graph |
| 195 | +- No analytics |
| 196 | + |
| 197 | +**PREMIUM**: |
| 198 | +- Unlimited courses |
| 199 | +- Unlimited flashcard sets |
| 200 | +- Unlimited quizzes |
| 201 | +- Knowledge graph ✓ |
| 202 | +- Analytics ✓ |
| 203 | + |
| 204 | +**STUDENT_PLUS**: |
| 205 | +- All Premium features |
| 206 | +- Exam prediction ✓ |
| 207 | +- Assignment help ✓ |
| 208 | +- 7-day free trial |
| 209 | + |
| 210 | +### Modifying Subscription Plans |
| 211 | + |
| 212 | +To add or modify plans: |
| 213 | + |
| 214 | +1. Update `apps/api/src/config/pricing.ts` |
| 215 | +2. Create corresponding products/prices in Stripe Dashboard |
| 216 | +3. Add price IDs to environment variables |
| 217 | +4. Update frontend pricing page |
| 218 | +5. Update feature gating logic |
| 219 | + |
| 220 | +## 🔒 Security |
| 221 | + |
| 222 | +### Best Practices |
| 223 | + |
| 224 | +1. **Never expose secret keys**: |
| 225 | + - Keep `STRIPE_SECRET_KEY` server-side only |
| 226 | + - Only use `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` on frontend |
| 227 | + |
| 228 | +2. **Verify webhooks**: |
| 229 | + - All webhook events are signature-verified |
| 230 | + - Invalid signatures are rejected automatically |
| 231 | + |
| 232 | +3. **Validate subscriptions**: |
| 233 | + - Always check subscription status server-side |
| 234 | + - Don't trust client-side subscription claims |
| 235 | + |
| 236 | +4. **Use HTTPS in production**: |
| 237 | + - Stripe requires HTTPS for webhooks |
| 238 | + - Never use HTTP in production |
| 239 | + |
| 240 | +5. **Secure customer data**: |
| 241 | + - All payment info is handled by Stripe |
| 242 | + - Never store raw credit card data |
| 243 | + - Follow PCI compliance guidelines |
| 244 | + |
| 245 | +## 📊 Monitoring |
| 246 | + |
| 247 | +### Stripe Dashboard |
| 248 | + |
| 249 | +Monitor your subscriptions in Stripe Dashboard: |
| 250 | + |
| 251 | +1. **Subscriptions**: View all active/canceled subscriptions |
| 252 | +2. **Customers**: See customer payment methods and history |
| 253 | +3. **Invoices**: Track all invoices and payments |
| 254 | +4. **Payments**: Monitor payment intents and failures |
| 255 | +5. **Events**: View all webhook events and delivery status |
| 256 | + |
| 257 | +### Database Queries |
| 258 | + |
| 259 | +Check subscription data in your database: |
| 260 | + |
| 261 | +```sql |
| 262 | +-- Get all active subscriptions |
| 263 | +SELECT u.email, u.subscriptionTier, u.subscriptionStatus, u.subscriptionEnd |
| 264 | +FROM "User" u |
| 265 | +WHERE u.subscriptionStatus = 'ACTIVE'; |
| 266 | + |
| 267 | +-- Get subscription history |
| 268 | +SELECT s.*, u.email |
| 269 | +FROM "Subscription" s |
| 270 | +JOIN "User" u ON s.userId = u.id |
| 271 | +ORDER BY s.createdAt DESC; |
| 272 | + |
| 273 | +-- Get payment history |
| 274 | +SELECT p.*, u.email |
| 275 | +FROM "Payment" p |
| 276 | +JOIN "User" u ON p.userId = u.id |
| 277 | +WHERE p.status = 'SUCCEEDED' |
| 278 | +ORDER BY p.createdAt DESC; |
| 279 | +``` |
| 280 | + |
| 281 | +## 🚨 Troubleshooting |
| 282 | + |
| 283 | +### Webhook Not Receiving Events |
| 284 | + |
| 285 | +1. Check webhook endpoint URL is correct |
| 286 | +2. Ensure endpoint is publicly accessible |
| 287 | +3. Verify webhook secret is correct |
| 288 | +4. Check API logs for errors |
| 289 | +5. Test webhook in Stripe Dashboard |
| 290 | + |
| 291 | +### Subscription Not Updating |
| 292 | + |
| 293 | +1. Check webhook delivery in Stripe Dashboard |
| 294 | +2. Verify webhook event was processed (check API logs) |
| 295 | +3. Ensure database connection is working |
| 296 | +4. Check for errors in webhook handler |
| 297 | + |
| 298 | +### Payment Failed |
| 299 | + |
| 300 | +1. Check Stripe Dashboard for decline reason |
| 301 | +2. Verify test card numbers are correct |
| 302 | +3. Ensure customer has valid payment method |
| 303 | +4. Check for insufficient funds or card errors |
| 304 | + |
| 305 | +### Feature Gating Not Working |
| 306 | + |
| 307 | +1. Verify user's subscription tier in database |
| 308 | +2. Check subscription status is ACTIVE |
| 309 | +3. Ensure feature gating middleware is applied |
| 310 | +4. Check pricing configuration is correct |
| 311 | + |
| 312 | +## 📚 Resources |
| 313 | + |
| 314 | +- [Stripe Documentation](https://stripe.com/docs) |
| 315 | +- [Stripe API Reference](https://stripe.com/docs/api) |
| 316 | +- [Stripe Webhooks Guide](https://stripe.com/docs/webhooks) |
| 317 | +- [Stripe Testing](https://stripe.com/docs/testing) |
| 318 | +- [Stripe Billing Best Practices](https://stripe.com/docs/billing/subscriptions/best-practices) |
| 319 | + |
| 320 | +## 🎯 Success Criteria |
| 321 | + |
| 322 | +Your payment system is properly configured when: |
| 323 | + |
| 324 | +- ✅ Users can subscribe via Stripe Checkout |
| 325 | +- ✅ Subscriptions automatically update in database |
| 326 | +- ✅ Webhooks are received and processed |
| 327 | +- ✅ Feature gating works correctly |
| 328 | +- ✅ Billing portal allows subscription management |
| 329 | +- ✅ Invoice history is accessible |
| 330 | +- ✅ Payment failures are handled gracefully |
| 331 | +- ✅ Free trials work as expected |
| 332 | +- ✅ Student discounts are applied correctly |
| 333 | +- ✅ Upgrade/downgrade flows function properly |
| 334 | + |
| 335 | +## 📞 Support |
| 336 | + |
| 337 | +For issues or questions: |
| 338 | + |
| 339 | +1. Check this documentation |
| 340 | +2. Review Stripe logs in Dashboard |
| 341 | +3. Check API server logs |
| 342 | +4. Consult Stripe support: https://support.stripe.com |
| 343 | +5. Contact development team |
| 344 | + |
| 345 | +--- |
| 346 | + |
| 347 | +**SSC-16 Implementation Complete!** 🎉 |
| 348 | + |
| 349 | +This payment system enables StudySync to: |
| 350 | +- Generate revenue through subscriptions |
| 351 | +- Provide tiered feature access |
| 352 | +- Manage billing automatically |
| 353 | +- Track payments and invoices |
| 354 | +- Enforce usage limits |
| 355 | +- Deliver premium value to paying users |
0 commit comments