The payment system is already integrated into the StrellerMinds Backend. To get started:
-
Install dependencies:
npm install
-
Configure environment variables:
cp .env.example .env.local
-
Set payment gateway credentials:
# Stripe STRIPE_SECRET_KEY=sk_test_your_key STRIPE_PUBLIC_KEY=pk_test_your_key STRIPE_WEBHOOK_SECRET=whsec_your_secret # PayPal PAYPAL_CLIENT_ID=your_client_id PAYPAL_SECRET=your_secret PAYPAL_MODE=sandbox
-
Run database migrations:
npm run typeorm migration:run
-
Start the server:
npm run start:dev
- Payment Gateway Integration - Stripe and PayPal support
- Subscription Engine - Recurring billing management
- Invoicing System - Automatic invoice generation
- Tax Calculation - Multi-jurisdiction tax support
- Financial Reporting - Comprehensive analytics
- Dispute Management - Chargeback and dispute handling
User Payment Request
↓
Payment Service
├─→ Stripe Service / PayPal Service
│ ↓
│ Payment Gateway
├─→ Payment Repository
├─→ Invoice Service
├─→ Subscription Service
└─→ Tax Calculation Service
↓
Webhook Events (async)
↓
Database Update
curl -X POST http://localhost:3000/payments/initialize \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": 99.99,
"currency": "USD",
"paymentMethod": "stripe"
}'curl -X POST http://localhost:3000/subscriptions \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"paymentPlanId": "plan-uuid",
"billingCycle": "monthly"
}'curl -X POST http://localhost:3000/tax/calculate \
-H "Content-Type: application/json" \
-d '{
"amount": 100.00,
"country": "US",
"state": "CA"
}'curl -X POST http://localhost:3000/financial-reports \
-H "Content-Type: application/json" \
-d '{
"reportType": "revenue",
"period": "monthly",
"startDate": "2024-01-01T00:00:00Z",
"endDate": "2024-01-31T23:59:59Z"
}'PENDING → Processing state waiting for confirmation
PROCESSING → Payment is being processed
COMPLETED → Successfully completed
FAILED → Payment failed
CANCELLED → User cancelled the payment
REFUNDED → Refund has been processed
DISPUTED → Payment is under dispute
PENDING → Waiting for first payment
ACTIVE → Active subscription
PAUSED → Temporarily paused
CANCELLED → Cancelled by user
EXPIRED → Subscription expired
FAILED → Payment failed
DRAFT → Draft mode, not sent to customer
ISSUED → Invoice created
SENT → Invoice sent to customer
VIEWED → Customer viewed invoice
PARTIALLY_PAID → Partial payment received
PAID → Fully paid
OVERDUE → Past due date
CANCELLED → Invoice cancelled
REFUNDED → Refund issued
- United States: Sales tax by state
- European Union: VAT
- Canada: GST/PST by province
- Australia: GST
curl -X POST http://localhost:3000/tax/rates \
-H "Content-Type: application/json" \
-d '{
"country": "US",
"state": "CA",
"rate": 8.625,
"type": "Sales Tax"
}'- Go to Stripe Dashboard → Webhooks
- Add endpoint:
https://yourdomain.com/webhooks/stripe - Copy webhook secret to
STRIPE_WEBHOOK_SECRET - Select events:
payment_intent.succeededpayment_intent.payment_failedcustomer.subscription.*charge.refundedcharge.dispute.created
- Go to PayPal Developer Dashboard → Webhooks
- Create webhook for:
https://yourdomain.com/webhooks/paypal - Subscribe to events:
CHECKOUT.ORDER.COMPLETEDBILLING.SUBSCRIPTION.*PAYMENT.CAPTURE.REFUNDED
- Revenue Report - Total sales, transaction count, average value
- Refund Report - Refund amounts, counts, refund rates
- Tax Report - Tax collected, effective rates, compliance status
- Reconciliation Report - Complete financial reconciliation
// Generate revenue report
const report = await paymentService.generateReport({
reportType: 'revenue',
period: 'monthly',
startDate: new Date('2024-01-01'),
endDate: new Date('2024-01-31')
});
// Get specific report
const retrieved = await paymentService.getReport(report.id);
// List all reports
const all = await paymentService.listReports('monthly');- Stripe Card - Credit and debit cards
- PayPal - PayPal wallet
- Bank Transfer - Direct bank transfers
- Cryptocurrency - Bitcoin, Ethereum (future)
curl -X POST http://localhost:3000/payments/methods \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"type": "card",
"provider": "stripe",
"externalId": "pm_1234567890abcdef",
"last4": "4242",
"brand": "visa",
"isDefault": true
}'curl -X POST http://localhost:3000/payments/uuid/refund \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": 50.00,
"reason": "Quality issues"
}'REQUESTED- Refund requestedAPPROVED- Refund approvedPROCESSING- Being processed by gatewayCOMPLETED- Successfully refundedFAILED- Refund failedREJECTED- Refund rejected
curl -X POST http://localhost:3000/disputes \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"paymentId": "payment-uuid",
"reason": "Unauthorized transaction",
"description": "I did not authorize this charge"
}'curl -X POST http://localhost:3000/disputes/uuid/evidence \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"evidence": [
"data:image/png;base64,...",
"data:application/pdf;base64,..."
]
}'INITIATED- Dispute just createdUNDER_REVIEW- Evidence submitted and under reviewRESOLVED- Dispute resolvedWON- Dispute won in favor of customerLOST- Dispute lostAPPEALED- Appealing a lost dispute
- payments - Payment transactions
- subscriptions - Active subscriptions
- payment_plans - Subscription plans
- invoices - Invoice documents
- refunds - Refund tracking
- disputes - Dispute records
- tax_rates - Tax rate configuration
- financial_reports - Generated reports
- payment_methods - Stored payment methods
Indexes created on:
payments.userIdpayments.statussubscriptions.userIdsubscriptions.statusinvoices.userIdinvoices.status
{
"statusCode": 400,
"message": "Payment amount must be greater than 0",
"error": "BadRequestException"
}{
"statusCode": 401,
"message": "Unauthorized access",
"error": "UnauthorizedException"
}{
"statusCode": 404,
"message": "Payment not found",
"error": "NotFoundException"
}# Unit tests
npm run test
# Test coverage
npm run test:cov
# Watch mode
npm run test:watchpayment.service.spec.tssubscription.service.spec.tstax-calculation.service.spec.ts
All payment operations are logged with:
- Request details
- Response outcomes
- Error messages
- Execution time
- User identification
Enable detailed logging:
NODE_ENV=development- Payment Processing - Async webhook processing
- Billing Cycles - Batch processing for recurring billing
- Report Generation - Scheduled off-peak generation
- Database Queries - Optimized with proper indexing
- Cache Strategy - Tax rates cached in memory
- Never log payment details - PII protection
- Use HTTPS everywhere - Encrypted communication
- Validate all inputs - Prevent injection attacks
- Verify webhooks - Signature verification
- Store secrets securely - Environment variables only
- Rate limiting - Prevent brute force attacks
- User isolation - Data belongs only to user
- Check webhook secret configuration
- Verify endpoint is publicly accessible
- Check firewall/security group settings
- Review webhook logs in payment gateway dashboard
- Verify payment method is valid
- Check next billing date calculation
- Review failed payment logs
- Ensure database migration ran successfully
- Verify tax rate exists for location
- Check country/state configuration
- Ensure tax rate is marked as active
- Review tax calculation logs
- Implement email service integration
- Configure email templates
- Check email provider credentials
- Review email logs
For issues or questions:
- Check PAYMENT_API.md for API reference
- Review PAYMENT_IMPLEMENTATION.md for technical details
- Check service logs for error details
- Contact payment gateway support teams
- v1.0.0 (2024-01-22) - Initial release
- Core payment processing
- Stripe and PayPal integration
- Subscription management
- Invoice generation
- Tax calculation
- Financial reporting
- Dispute handling
This project is licensed under UNLICENSED - All rights reserved