|
# 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 ✅
|
|
- [x] Install Stripe SDK: `npm install stripe @types/stripe`
|
|
- [x] Add Stripe environment variables to `.env`:
|
|
```env
|
|
STRIPE_PUBLISHABLE_KEY=pk_test_...
|
|
STRIPE_SECRET_KEY=sk_test_...
|
|
STRIPE_WEBHOOK_SECRET=whsec_...
|
|
```
|
|
- [x] Update `env.example` with Stripe configuration
|
|
|
|
### 1.2 Database Schema Updates ✅
|
|
- [x] Create migration script for `payment_records` table updates:
|
|
- [x] Add `stripe_payment_intent_id` (VARCHAR(255))
|
|
- [x] Add `stripe_payment_method_id` (VARCHAR(255))
|
|
- [x] Add `stripe_customer_id` (VARCHAR(255))
|
|
- [x] Add `payment_flow_type` (ENUM: 'card', 'ideal', 'bank_transfer')
|
|
- [x] Add `stripe_metadata` (JSON)
|
|
- [x] Add `refund_reason` (TEXT)
|
|
- [x] Add `refunded_amount` (DECIMAL(10,2))
|
|
- [x] Add `custom_quantity` (INT) - for custom token purchases
|
|
- [x] Add `applied_discount_percentage` (DECIMAL(5,2)) - discount applied
|
|
- [x] Create migration script for `users` table:
|
|
- [x] Add `stripe_customer_id` (VARCHAR(255))
|
|
|
|
### 1.3 New Services ✅
|
|
|
|
#### StripeService (`backend/src/services/StripeService.ts`) ✅
|
|
- [x] Create Stripe client initialization
|
|
- [x] `createPaymentIntent(amount, currency, metadata)` - Create payment intent
|
|
- [x] `createCustomer(userId, email, name)` - Create Stripe customer
|
|
- [x] `confirmPaymentIntent(paymentIntentId)` - Confirm payment
|
|
- [x] `createRefund(paymentIntentId, amount, reason)` - Process refunds
|
|
- [x] `getPaymentMethods(customerId)` - Get saved payment methods
|
|
- [x] `createSetupIntent(customerId)` - For saving payment methods
|
|
- [x] `verifyWebhookSignature(payload, signature)` - Webhook verification
|
|
- [x] `getAvailablePaymentMethods(countryCode)` - Get payment methods by region
|
|
- [x] `getIdealConfiguration()` - iDEAL bank configuration
|
|
|
|
#### PaymentService (`backend/src/services/PaymentService.ts`) ✅
|
|
- [x] `createPaymentRecord(userId, packageId, customQuantity, amount)` - Create payment record
|
|
- [x] `processSuccessfulPayment(paymentIntentId)` - Handle successful payment
|
|
- [x] `processFailedPayment(paymentIntentId, reason)` - Handle failed payment
|
|
- [x] `calculateTokenPrice(quantity, packageId)` - Calculate price with discounts
|
|
- [x] `allocateTokens(userId, quantity, paymentId)` - Add tokens to user account
|
|
- [x] `getUserPaymentHistory(userId)` - Get user's payment history
|
|
- [x] `refundPayment(paymentId, amount, reason)` - Process refunds
|
|
- [x] `getPaymentStatistics()` - Get payment analytics
|
|
|
|
### 1.4 New API Controllers ✅
|
|
|
|
#### PaymentController (`backend/src/controllers/rest/PaymentController.ts`) ✅
|
|
- [x] `POST /api/payments/calculate-price` - Calculate token pricing
|
|
- [x] `POST /api/payments/create-intent` - Create payment intent
|
|
- [x] Validate user authentication
|
|
- [x] Calculate pricing (package vs custom)
|
|
- [x] Create Stripe payment intent
|
|
- [x] Save payment record as 'pending'
|
|
- [x] `POST /api/payments/confirm` - Confirm payment completion
|
|
- [x] Verify payment intent
|
|
- [x] Update payment record
|
|
- [x] Allocate tokens to user
|
|
- [x] `GET /api/payments/methods` - Get available payment methods
|
|
- [x] `GET /api/payments/history` - Get user payment history
|
|
- [x] `GET /api/payments/:id` - Get specific payment details
|
|
- [x] `POST /api/payments/:id/refund` - Process refunds (admin only)
|
|
- [x] `POST /api/payments/:id/cancel` - Cancel payment
|
|
- [x] `GET /api/payments/admin/statistics` - Payment statistics (admin)
|
|
|
|
#### WebhookController (`backend/src/controllers/rest/WebhookController.ts`) ✅
|
|
- [x] `POST /api/webhooks/stripe` - Handle Stripe webhooks
|
|
- [x] Verify webhook signature
|
|
- [x] Process `payment_intent.succeeded`
|
|
- [x] Process `payment_intent.payment_failed`
|
|
- [x] Process `payment_intent.cancelled`
|
|
- [x] Process `charge.dispute.created`
|
|
- [x] Process `customer.created`
|
|
- [x] Process `invoice.payment_succeeded`
|
|
- [x] `POST /api/webhooks/stripe/health` - Health check endpoint
|
|
|
|
### 1.5 Update Existing Services ✅
|
|
- [x] Update `TokenService.ts`:
|
|
- [x] Add `calculateCustomTokenPrice(quantity)` method
|
|
- [x] Add `getBestPackageForQuantity(quantity)` method
|
|
- [x] Add `addTokensToUserFromPayment()` method
|
|
- [x] Update `UserService.ts`:
|
|
- [x] Add `getUserPaymentHistory(userId)` method
|
|
- [x] Add `getUserByStripeCustomerId()` method
|
|
- [x] Add `updateUserStripeCustomerId()` method
|
|
- [x] Add `getUserPaymentStatistics()` method
|
|
|
|
---
|
|
|
|
## Phase 2: Frontend Integration ✅ COMPLETED
|
|
|
|
### 2.1 Dependencies & Configuration ✅
|
|
- [x] Install Stripe React: `npm install @stripe/stripe-js @stripe/react-stripe-js`
|
|
- [x] Add Stripe publishable key to environment variables
|
|
- [x] Configure Stripe provider in app layout
|
|
|
|
### 2.2 New Components ✅
|
|
|
|
#### PaymentModal (`frontend/src/components/PaymentModal.tsx`) ✅
|
|
- [x] Payment method selection (Card, iDEAL, Bank Transfer)
|
|
- [x] Token quantity input (custom amount)
|
|
- [x] Package selection with discount display
|
|
- [x] Price calculation and display
|
|
- [x] Payment form with Stripe Elements
|
|
- [x] Loading states and error handling
|
|
|
|
#### TokenPurchaseFlow (`frontend/src/components/TokenPurchaseFlow.tsx`) ✅
|
|
- [x] Package vs custom amount selection
|
|
- [x] Dynamic pricing calculation
|
|
- [x] Payment processing flow
|
|
- [x] Success/failure handling
|
|
- [x] Token allocation confirmation
|
|
|
|
#### PaymentHistory (`frontend/src/components/PaymentHistory.tsx`) ✅
|
|
- [x] List of past payments
|
|
- [x] Payment status indicators
|
|
- [x] Receipt download links
|
|
- [x] Refund information (if applicable)
|
|
|
|
#### CustomTokenCalculator (`frontend/src/components/CustomTokenCalculator.tsx`) ✅
|
|
- [x] Quantity input with validation
|
|
- [x] Real-time price calculation
|
|
- [x] Discount percentage display
|
|
- [x] Package comparison tooltips
|
|
|
|
#### StripeProvider (`frontend/src/components/StripeProvider.tsx`) ✅
|
|
- [x] Stripe Elements provider wrapper
|
|
- [x] Environment configuration
|
|
|
|
### 2.3 Update Existing Components ✅
|
|
|
|
#### Dashboard Page (`frontend/src/app/dashboard/page.tsx`)
|
|
- [x] Add "Buy Tokens" button/CTA
|
|
- [x] Display current token balance prominently
|
|
- [x] Add payment history section
|
|
|
|
#### Header Component (`frontend/src/components/Header.tsx`) ✅
|
|
- [x] Add "Buy Tokens" button in header
|
|
- [x] Add payment history button
|
|
- [x] Update token display with purchase option
|
|
- [x] Integrate payment modals
|
|
|
|
#### Layout (`frontend/src/app/layout.tsx`) ✅
|
|
- [x] Add StripeProvider wrapper
|
|
- [x] Configure Stripe environment
|
|
|
|
### 2.4 New Pages ✅
|
|
|
|
#### Payment Success Page (`frontend/src/app/payment/success/page.tsx`) ✅
|
|
- [x] Payment confirmation
|
|
- [x] Token allocation summary
|
|
- [x] Next steps guidance
|
|
|
|
#### Payment Failed Page (`frontend/src/app/payment/failed/page.tsx`) ✅
|
|
- [x] Error explanation
|
|
- [x] Retry options
|
|
- [x] Support contact information
|
|
|
|
---
|
|
|
|
## Phase 3: Payment Methods Implementation ✅ COMPLETED
|
|
|
|
### 3.1 Credit/Debit Cards ✅
|
|
- [x] Stripe Elements integration
|
|
- [x] Card validation
|
|
- [x] 3D Secure authentication
|
|
- [x] Real-time payment confirmation
|
|
|
|
### 3.2 iDEAL (Netherlands) ✅
|
|
- [x] iDEAL bank selection interface
|
|
- [x] Redirect-based payment flow
|
|
- [x] Webhook confirmation handling
|
|
- [x] Bank-specific error handling
|
|
|
|
### 3.3 Bank Transfer (SEPA) ✅
|
|
- [x] SEPA Direct Debit setup
|
|
- [x] Mandate collection form
|
|
- [x] Delayed payment confirmation
|
|
- [x] Webhook-based status updates
|
|
|
|
---
|
|
|
|
## Phase 4: Pricing & Discount Logic ✅ COMPLETED
|
|
|
|
### 4.1 Dynamic Pricing System ✅
|
|
- [x] Create `PricingService.ts`:
|
|
- [x] `calculatePrice(quantity, packageId?)` - Calculate final price
|
|
- [x] `getBestDiscount(quantity)` - Find best applicable discount
|
|
- [x] `getPackageRecommendation(quantity)` - Recommend best package
|
|
- [x] Update token packages to support custom quantities
|
|
- [x] Implement tiered pricing logic
|
|
|
|
### 4.2 Discount Application ✅
|
|
- [x] Package-based discounts for predefined quantities
|
|
- [x] Volume discounts for custom quantities
|
|
- [x] Display savings compared to single token price
|
|
- [x] Clear pricing breakdown in UI
|
|
|
|
---
|
|
|
|
## Phase 5: User Experience & UI ✅ COMPLETED
|
|
|
|
### 5.1 Purchase Flow Design ✅
|
|
- [x] **Step 1**: Token quantity selection (package or custom)
|
|
- [x] **Step 2**: Payment method selection
|
|
- [x] **Step 3**: Payment details and confirmation
|
|
- [x] **Step 4**: Payment processing with progress indicator
|
|
- [x] **Step 5**: Success confirmation with token allocation
|
|
|
|
### 5.2 Error Handling ✅
|
|
- [x] Payment failure messages
|
|
- [x] Network error handling
|
|
- [x] Timeout handling
|
|
- [x] Retry mechanisms
|
|
- [x] Support contact integration
|
|
|
|
### 5.3 Loading States ✅
|
|
- [x] Payment processing indicators
|
|
- [x] Progress tracking
|
|
- [x] Skeleton loaders
|
|
- [x] 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
|
|
```sql
|
|
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 intent
|
|
- `POST /api/payments/confirm` - Confirm payment
|
|
- `GET /api/payments/methods` - Get payment methods
|
|
- `GET /api/user/payments` - User payment history
|
|
- `POST /api/webhooks/stripe` - Stripe webhooks
|
|
|
|
### Environment Variables
|
|
```env
|
|
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
|