Stripe Payment Integration - Implementation Plan
Overview
Integration of Stripe payment system with iDEAL and bank transfer support for token purchases. Users must be registered to purchase tokens, with both predefined packages and custom token amounts supported.
Key Requirements
- ✅ User must be registered to buy tokens
- ✅ Purchase modal on user's dashboard/profile page
- ✅ Support for predefined token packages
- ✅ Support for custom token amounts
- ✅ Dynamic pricing based on package discounts
- ✅ Support for iDEAL and bank transfer payments
Phase 1: Backend Foundation ✅ COMPLETED
1.1 Dependencies & Configuration ✅
- Install Stripe SDK:
npm install stripe @types/stripe - Add Stripe environment variables to
.env:STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_SECRET_KEY=sk_test_... STRIPE_WEBHOOK_SECRET=whsec_... - Update
env.examplewith Stripe configuration
1.2 Database Schema Updates ✅
- Create migration script for
payment_recordstable updates:- Add
stripe_payment_intent_id(VARCHAR(255)) - Add
stripe_payment_method_id(VARCHAR(255)) - Add
stripe_customer_id(VARCHAR(255)) - Add
payment_flow_type(ENUM: 'card', 'ideal', 'bank_transfer') - Add
stripe_metadata(JSON) - Add
refund_reason(TEXT) - Add
refunded_amount(DECIMAL(10,2)) - Add
custom_quantity(INT) - for custom token purchases - Add
applied_discount_percentage(DECIMAL(5,2)) - discount applied
- Add
- Create migration script for
userstable:- Add
stripe_customer_id(VARCHAR(255))
- Add
1.3 New Services ✅
StripeService (backend/src/services/StripeService.ts) ✅
- Create Stripe client initialization
createPaymentIntent(amount, currency, metadata)- Create payment intentcreateCustomer(userId, email, name)- Create Stripe customerconfirmPaymentIntent(paymentIntentId)- Confirm paymentcreateRefund(paymentIntentId, amount, reason)- Process refundsgetPaymentMethods(customerId)- Get saved payment methodscreateSetupIntent(customerId)- For saving payment methodsverifyWebhookSignature(payload, signature)- Webhook verificationgetAvailablePaymentMethods(countryCode)- Get payment methods by regiongetIdealConfiguration()- iDEAL bank configuration
PaymentService (backend/src/services/PaymentService.ts) ✅
createPaymentRecord(userId, packageId, customQuantity, amount)- Create payment recordprocessSuccessfulPayment(paymentIntentId)- Handle successful paymentprocessFailedPayment(paymentIntentId, reason)- Handle failed paymentcalculateTokenPrice(quantity, packageId)- Calculate price with discountsallocateTokens(userId, quantity, paymentId)- Add tokens to user accountgetUserPaymentHistory(userId)- Get user's payment historyrefundPayment(paymentId, amount, reason)- Process refundsgetPaymentStatistics()- Get payment analytics
1.4 New API Controllers ✅
PaymentController (backend/src/controllers/rest/PaymentController.ts) ✅
POST /api/payments/calculate-price- Calculate token pricingPOST /api/payments/create-intent- Create payment intent- Validate user authentication
- Calculate pricing (package vs custom)
- Create Stripe payment intent
- Save payment record as 'pending'
POST /api/payments/confirm- Confirm payment completion- Verify payment intent
- Update payment record
- Allocate tokens to user
GET /api/payments/methods- Get available payment methodsGET /api/payments/history- Get user payment historyGET /api/payments/:id- Get specific payment detailsPOST /api/payments/:id/refund- Process refunds (admin only)POST /api/payments/:id/cancel- Cancel paymentGET /api/payments/admin/statistics- Payment statistics (admin)
WebhookController (backend/src/controllers/rest/WebhookController.ts) ✅
POST /api/webhooks/stripe- Handle Stripe webhooks- Verify webhook signature
- Process
payment_intent.succeeded - Process
payment_intent.payment_failed - Process
payment_intent.cancelled - Process
charge.dispute.created - Process
customer.created - Process
invoice.payment_succeeded
POST /api/webhooks/stripe/health- Health check endpoint
1.5 Update Existing Services ✅
- Update
TokenService.ts:- Add
calculateCustomTokenPrice(quantity)method - Add
getBestPackageForQuantity(quantity)method - Add
addTokensToUserFromPayment()method
- Add
- Update
UserService.ts:- Add
getUserPaymentHistory(userId)method - Add
getUserByStripeCustomerId()method - Add
updateUserStripeCustomerId()method - Add
getUserPaymentStatistics()method
- Add
Phase 2: Frontend Integration ✅ COMPLETED
2.1 Dependencies & Configuration ✅
- Install Stripe React:
npm install @stripe/stripe-js @stripe/react-stripe-js - Add Stripe publishable key to environment variables
- Configure Stripe provider in app layout
2.2 New Components ✅
PaymentModal (frontend/src/components/PaymentModal.tsx) ✅
- Payment method selection (Card, iDEAL, Bank Transfer)
- Token quantity input (custom amount)
- Package selection with discount display
- Price calculation and display
- Payment form with Stripe Elements
- Loading states and error handling
TokenPurchaseFlow (frontend/src/components/TokenPurchaseFlow.tsx) ✅
- Package vs custom amount selection
- Dynamic pricing calculation
- Payment processing flow
- Success/failure handling
- Token allocation confirmation
PaymentHistory (frontend/src/components/PaymentHistory.tsx) ✅
- List of past payments
- Payment status indicators
- Receipt download links
- Refund information (if applicable)
CustomTokenCalculator (frontend/src/components/CustomTokenCalculator.tsx) ✅
- Quantity input with validation
- Real-time price calculation
- Discount percentage display
- Package comparison tooltips
StripeProvider (frontend/src/components/StripeProvider.tsx) ✅
- Stripe Elements provider wrapper
- Environment configuration
2.3 Update Existing Components ✅
Dashboard Page (frontend/src/app/dashboard/page.tsx)
- Add "Buy Tokens" button/CTA
- Display current token balance prominently
- Add payment history section
Header Component (frontend/src/components/Header.tsx) ✅
- Add "Buy Tokens" button in header
- Add payment history button
- Update token display with purchase option
- Integrate payment modals
Layout (frontend/src/app/layout.tsx) ✅
- Add StripeProvider wrapper
- Configure Stripe environment
2.4 New Pages ✅
Payment Success Page (frontend/src/app/payment/success/page.tsx) ✅
- Payment confirmation
- Token allocation summary
- Next steps guidance
Payment Failed Page (frontend/src/app/payment/failed/page.tsx) ✅
- Error explanation
- Retry options
- Support contact information
Phase 3: Payment Methods Implementation ✅ COMPLETED
3.1 Credit/Debit Cards ✅
- Stripe Elements integration
- Card validation
- 3D Secure authentication
- Real-time payment confirmation
3.2 iDEAL (Netherlands) ✅
- iDEAL bank selection interface
- Redirect-based payment flow
- Webhook confirmation handling
- Bank-specific error handling
3.3 Bank Transfer (SEPA) ✅
- SEPA Direct Debit setup
- Mandate collection form
- Delayed payment confirmation
- Webhook-based status updates
Phase 4: Pricing & Discount Logic ✅ COMPLETED
4.1 Dynamic Pricing System ✅
- Create
PricingService.ts:calculatePrice(quantity, packageId?)- Calculate final pricegetBestDiscount(quantity)- Find best applicable discountgetPackageRecommendation(quantity)- Recommend best package
- Update token packages to support custom quantities
- Implement tiered pricing logic
4.2 Discount Application ✅
- Package-based discounts for predefined quantities
- Volume discounts for custom quantities
- Display savings compared to single token price
- Clear pricing breakdown in UI
Phase 5: User Experience & UI ✅ COMPLETED
5.1 Purchase Flow Design ✅
- Step 1: Token quantity selection (package or custom)
- Step 2: Payment method selection
- Step 3: Payment details and confirmation
- Step 4: Payment processing with progress indicator
- Step 5: Success confirmation with token allocation
5.2 Error Handling ✅
- Payment failure messages
- Network error handling
- Timeout handling
- Retry mechanisms
- Support contact integration
5.3 Loading States ✅
- Payment processing indicators
- Progress tracking
- Skeleton loaders
- Disabled states during processing
Phase 6: Testing & Quality Assurance
6.1 Stripe Test Mode
- Test payment methods with Stripe test cards
- Test iDEAL flow with test banks
- Test SEPA with test accounts
- Webhook testing with Stripe CLI
6.2 Integration Testing
- End-to-end payment flows
- Webhook processing verification
- Token allocation testing
- Error scenario testing
6.3 User Acceptance Testing
- Payment flow usability
- Error message clarity
- Mobile responsiveness
- Cross-browser compatibility
Phase 7: Security & Compliance
7.1 Security Implementation
- Webhook signature verification
- PCI compliance through Stripe
- Secure token storage
- Rate limiting on payment endpoints
- Input validation and sanitization
7.2 Data Protection
- GDPR compliance for EU users
- Secure handling of payment data
- Audit logging for all transactions
- Data retention policies
Phase 8: Monitoring & Analytics
8.1 Payment Metrics
- Success/failure rates by payment method
- Average transaction values
- Conversion rates from package selection to payment
- User payment behavior analytics
8.2 Error Tracking
- Failed payment reasons tracking
- Webhook processing errors
- User experience issues
- Performance monitoring
Phase 9: Documentation & Deployment
9.1 Documentation
- API documentation for payment endpoints
- User guide for token purchasing
- Admin guide for payment management
- Webhook documentation
9.2 Deployment
- Staging environment setup
- Production deployment plan
- Database migration scripts
- Environment configuration
- Stripe webhook endpoint configuration
Phase 10: Post-Launch
10.1 Monitoring
- Payment success rate monitoring
- Error rate tracking
- User feedback collection
- Performance optimization
10.2 Iterations
- A/B testing for payment flow
- User experience improvements
- Additional payment methods if needed
- Feature enhancements based on usage
Technical Specifications
Database Schema Updates
ALTER TABLE payment_records
ADD COLUMN stripe_payment_intent_id VARCHAR(255),
ADD COLUMN stripe_payment_method_id VARCHAR(255),
ADD COLUMN stripe_customer_id VARCHAR(255),
ADD COLUMN payment_flow_type ENUM('card', 'ideal', 'bank_transfer'),
ADD COLUMN stripe_metadata JSON,
ADD COLUMN refund_reason TEXT,
ADD COLUMN refunded_amount DECIMAL(10,2),
ADD COLUMN custom_quantity INT,
ADD COLUMN applied_discount_percentage DECIMAL(5,2);
API Endpoints
POST /api/payments/create-intent- Create payment intentPOST /api/payments/confirm- Confirm paymentGET /api/payments/methods- Get payment methodsGET /api/user/payments- User payment historyPOST /api/webhooks/stripe- Stripe webhooks
Environment Variables
STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
Success Criteria
- Users can purchase tokens with custom quantities
- All three payment methods (Card, iDEAL, Bank Transfer) work
- Dynamic pricing with package discounts functions correctly
- Payment success rate > 95%
- User experience is smooth and intuitive
- All security requirements are met
- Webhook processing is reliable
- Mobile experience is optimized