Forhopp

ForhoppPay Connect - Architecture & Security Documentation

System Architecture

High-Level Overview

ForhoppPay Connect extends the existing ForhoppPay service with merchant payment integration capabilities. It runs within the same Spring Boot application and shares the PostgreSQL database and Redis infrastructure.

┌─────────────────────────────────────────────────────────────┐
│                    Client Applications                       │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌────────────┐ │
│  │WordPress │  │ Shopify  │  │   JS SDK │  │  Custom    │ │
│  │ Plugin   │  │   App    │  │          │  │Integration │ │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └─────┬──────┘ │
└───────┼──────────────┼──────────────┼──────────────┼────────┘
        │              │              │              │
        ▼              ▼              ▼              ▼
┌─────────────────────────────────────────────────────────────┐
│                  API Gateway Layer                            │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │ ApiKeyAuth Filter│  │ ConnectRateLimitFilter            │ │
│  │ (Bearer sk_*)    │  │ (Redis sliding window)            │ │
│  └────────┬─────────┘  └──────────────┬───────────────────┘ │
└───────────┼────────────────────────────┼────────────────────┘
            │                            │
            ▼                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    Controller Layer                           │
│  ┌────────────────┐ ┌──────────────┐ ┌───────────────────┐ │
│  │ConnectCharge   │ │ConnectWebhook│ │ConnectCheckout    │ │
│  │Controller      │ │Controller    │ │Controller         │ │
│  └───────┬────────┘ └──────┬───────┘ └────────┬──────────┘ │
│  ┌────────────────┐ ┌──────────────┐                        │
│  │ConnectKey      │ │ApiVersion    │                        │
│  │Controller      │ │Filter        │                        │
│  └───────┬────────┘ └──────┬───────┘                        │
└──────────┼─────────────────┼────────────────────────────────┘
           │                 │
           ▼                 ▼
┌─────────────────────────────────────────────────────────────┐
│                    Service Layer                             │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │MerchantApiKey    │  │MerchantChargeService              │ │
│  │Service           │  │  - createCharge()                 │ │
│  │  - generateKey() │  │  - captureCharge()                │ │
│  │  - authenticate()│  │  - refundCharge()                 │ │
│  └──────────────────┘  └──────────────────────────────────┘ │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │MerchantWebhook   │  │MerchantCheckoutService            │ │
│  │Service           │  │  - getCheckoutData()              │ │
│  │  - dispatch()    │  │  - completeCheckout()             │ │
│  │  - retry()       │  │  - cancelCheckout()               │ │
│  └──────────────────┘  └──────────────────────────────────┘ │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │MerchantPayout    │  │ConnectFeeCalculation              │ │
│  │Service           │  │Service                            │ │
│  │  - daily/weekly/ │  │  - calculateFee()                 │ │
│  │    monthly       │  │  - 2.9% + $0.30                   │ │
│  └──────────────────┘  └──────────────────────────────────┘ │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │ConnectDispute    │  │CurrencyConversion                 │ │
│  │Service           │  │Service                            │ │
│  │  - createDispute │  │  - convert()                      │ │
│  │  - resolveWon()  │  │  - 1% fee                         │ │
│  └──────────────────┘  └──────────────────────────────────┘ │
│  ┌──────────────────┐  ┌──────────────────────────────────┐ │
│  │SandboxPayment    │  │ConnectRateLimiter                 │ │
│  │Simulator         │  │  - Redis sliding window           │ │
│  │  - test cards    │  │  - 100/sec live, 25/sec test      │ │
│  └──────────────────┘  └──────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
           │                            │
           ▼                            ▼
