-
Notifications
You must be signed in to change notification settings - Fork 1
Stripe Integration
Payment processing and subscription management with Stripe
Complete Stripe integration for:
- One-time credit purchases
- Subscription plans
- Webhook event handling
- Automatic credit addition
- Referral bonus processing
Credit Model: 1 credit = $0.01 ($10 purchase = 1000 credits)
# Stripe Keys
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_PUBLISHABLE_KEY=pk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
# Frontend URL
FRONTEND_URL=http://localhost:3000curl -X POST http://localhost:8000/api/stripe/checkout-session \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": 1000,
"currency": "usd",
"description": "1000 credits purchase"
}'Response:
{
"session_id": "cs_test_...",
"url": "https://checkout.stripe.com/c/pay/...",
"payment_id": 1,
"status": "pending",
"amount": 1000,
"expires_at": "2024-12-16T10:30:00Z"
}GET /api/stripe/credit-packages
Returns available credit bundles (public, no auth).
POST /api/stripe/checkout-session
Request:
{
"amount": 1000,
"currency": "usd",
"description": "Optional description"
}Response: Session ID and checkout URL
GET /api/stripe/checkout-session/{session_id}
Fetch session details.
POST /api/stripe/payment-intent
GET /api/stripe/payment-intent/{id}
Create or retrieve PaymentIntent (alternative to checkout).
GET /api/stripe/payments # List all
GET /api/stripe/payments/{id} # Get specific
POST /api/stripe/webhook
Stripe calls this endpoint - must verify signature.
POST /api/stripe/refund
Requires admin auth.
- Go to Stripe Dashboard → Developers → Webhooks
- Add endpoint:
https://your-domain.com/api/stripe/webhook - Select events:
checkout.session.completedcheckout.session.expiredpayment_intent.succeededpayment_intent.payment_failedpayment_intent.canceledcharge.refunded
- Copy signing secret to
.envasSTRIPE_WEBHOOK_SECRET
Install Stripe CLI:
# macOS
brew install stripe/stripe-cli/stripe
# Windows
scoop install stripe
# Linux
See https://stripe.com/docs/stripe-cliForward webhooks:
# Login
stripe login
# Forward to local server
stripe listen --forward-to localhost:8000/api/stripe/webhookCopy the whsec_... secret to .env.
1. User creates checkout session
2. User completes payment at Stripe
3. Stripe sends webhook to /api/stripe/webhook
4. Backend verifies signature
5. Backend adds credits to user account
6. Backend creates payment record
7. If referral code used & first purchase:
→ Add bonus to both users
8. Mark payment as completed
credits = amount_in_cents / 100 # $10 = 1000 cents = 10.00 creditsIf user has referred_by_code and has_made_first_purchase = false:
- User gets: payment amount + $10 bonus
- Referrer gets: $10 bonus
- Only applied once (first purchase >= $10)
CREATE TABLE payments (
id INTEGER PRIMARY KEY,
user_id INTEGER,
amount NUMERIC, -- Amount in dollars
currency TEXT, -- 'usd'
status TEXT, -- 'pending', 'completed', 'failed', 'refunded'
stripe_session_id TEXT, -- Checkout session ID
stripe_payment_intent_id TEXT,
description TEXT,
created_at TIMESTAMP,
completed_at TIMESTAMP
);| Purpose | Number |
|---|---|
| Success | 4242 4242 4242 4242 |
| 3D Secure | 4000 0025 0000 3155 |
| Declined | 4000 0000 0000 9995 |
| Insufficient funds | 4000 0000 0000 9995 |
| Expired | 4000 0000 0000 0069 |
Use any future expiry, any CVC, any ZIP.
# Simulate successful payment
stripe trigger checkout.session.completed
# Simulate failed payment
stripe trigger payment_intent.payment_failed
# Simulate expired session
stripe trigger checkout.session.expired
# Simulate refund
stripe trigger charge.refunded# 1. Create session
SESSION=$(curl -X POST http://localhost:8000/api/stripe/checkout-session \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"amount":1000,"currency":"usd"}' | jq -r '.url')
# 2. Open checkout URL
echo "Complete payment at: $SESSION"
# 3. Verify credits added
curl http://localhost:8000/user/balance \
-H "Authorization: Bearer $API_KEY"
# 4. Check payment history
curl http://localhost:8000/api/stripe/payments \
-H "Authorization: Bearer $API_KEY"Location: src/routes/payments.py
checkout.session.completed:
- Extract user, amount, payment intent
- Add credits to user
- Apply referral bonus (if applicable)
- Create payment record
- Mark as completed
checkout.session.expired:
- Mark payment as expired
- Update status
payment_intent.succeeded:
- Confirm payment completed
- Update records
payment_intent.payment_failed:
- Mark payment as failed
- Log error
payment_intent.canceled:
- Mark as canceled
- Clean up session
charge.refunded:
- Deduct credits from user
- Mark payment as refunded
- Create refund record
import stripe
def verify_webhook(payload: bytes, signature: str):
try:
event = stripe.Webhook.construct_event(
payload, signature, webhook_secret
)
return event
except ValueError:
# Invalid payload
raise
except stripe.error.SignatureVerificationError:
# Invalid signature
raiseNever bypass signature verification in production!
- Always verify webhook signatures
- Use test keys in development
- Never expose secret keys in frontend
- Use HTTPS in production
- Validate amounts server-side
- Check payment status before granting access
- Implement idempotency for webhooks
- Log all payment events
Cause: Incorrect endpoint URL or firewall blocking
Solution:
- Check webhook endpoint in Stripe Dashboard
- Ensure URL is publicly accessible
- Verify webhook secret matches
.env - Check logs for incoming requests
Cause: Wrong webhook secret or modified payload
Solution:
- Copy fresh webhook secret from Stripe
- Update
STRIPE_WEBHOOK_SECRETin.env - Restart server
- Don't modify webhook payload before verification
Cause: Webhook not processed or failed
Solution:
- Check Stripe CLI output for errors
- Review webhook endpoint logs
- Verify user_id in session metadata
- Check database for payment record
- Look for errors in application logs
Cause: Webhook forwarding not running
Solution:
# Start webhook forwarding
stripe listen --forward-to localhost:8000/api/stripe/webhook- Switch to live API keys
- Configure production webhook endpoint
- Enable webhook event filtering
- Set up webhook monitoring/alerts
- Test end-to-end payment flow
- Verify credit calculations
- Test refund process
- Configure error notifications
- Set up payment analytics
- Document customer support procedures
- Referral System - Bonus application
- Subscription Plans - Recurring billing
- API Keys - Authentication
Last Updated: December 2024 Status: Production Ready
For questions: See Troubleshooting or Stripe Docs
- Subscription-Plans — Plan tiers, lifecycle, credit allocation
- Free-Trial-System — Trial limits and conversion to paid
- Coupon-System — Coupon redemption adds credits
- Referral-System — Referral bonuses add credits
- Features Acceptance Criteria — Acceptance criteria for Payments (Section 6)
Reading Path (start here, in order)
- Conceptual Model
- Stability Definition
- Conceptual Model Features
- Features
- Delta Report
- Features-Acceptance-Criteria
Testing
Security & Access
Billing
Monitoring
Features
Providers
Operations
Data References