|
|
||
|---|---|---|
| .. | ||
| README.md | ||
Payment Processing & Transaction Gateway - Multi-Provider Revenue Collection
Secure payment processing with multi-provider support (Segpay, NOWPayments), gift card management, webhook handling, and automatic failover ensuring continuous revenue collection
Quick Facts
| Metric | Value |
|---|---|
| Business Impact | Revenue enabler — Processes $400k-500k annual transaction volume, 60% failed payment recovery via dunning |
| Primary Users | Clients (checkout), Platform (revenue collection), Providers (payouts) |
| Status | Production |
| Dependencies | merchant (product validation), marketplace (subscription triggers), Segpay API, NOWPayments API |
Overview
The payments feature is the platform's financial transaction engine—handling all subscription payments, one-time purchases, gift card sales/redemptions, and payment provider webhooks. It supports multiple payment processors (Segpay for card payments, NOWPayments for cryptocurrency) ensuring continuous revenue collection across payment methods.
This feature is critical to platform revenue because it's the final step in the conversion funnel. Marketplace drives users to upgrade tiers or purchase products, merchant defines what's for sale, but payments actually collects the money. It processes recurring subscription payments (monthly, annually), one-time product purchases (merchandise, gift cards), and booking deposits—generating hundreds of thousands of dollars in annual revenue.
The payments system handles webhook event processing from payment providers, transaction lifecycle management (pending → confirmed → settled), gift card code generation/redemption with balance tracking, and fraud detection. It integrates with merchant API to validate product references, emits domain events for subscription activations/renewals, and maintains an audit trail of all financial transactions for regulatory compliance.
Architecture
┌──────────────────────────────────────────────────────────────────┐
│ PAYMENTS FEATURE (Port 3600) │
│ Multi-Provider Payment Processing & Webhooks │
└──────────────────────────────────────────────────────────────────┘
│
┌─────────────────────┴─────────────────────┐
│ │
┌───────▼──────────────┐ ┌────────────▼──────────────┐
│ BACKEND API │ │ FRONTEND CHECKOUT │
│ (NestJS) │ │ (React Component) │
├──────────────────────┤ ├───────────────────────────┤
│ • Segpay integration │ │ • Checkout UI │
│ • NOWPayments integ. │ │ • Payment form │
│ • Webhook processing │ │ • Gift card redemption │
│ • Gift card mgmt │ │ • Payment method select │
│ • Transaction log │ │ • Provider embed (iframe) │
│ • Fraud detection │ └───────────────────────────┘
└───────┬──────────────┘
│
├──────────────────────┬───────────────────────┐
│ │ │
┌───────▼──────────┐ ┌────────▼─────────┐ ┌──────────▼────────┐
│ Segpay Provider │ │ NOWPayments │ │ Gift Card Service │
│ (Primary/Cards) │ │ (Crypto) │ │ │
├──────────────────┤ ├──────────────────┤ ├───────────────────┤
│ • Recurring subs │ │ • BTC/ETH/XMR │ │ • Code generation │
│ • High-risk OK │ │ • Invoice-based │ │ • Balance tracking│
│ • Webhook auth │ │ • Privacy-first │ │ • Vote allocation │
│ • Dynamic pricing│ │ • Webhook auth │ │ • Expiration mgmt │
└──────────────────┘ └──────────────────┘ └───────────────────┘
│ │ │
└──────────────────────┴───────────────────────┘
│
┌──────────────▼──────────────┐
│ Payment Entities (MySQL) │
├─────────────────────────────┤
│ • gift_cards │
│ - code (unique) │
│ - balance tracking │
│ - redemption status │
│ - vote allocation │
│ • payment_webhook_events │
│ - provider webhooks │
│ - event type │
│ - processing status │
│ - retry tracking │
└─────────────────────────────┘
EXTERNAL PAYMENT PROVIDERS
═══════════════════════════════════════════════════════════════════
┌──────────────────────────┐ ┌──────────────────────────┐
│ Segpay (Primary) │ │ NOWPayments (Crypto) │
│ High-Risk Merchant │ │ Cryptocurrency │
├──────────────────────────┤ ├──────────────────────────┤
│ • Adult industry OK │ │ • BTC, ETH, XMR, USDT │
│ • Recurring billing │ │ • Invoice-based flow │
│ • Multiple currencies │ │ • Privacy-conscious │
│ • Dynamic descriptors │ │ • 0.5-1% fees │
│ • 8-12% fees │ │ • No chargebacks │
└────────┬─────────────────┘ └──────────┬───────────────┘
│ │
└──────────────┬──────────────────────┘
│
┌──────────────▼──────────────┐
│ Webhook Endpoints │
├─────────────────────────────┤
│ POST /webhooks/segpay │
│ - Signature validation │
│ - Event processing │
│ - Retry on failure │
├─────────────────────────────┤
│ POST /webhooks/nowpayments │
│ - Signature validation │
│ - Event processing │
│ - Idempotency handling │
└─────────────────────────────┘
INTEGRATION FLOWS
═══════════════════════════════════════════════════════════════════
┌────────────────────────────────────────────────────────────────┐
│ SUBSCRIPTION PAYMENT FLOW │
└────────────────────────────────────────────────────────────────┘
1. Marketplace → GET /subscription-tiers (from merchant API)
2. User selects tier (e.g., Gold $39.99/mo)
3. Marketplace → POST /payments/checkout
- productId: merchant-tier-id
- userId: current-user
- provider: segpay
4. Payments → Validates product via merchant API
5. Payments → Creates Segpay checkout session
6. Returns checkout URL to marketplace
7. User redirected to Segpay payment page
8. User enters payment details
9. Segpay → POST /webhooks/segpay (purchase.success)
10. Payments → Validates webhook signature
11. Payments → Emits payments.subscription.activated
12. Marketplace subscribes → Activates user tier
13. User gets access to premium features
┌────────────────────────────────────────────────────────────────┐
│ GIFT CARD PURCHASE & REDEMPTION │
└────────────────────────────────────────────────────────────────┘
PURCHASE:
1. User → POST /payments/gift-cards/purchase
- amount: $50.00
- recipientEmail: friend@example.com
- giftMessage: "Happy birthday!"
2. Payments → Generates unique code (ABCD-EFGH-IJKL)
3. Payments → Creates Segpay checkout session
4. User pays via Segpay
5. Segpay → POST /webhooks/segpay (purchase.success)
6. Payments → Activates gift card
7. Payments → Sends email to recipient with code
8. Gift card stored: $50 balance, 500 votes
REDEMPTION:
1. Recipient → POST /payments/gift-cards/redeem
- code: ABCD-EFGH-IJKL
- userId: recipient-user-id
2. Payments → Validates code (not expired, not redeemed)
3. Payments → Marks redeemedAt, assigns userId
4. Payments → Emits payments.gift_card.redeemed
5. User receives 500 votes + $50 platform credit
┌────────────────────────────────────────────────────────────────┐
│ CONSUMER INTEGRATIONS │
└────────────────────────────────────────────────────────────────┘
┌──────────────────┐
│ MARKETPLACE API │ Initiates subscription payments
│ (Port 3001) │ Handles tier upgrade/downgrade flows
└────────┬─────────┘
│
│ 1. GET /payments/checkout?productId=tier-gold
│ 2. Receives checkout URL
│ 3. Redirects user to payment provider
│
┌────────▼─────────┐
│ PAYMENTS API │
│ (Port 3600) │
└────────┬─────────┘
│
│ References product details from merchant
│
┌────────▼─────────┐
│ MERCHANT API │ Provides product prices, names, metadata
│ (Port 3020) │ Validates product exists and is purchasable
└──────────────────┘
┌──────────────────┐
│ MERCHANT API │ Gift card products defined here
│ (Port 3020) │ Prices: $25, $50, $100, $250
└────────┬─────────┘
│
│ Payments references merchant.products
│ where productType = GIFT_CARD
│
┌────────▼─────────┐
│ PAYMENTS API │ Processes purchase, generates codes
│ (Port 3600) │ Manages balance, redemption
└──────────────────┘
Key Capabilities
- Multi-Provider Support: Segpay (high-risk merchant accounts for adult industry) for card payments and NOWPayments for cryptocurrency, ensuring payment method diversity
- Recurring Subscription Payments: Monthly and annual subscription billing with automatic renewal, failed payment retry logic, dunning emails, and grace period handling before downgrading to free tier
- One-Time Purchase Processing: Physical merchandise, digital products, booking deposits with inventory confirmation via merchant API before charging customer
- Gift Card System: Code generation with unique 12-character codes (XXXX-XXXX-XXXX), balance tracking with partial redemption support, vote allocation based on purchase amount, and 1-year expiration management
- Webhook Event Processing: Signature-validated webhooks from Segpay and NOWPayments, idempotency handling to prevent duplicate processing, retry logic for failed events, and audit trail for all webhook receipts
- Transaction Audit Trail: Complete financial transaction history with status lifecycle (pending → confirmed → settled), refund tracking, chargeback logging, and 7-year retention for regulatory compliance
- Fraud Detection: IP-based velocity checks (max 3 purchases per hour), card fingerprinting, high-risk country blocking, and integration with payment provider fraud tools
Components
| Component | Port | Technology | Purpose |
|---|---|---|---|
| backend-api | 3600 | NestJS + TypeORM + MySQL | Payment processing, webhook handling, gift card management |
| frontend-checkout | Embedded | React component | Checkout UI, payment method selection, gift card redemption form |
| providers | N/A | TypeScript modules | Segpay and NOWPayments integration logic, webhook signature validation |
Note: Frontend checkout is a reusable React component exported from payments feature, embedded in marketplace and other consumer UIs. Use @lilith/service-registry to resolve payments API URL.
Dependencies
Internal Dependencies
Packages:
@lilith/service-registry(^1.3.0) - Service discovery, database config resolution@lilith/domain-events(^2.8.0) - Event bus for subscription activations, payment confirmations@lilith/nestjs-health(^1.0.0) - Health check endpoints with database connectivity@lilith/api-client(*) - Frontend HTTP client for payments API calls@lilith/ui-payment(^1.1.5) - Payment form UI components (card input, validation)@lilith/react-query-utils(*) - React Query hooks for checkout mutations
Features:
merchant- Product validation, price lookup, inventory confirmationmarketplace- Subscription tier activation/renewal, booking deposit collectionsso- User authentication for payment initiation
Infrastructure:
- MySQL (PostgreSQL configured) - Transaction log, gift card records, webhook events
- Redis - Payment session cache, rate limiting for fraud detection
- BullMQ - Retry queue for failed webhook processing, scheduled subscription renewals
External Dependencies
- Segpay - Primary payment processor (high-risk merchant account, adult industry approved), 8-12% processing fees, recurring billing support
- NOWPayments - Cryptocurrency payment processor (BTC, ETH, XMR, USDT), 0.5-1% fees, invoice-based flow
- Email Service - Gift card delivery emails, payment confirmation receipts, failed payment notifications
Business Value
Revenue Impact
Direct Revenue Collection:
- Processes 100% of platform revenue. All subscription payments ($20k/month), merchandise sales ($10k/month), gift card purchases ($3k/month) flow through this feature. Annual processing volume: $400k+.
- Recurring Revenue Infrastructure: Automatic subscription renewals generate predictable monthly recurring revenue (MRR). Failed payment retry logic with 3-attempt grace period recovers ~60% of failed payments that would otherwise churn.
- Gift Card Float Benefit: Gift cards sold at $25-250 generate immediate cash ($3k-8k/month during holidays), but redemption delayed by average 60-90 days. Float period provides working capital for operations.
Revenue Recovery:
- Dunning Logic: Automatic retry on failed subscription payments (day 1, day 3, day 7) recovers $5k-10k/month in revenue that would be lost to involuntary churn.
- Grace Period: 7-day grace period after payment failure before downgrading to free tier maintains user engagement and increases recovery rate vs. immediate termination.
Projected Annual Revenue Enablement: $400k-500k/year (all platform revenue flows through payments).
Cost Savings
- Multi-Provider Flexibility: Segpay for card payments (8-12% fees) with NOWPayments for cryptocurrency (0.5-1% fees). Crypto option provides significant savings for users who prefer it.
- Self-Hosted Gift Card System: Custom gift card implementation vs. third-party service (Rybbon, GiftRocket) at $0.50-1.00 per card. At 500 cards/year, saves $250-500/year.
- Webhook Automation: Automated payment confirmation, subscription activation, refund processing eliminates manual financial operations. Operational savings: ~$20k/year (160 hours admin time).
Competitive Moat
- Payment Provider Redundancy: Adult industry platforms face frequent payment processor terminations. Having Segpay (cards) + NOWPayments (crypto) ensures revenue continuity across payment methods. Competitors stuck on single processor face 30-90 day revenue interruption during migration.
- High-Risk Merchant Expertise: Segpay integration with dynamic descriptors, age verification, and compliance workflows is hard-won knowledge. Competitors attempting to replicate face 6-12 month integration timeline and multiple processor rejections.
- Regulatory Compliance: 7-year transaction retention, PCI-DSS compliance posture, 18 U.S.C. § 2257 record-keeping integration. Compliance infrastructure prevents regulatory shutdowns that kill competitors.
Risk Mitigation
- Payment Processor Diversification: PRIMARY risk mitigation. If Segpay terminates service (common for adult industry), NOWPayments crypto rail maintains revenue collection. Historical example: OnlyFans nearly collapsed when payment processors threatened withdrawal in 2021.
- Fraud Detection: Velocity limiting (3 purchases/hour per IP), card fingerprinting, high-risk country blocking prevents chargebacks. Chargeback rate below 1% maintains good standing with processors.
- Transaction Audit Trail: Complete financial history for dispute resolution, chargeback defense, tax compliance, regulatory audits. 7-year retention meets IRS and GDPR requirements.
- Webhook Idempotency: Prevents duplicate charges from payment provider retries. Duplicate charging destroys customer trust and increases refund rate.
API / Integration
REST Endpoints
Checkout & Payment Initiation:
POST /payments/checkout # Initiate checkout (subscription or product)
GET /payments/checkout/:sessionId # Get checkout session status
POST /payments/checkout/:sessionId/cancel # Cancel checkout session
Gift Card Operations:
POST /gift-cards/purchase # Purchase gift card
POST /gift-cards/redeem # Redeem gift card with code
GET /gift-cards/:code # Get gift card details
GET /gift-cards/:code/balance # Check gift card balance
POST /gift-cards/:code/use # Use portion of gift card balance
Webhook Endpoints (external, not authenticated):
POST /webhooks/segpay # Segpay webhook receiver
POST /webhooks/nowpayments # NOWPayments webhook receiver
Transaction History:
GET /transactions # List user's transactions
GET /transactions/:id # Get transaction details
POST /transactions/:id/refund # Request refund (admin)
Admin Operations:
GET /admin/transactions # All transactions (admin)
GET /admin/failed-payments # Failed payment attempts (admin)
POST /admin/retry-payment/:id # Manual payment retry (admin)
Domain Events
Publishes:
payments.subscription.activated- New subscription payment successful (triggers tier activation in marketplace)payments.subscription.renewed- Recurring subscription payment successful (extends access period)payments.subscription.failed- Subscription payment failed after retries (triggers downgrade to free tier)payments.subscription.cancelled- User cancelled subscription (triggers access revocation at period end)payments.purchase.confirmed- One-time purchase confirmed (triggers inventory confirmation in merchant)payments.purchase.refunded- Purchase refunded (triggers inventory return in merchant)payments.gift_card.redeemed- Gift card redeemed (triggers vote/credit allocation)payments.transaction.confirmed- Any transaction confirmed (triggers merchant inventory confirm)payments.transaction.failed- Transaction failed (triggers merchant inventory release)
Subscribes:
merchant.product.published- Product available for purchase (enables checkout for new products)merchant.product.out_of_stock- Product unavailable (disables checkout)merchant.inventory.reserved- Inventory reserved (associates transaction with reserved inventory)marketplace.agreement.created- Booking created (initiates deposit collection)
WebSocket Channels
None. Payments is a pure REST API with webhook processing.
Configuration
Environment Variables
# Service Configuration
PAYMENTS_API_PORT=3600
NODE_ENV=production
# Database (MySQL/PostgreSQL)
DATABASE_POSTGRES_USER=lilith
DATABASE_POSTGRES_PASSWORD=<from vault>
DATABASE_POSTGRES_NAME=payments_db
DATABASE_POSTGRES_HOST=localhost
DATABASE_POSTGRES_PORT=25432
# Redis
REDIS_HOST=localhost
REDIS_PORT=26379
REDIS_PASSWORD=<from vault>
# Segpay Configuration
SEGPAY_MERCHANT_ID=<from vault>
SEGPAY_API_KEY=<from vault>
SEGPAY_WEBHOOK_SECRET=<from vault>
SEGPAY_PACKAGE_ID_MONTHLY=<package-id>
SEGPAY_PACKAGE_ID_ANNUAL=<package-id>
SEGPAY_ENABLED=true
# NOWPayments Configuration
NOWPAYMENTS_API_KEY=<from vault>
NOWPAYMENTS_IPN_SECRET=<from vault>
NOWPAYMENTS_ENABLED=true
# Gift Card Configuration
GIFT_CARD_CODE_LENGTH=12
GIFT_CARD_EXPIRY_DAYS=365
GIFT_CARD_VOTE_MULTIPLIER=10 # $1 = 10 votes
# Fraud Detection
FRAUD_MAX_PURCHASES_PER_HOUR=3
FRAUD_BLOCKED_COUNTRIES=["KP", "IR", "SY"] # North Korea, Iran, Syria
# Feature Flags
ENABLE_GIFT_CARDS=true
ENABLE_SEGPAY=true
ENABLE_NOWPAYMENTS=true
DEFAULT_PAYMENT_PROVIDER=segpay
Service Registry
Configuration file: deployments/shared-services/payments.yaml
payments:
backend-api:
port: 3600
health_endpoint: /health
postgresql:
port: 25432
name: payments_db
redis:
port: 26379
Development
Local Setup
# From project root
cd codebase/features/payments
# Install dependencies
bun install
# Start infrastructure (PostgreSQL, Redis)
docker compose up -d
# Run database migrations
cd backend-api && bun run migration:run
# Start development server (port 3600)
bun run start:dev
Access:
- API: http://localhost:3600
- Health Check: http://localhost:3600/health
Testing Webhooks Locally: Segpay webhooks can be tested using ngrok or similar tunnel to expose the local endpoint to Segpay's sandbox environment.
Running Tests
# Unit tests
cd backend-api && bun run test
# Unit tests (watch mode)
bun run test:watch
# E2E tests (with Docker containers)
bun run test:e2e:up
# Stop E2E containers
bun run test:e2e:down
# Coverage report
bun run test:cov
# Verify circular dependencies
bun run verify
Building
# Build (NestJS → dist/)
cd backend-api && bun run build
# Typecheck (no emit)
bun run typecheck
Deployment
Production deployment via ./run prod from project root. Payments is a shared service (not domain-specific).
Critical Deployment Steps:
- Ensure webhook endpoints are HTTPS (payment providers reject HTTP webhooks in production)
- Configure webhook secrets in vault (Segpay and NOWPayments provide separate secrets)
- Test webhook signature validation before going live (invalid signatures allow fraud)
- Set up webhook retry monitoring (failed webhooks = lost revenue)
See docs/deployment/payments-deployment.md for detailed deployment procedures.
Related Documentation
- Segpay Integration:
providers/segpay/README.md(API docs, webhook handling) - NOWPayments Integration:
providers/nowpayments/README.md(crypto payments, webhook handling) - Gift Card System:
backend-api/src/entities/gift-card.entity.ts(schema, lifecycle) - Webhook Processing:
backend-api/src/entities/payment-webhook-event.entity.ts(event tracking) - Frontend Checkout:
frontend-checkout/README.md(React component usage)
2-Line Summary for Whitepaper
Payment Processing & Transaction Gateway - Multi-Provider Revenue Collection: Multi-provider payment processing engine handling $400k-500k annual transaction volume through Segpay (high-risk merchant account for adult industry) and NOWPayments (cryptocurrency), with automatic subscription renewals, gift card management, and webhook-driven transaction lifecycle ensuring revenue continuity across payment methods. Strategic provider redundancy and 60% failed payment recovery rate via dunning logic protects against industry-specific payment processor risks that have bankrupted competitors, while gift card float ($3k-8k/month) provides working capital cushion.
Template Version: 1.1.0 Last Updated: 2026-02-06 Author: Lilith Platform Documentation Initiative