┌──────────────────────┐  ┌──────────────────────────────────┐
│    PostgreSQL        │  │         Redis                     │
│  forhopppay schema   │  │  - Rate limiting (sorted sets)    │
│  - merchant_api_keys │  │  - Session cache                  │
│  - merchant_charges  │  │  - Key usage tracking             │
│  - merchant_webhooks │  │                                   │
│  - merchant_payouts  │  │                                   │
│  - merchant_disputes │  │                                   │
│  - merchant_profiles │  │                                   │
│  - merchant_customers│  │                                   │
│  - merchant_plans    │  │                                   │
│  - merchant_prices   │  │                                   │
│  - merchant_         │  │                                   │
│    subscriptions     │  │                                   │
│  - subscription_items│  │                                   │
│  - subscription_     │  │                                   │
│    invoices          │  │                                   │
│  - subscription_     │  │                                   │
│    invoice_line_items│  │                                   │
│  - pending_prorations│  │                                   │
│  - payment_method_   │  │                                   │
│    tokens            │  │                                   │
│  - subscription_     │  │                                   │
│    tax_rates         │  │                                   │
│  - merchant_webhook_ │  │                                   │
│    deliveries        │  │                                   │
│  - merchant_refunds  │  │                                   │
└──────────────────────┘  └──────────────────────────────────┘

Technology Stack

Component Technology Version
Backend API Java / Spring Boot 17 / 3.4
Database PostgreSQL 13+
Cache / Rate Limiting Redis 6+
ORM Hibernate / JPA 6.x
Migrations Flyway 9.x
Build Maven 3.9+
Deployment Kubernetes 1.28+
Testing JUnit 5, jqwik (property-based) 5.x

Controllers (Complete List)

Controller Base Path Auth Purpose
ConnectChargeController /api/v1/connect/charges API Key Charges CRUD, capture, refund
ConnectWebhookController /api/v1/connect/webhooks API Key Webhook endpoint management
ConnectCheckoutController /api/v1/connect/checkout None (public) Hosted checkout pages
ConnectKeyController /api/v1/connect/keys JWT API key management
ConnectSubscriptionController /api/v1/connect/subscriptions API Key Subscription lifecycle
ConnectSubscriptionItemController /api/v1/connect/subscriptions/{id}/items API Key Subscription add-ons
ConnectCustomerController /api/v1/connect/customers API Key Customer management
ConnectPlanController /api/v1/connect/plans API Key Plans and prices
ConnectPaymentMethodController /api/v1/connect/customers/{id}/payment-methods API Key Payment method vault
ConnectInvoiceController /api/v1/connect/invoices API Key Subscription invoices
ConnectBalanceController /api/v1/connect/balance API Key Merchant balance
ConnectTaxRateController /api/v1/connect/tax-rates API Key Tax rate configuration
ConnectPortalController /api/v1/connect/portal-sessions API Key Customer self-service portal
ConnectEnableController /api/v1/connect/enable JWT Connect onboarding
ConnectTestController /api/v1/connect/test API Key Test/sandbox utilities

Security Architecture

Authentication Flow

Client Request
    │
    ▼
┌─────────────────────────────────┐
│ ApiVersionFilter                │
│ @Order(HIGHEST_PRECEDENCE + 10) │
│                                 │
│ 1. Extract ForhoppPay-Version   │
│ 2. Set in ApiVersionHolder      │
│ 3. Add response header          │
│ 4. Add deprecation warning if   │
│    using deprecated version     │
└────────────┬────────────────────┘
             │
             ▼
┌─────────────────────────────────┐
│ ApiKeyAuthenticationFilter      │
│ @Order(1)                       │
│                                 │
│ 1. Extract Bearer token         │
│ 2. Validate sk_* prefix         │
│ 3. Verify format (40 chars)     │
│ 4. Authenticate via bcrypt      │
│ 5. Check key not revoked        │
│ 6. Set MerchantContext          │
│ 7. Set Spring Security auth     │
│    (ROLE_MERCHANT)              │
│ 8. Record key usage (async)     │
└────────────┬────────────────────┘
             │
             ▼
┌─────────────────────────────────┐
│ ConnectRateLimitFilter          │
│ @Order(2)                       │
│                                 │
│ 1. Get rate limit for key       │
│ 2. Check Redis sliding window   │
│ 3. Add rate limit headers       │
│ 4. Return 429 if exceeded       │
└────────────┬────────────────────┘
             │
             ▼
┌─────────────────────────────────┐
│ Controller (business logic)     │
│                                 │
│ → ApiVersionResponseAdvice      │
│   transforms response body      │
│   based on version              │
└─────────────────────────────────┘

API Key Security

  • Secret keys are hashed with bcrypt before storage
  • Plaintext secret key is returned only once at creation
  • Keys use cryptographically secure random generation (SecureRandom)
  • Key format: sk_(live|test)_[a-zA-Z0-9]{32} (40 chars total)
  • Maximum 10 active keys per merchant
  • Soft delete via revoked_at timestamp (audit trail preserved)
  • Key usage tracked via last_used_at timestamp

Webhook Signature Security

Webhook payloads are signed using HMAC-SHA256:

Signature = HMAC-SHA256(timestamp + "." + payload, webhook_secret)
Header: ForhoppPay-Signature: t={timestamp},v1={signature}

Verification requirements:

  • Timestamp must be within 5 minutes of current time (replay protection)
  • Signature comparison uses constant-time algorithm (timing attack prevention)
  • Each webhook endpoint has a unique signing secret

Rate Limiting

Implemented using Redis sorted sets with sliding window algorithm:

-- Atomic Lua script for rate limiting
1. Remove expired entries from sorted set
2. Count current requests in window
3. If count >= limit: return denied
4. Add current request to sorted set
5. Set TTL on key
6. Return allowed with remaining count
Environment Limit Window
Live (sk_live_*) 100 req/sec 1 second
Test (sk_test_*) 25 req/sec 1 second

Response headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890

Environment Isolation

  • sk_live_* keys access production data only
  • sk_test_* keys access sandbox data only
  • Sandbox charges never process real payments
  • Test data is isolated from production via environment column
  • Rate limits differ between environments

Endpoint Security

Endpoint Pattern Authentication Access
/api/v1/connect/charges/** API Key (sk_*) Merchant
/api/v1/connect/webhooks/** API Key (sk_*) Merchant
/api/v1/connect/subscriptions/** API Key (sk_*) Merchant
/api/v1/connect/customers/** API Key (sk_*) Merchant
/api/v1/connect/plans/** API Key (sk_*) Merchant
/api/v1/connect/invoices/** API Key (sk_*) Merchant
/api/v1/connect/balance API Key (sk_*) Merchant
/api/v1/connect/tax-rates/** API Key (sk_*) Merchant
/api/v1/connect/portal-sessions/** API Key (sk_*) Merchant
/api/v1/connect/keys/** JWT Token Merchant Dashboard
/api/v1/connect/enable/** JWT Token Merchant Dashboard
/api/v1/connect/profile/** JWT Token Merchant Dashboard
/api/v1/connect/checkout/** None (public) End Customer

Scheduled Tasks

Billing Cycle Scheduler

┌─────────────────────────────────────────┐
│ BillingCycleScheduler                   │
│ Runs: Every hour (fixedRate = 3600000)  │
│                                         │
│ 1. Find ACTIVE subscriptions where      │
│    current_period_end < NOW()           │
│    FOR UPDATE SKIP LOCKED LIMIT 100     │
│                                         │
│ 2. For each: SubscriptionBillingService │
│    .billSubscription(subscription)      │
│    - Build consolidated invoice         │
│    - Calculate tax                      │
│    - Charge saved payment method        │
│    - On success: advance period, credit │
│    - On failure: PAST_DUE + dunning     │
│                                         │
│ 3. Find TRIALING subscriptions where    │
│    trial_end < NOW()                    │
│    → Transition to ACTIVE and bill      │
└─────────────────────────────────────────┘

Charge Expiration Scheduler

┌─────────────────────────────────────────┐
│ ChargeExpirationScheduler               │
│ Runs: Every 5 minutes                   │
│                                         │
│ 1. Find PENDING charges > 24h old       │
│    → Set status to EXPIRED              │
│                                         │
│ 2. Find AUTHORIZED charges > 7 days old │
│    → Set status to VOIDED               │
└─────────────────────────────────────────┘

Payout Scheduler

┌─────────────────────────────────────────┐
│ MerchantPayoutService                   │
│                                         │
│ Daily:   0 0 0 * * *    (00:00 UTC)     │
│ Weekly:  0 0 0 * * MON  (Monday 00:00)  │
│ Monthly: 0 0 0 1 * *    (1st 00:00)     │
│                                         │
│ For each merchant with matching schedule:│
│ 1. Calculate: captured - fees - refunds  │
│    - disputed amounts                    │
│ 2. Check >= $25 minimum threshold        │
│ 3. Create payout record                  │
│ 4. Dispatch payout.created webhook       │
└─────────────────────────────────────────┘

Webhook Retry Scheduler

┌─────────────────────────────────────────┐
│ MerchantWebhookService.retryFailed()    │
│ Runs: Every 60 seconds                  │
│                                         │
│ 1. Find PENDING deliveries past retry   │
│ 2. Attempt delivery (HTTP POST)         │
│ 3. On success: mark DELIVERED           │
│ 4. On failure: schedule next retry      │
│    Intervals: 1m, 5m, 30m, 2h, 24h     │
│ 5. After 5 failures: mark endpoint      │
│    as failing                           │
└─────────────────────────────────────────┘

Fee Calculation

Transaction Fee

fee = (amount_cents × 0.029) + 30

Example: $50.00 charge (5000 cents)
  Percentage: 5000 × 0.029 = 145 cents
  Fixed: 30 cents
  Total fee: 175 cents ($1.75)
  Net to merchant: 4825 cents ($48.25)

Currency Conversion Fee

conversion_fee = 1% above mid-market rate

Example: €50.00 → USD
  Mid-market rate: 1 EUR = 1.087 USD
  Applied rate: 1 EUR = 1.087 × 0.99 = 1.076 USD
  Conversion fee: ~0.5% of converted amount

Dispute Fee

dispute_fee = $15.00 (1500 cents)
  - Charged when dispute is opened
  - Refunded if merchant wins dispute

API Versioning

The Connect API supports versioning via the ForhoppPay-Version header:

ForhoppPay-Version: 2024-01-01
  • If no version header is provided, the latest stable version is used
  • Deprecated versions are supported for 12 months
  • Breaking changes only in major versions
  • Version is echoed in response headers

Version Filter Flow

Request → ApiVersionFilter
  1. Extract ForhoppPay-Version header
  2. Set version in ApiVersionHolder (ThreadLocal)
  3. Continue filter chain
  
Response → ApiVersionResponseAdvice
  1. Read version from ApiVersionHolder
  2. Add ForhoppPay-Version response header
  3. Format response per version spec

Error Handling

Error Response Format

All errors follow a consistent JSON structure:

{
  "error": {
    "type": "invalid_request_error",
    "code": "parameter_invalid",
    "message": "Human-readable description",
    "param": "amount",
    "doc_url": "https://docs.forhopppay.com/errors/parameter_invalid"
  }
}

Error Types

Type HTTP Status When
invalid_request_error 400 Bad parameters
authentication_error 401 Invalid/missing API key
authorization_error 403 Insufficient permissions
resource_not_found 404 Resource doesn't exist
idempotency_error 409 Key reused with different params
rate_limit_error 429 Too many requests
api_error 500 Internal server error
gateway_error 502 Payment gateway error

Circuit Breaker Pattern

For external service calls (payment gateways, webhook delivery):

  • Open after 5 consecutive failures
  • Half-open after 30 seconds
  • Close after 3 successful calls
  • Fallback: queue for retry, return appropriate error

Deployment

Kubernetes Configuration

The Connect module deploys as part of the forhopppay-service:

# backend/k8s/base/forhopppay/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: forhopppay-service
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: forhopppay-service
        image: forhopppay-service:latest
        ports:
        - containerPort: 8082
        env:
        - name: SPRING_PROFILES_ACTIVE
          value: production
        - name: CONNECT_RATE_LIMIT_ENABLED
          value: "true"

Required Environment Variables

Variable Description
SPRING_DATASOURCE_URL PostgreSQL connection URL
SPRING_REDIS_HOST Redis host for rate limiting
FORHOPPPAY_CONNECT_CHECKOUT_BASE_URL Checkout page base URL
CONNECT_RATE_LIMIT_ENABLED Enable/disable rate limiting
CONNECT_RATE_LIMIT_LIVE_REQUESTS_PER_SECOND Live key rate limit
CONNECT_RATE_LIMIT_TEST_REQUESTS_PER_SECOND Test key rate limit

Non-Functional Requirements

Requirement Target
API response time (p95) < 200ms
Webhook delivery latency < 5 seconds
Checkout page load < 2 seconds
Concurrent API requests 10,000
API uptime SLA 99.99%
Dashboard uptime SLA 99.9%
Authentication latency (p99) < 50ms

Last Updated: July 2026

Was this page helpful?

Edit this page