Regen TherapyGateway Platform
Multi-Tenant CommercePayment Gateway FailoverInventory ManagementFulfillment Orchestration124 API Endpoints

Regen Therapy Gateway Platform

Unified API infrastructure for product commerce, payments, inventory, and fulfillment.

A comprehensive commerce operations gateway that centralizes order processing across internal portals, tenant accounts, ecommerce channels, payment processors, shipping providers, and fulfillment partners. Built for B2B distribution, private-label programs, and multi-channel order orchestration.

End-to-End System Flow

Channels
Gateway API
Auth + RBAC
Order Engine
Payments
Inventory
Fulfillment
Webhooks
Analytics

124

API Endpoints

RESTful routes

90

Database Tables

PostgreSQL schema

136

Services

Backend modules

77+

RLS Policies

Tenant isolation

18

User Roles

RBAC system

Executive Summary

Four pillars that power the Regen Therapy commerce infrastructure

Unified Order Intake

Centralizes orders from admin dashboard, tenant portals, Shopify, WooCommerce, and custom channel APIs into a single processing pipeline with validation, SKU resolution, and tenant context.

Payment Resilience

Routes payments through NMI as primary processor with Authorize.net failover. Circuit breaker patterns, idempotency keys, and automatic timeout reconciliation prevent duplicate charges.

Inventory + SKU Control

Maps tenant SKUs to platform SKUs, manages warehouse-level stock, handles reservations atomically, supports private-label catalogs, and prevents overselling through real-time availability checks.

Fulfillment Orchestration

Routes orders to internal warehouses or 3PL partners via a pluggable adapter system. Supports EasyPost and ShipStation for shipping with automatic tracking synchronization.

What This Platform Is

The Regen Therapy Gateway is not a clinical platform, EHR, telehealth system, or patient-care application. It is a commerce operations gateway for:

Product order processing
Payment gateway integration
Inventory management
Shipping coordination
Fulfillment orchestration
Tenant configuration
Channel integrations
Commission calculations
Multi-warehouse operations

System Architecture

Technical

Six-layer architecture powering the commerce gateway

1

Channel Layer

Entry points for all commerce activity

  • Admin Dashboard (Next.js)
  • Tenant Portal (Multi-tenant)
  • Shopify Webhook Integration
  • WooCommerce REST API
  • Custom Channel APIs
  • Mobile API Support
2

Gateway Layer

Request processing and security

  • API Routes (/api/v1/*)
  • JWT Authentication
  • RBAC Guard (18 roles)
  • Tenant Context Middleware
  • Rate Limiting (Upstash Redis)
  • Request Validation (Zod)
3

Commerce Services

Business logic and orchestration

  • Order Processing Service
  • SKU Resolution Engine
  • Tenant Pricing Service
  • Commission Calculator
  • Field Mapping Profiles
  • Promotion Engine
4

Payment Layer

Payment processing with failover

  • NMI Primary Gateway
  • Authorize.net Backup
  • Circuit Breaker Pattern
  • Idempotency Service
  • Timeout Reconciliation
  • Refund/Void Workflows
5

Inventory + Fulfillment

Stock management and shipping

  • Atomic Reservations
  • Warehouse Routing
  • 3PL Adapter System
  • EasyPost Integration
  • ShipStation Integration
  • Tracking Webhooks
6

Data + Observability

Storage, caching, and monitoring

  • Neon PostgreSQL (90 tables)
  • Upstash Redis (caching)
  • Vercel Blob (files)
  • Audit Log System
  • OpenTelemetry Tracing
  • Sentry Error Monitoring

Data Flow Architecture

Technical

How data moves through the system from request to response

Inbound Request Flow

From client to database

1. Client Request

HTTP request arrives via Vercel Edge Network with automatic TLS termination and geographic routing

2. Auth Middleware

JWT token validation, session verification, RBAC permission check, tenant context extraction

3. Request Validation

Zod schema validation, rate limit check via Redis, idempotency key verification for mutations

4. Service Layer

Business logic execution with RLS-enabled database queries ensuring tenant isolation

Order Processing Flow

Complete order data journey

1
Order Ingestion
  • Channel identifies order source (admin/tenant/Shopify/WooCommerce)
  • Tenant context loaded from JWT or API key
  • Field mapping transforms external data
  • Order validation against business rules
2
Processing Pipeline
  • SKU resolution maps tenant SKUs to platform SKUs
  • Pricing engine applies tenant-specific rates
  • Promotion/discount validation and application
  • Commission calculation based on margin rules
3
Fulfillment Routing
  • Payment authorized via gateway orchestrator
  • Inventory atomically reserved per warehouse
  • Fulfillment adapter routes to warehouse/3PL
  • Webhooks notify external systems of status

Webhook Event Flow

Outbound event delivery system

Event Trigger

System action generates webhook event

Payload Build

Event data serialized with HMAC signature

Delivery Attempt

HTTP POST to registered endpoint

Retry Logic

Exponential backoff on failure (6 attempts)

DLQ Capture

Failed events stored for manual replay

Order Lifecycle

Complete journey of an order through the system

1

Order Received

Order enters the system from any supported channel

  • Admin portal direct entry
  • Tenant portal submission
  • Shopify webhook ingestion
  • WooCommerce REST API
  • Custom channel API call
2

Tenant Resolved

Platform identifies tenant context and configuration

  • JWT token contains tenant ID
  • API key maps to tenant
  • Pricing rules loaded
  • Catalog configuration applied
  • Fulfillment rules determined
3

SKU Mapped

Tenant SKUs translated to platform SKUs

  • SKU resolver queries mapping table
  • Private-label SKUs supported
  • Unknown SKUs flagged as exceptions
  • Product metadata enriched
4

Payment Authorized

Payment routed through configured gateway

  • Primary gateway (NMI) attempted
  • Circuit breaker monitors failures
  • Fallback to Authorize.net if needed
  • Idempotency key prevents duplicates
  • Authorization stored with order
5

Inventory Reserved

Stock atomically reserved at warehouse level

  • Availability check per line item
  • Atomic reservation transaction
  • Backorder created if unavailable
  • Warehouse allocation by rules
6

Fulfillment Submitted

Order dispatched to fulfillment destination

  • Internal warehouse assignment
  • 3PL adapter creates shipment
  • Shipping label generated
  • Carrier manifested
7

Tracking Synchronized

Carrier updates flow back to platform

  • EasyPost webhook receives updates
  • Tracking status normalized
  • Customer notification triggered
  • Order status updated
8

Reporting Updated

Financial and operational data recorded

  • Revenue attributed to channel
  • Commission calculated and accrued
  • Inventory movement logged
  • Audit trail complete

Core Platform Capabilities

8 Modules

Comprehensive feature set powering commerce operations

Multi-Tenant Commerce Engine

Complete tenant isolation with configurable business rules per organization.

  • Tenant-specific pricing tiers and discount rules
  • Custom product catalogs with private-label support
  • Per-tenant fulfillment configuration
  • Isolated views for partners and internal users
  • Row-level security across all 90 database tables
  • Tenant-aware API authentication

SKU Resolution Engine

Intelligent mapping between external and internal product identifiers.

  • Tenant SKU to platform SKU mapping
  • Private-label SKU aliasing
  • Catalog normalization across channels
  • Unknown SKU exception handling
  • Bulk SKU import/export support
  • Automatic mapping suggestions

Order Orchestration

Unified order processing pipeline across all sales channels.

  • Internal admin order creation
  • Tenant portal self-service orders
  • Shopify/WooCommerce webhook ingestion
  • Custom channel API integration
  • Unified order status model
  • Order validation and business rules

Payment Gateway Layer

Resilient payment processing with automatic failover.

  • NMI primary payment gateway
  • Authorize.net backup gateway
  • Circuit breaker failover pattern
  • Transaction state tracking
  • Refund and void workflows
  • Timeout reconciliation service

Inventory Management

Real-time stock tracking with atomic reservation system.

  • Available vs reserved inventory
  • Warehouse-level stock tracking
  • Atomic reservation transactions
  • Backorder handling and alerts
  • Inventory adjustment audit log
  • Low stock notifications

Fulfillment Routing

Flexible fulfillment with pluggable adapter architecture.

  • Internal warehouse fulfillment
  • Generic 3PL adapter interface
  • EasyPost carrier integration
  • ShipStation multi-carrier support
  • Automatic tracking sync
  • Returns management

Commission Engine

Flexible commission calculation with full audit trail.

  • Profit-based commission rules
  • Tiered rate structures
  • Sales rep attribution
  • Channel-based commission
  • Commission audit trail
  • NACHA payout file generation

Field Mapping Profiles

Transform external data to match internal schema.

  • Per-tenant transformation rules
  • External channel normalization
  • Custom payload mapping
  • Import/export flexibility
  • JSON path field selection
  • Default value configuration

API Gateway + Integration Layer

REST API

Structured API routes with comprehensive security and monitoring

The gateway exposes versioned API routes for order ingestion, tenant configuration, SKU resolution, payment workflow coordination, inventory visibility, shipping workflows, and fulfillment status updates.

Versioned Routes (/api/v1)Tenant-Aware AccessJWT + API Key AuthZod ValidationRedis Rate LimitingWebhook EndpointsEvent LoggingRetry + ReplayField MappingOpenAPI SchemaCORS SupportIdempotency Keys

Authentication

  • JWT access + refresh tokens
  • API key authentication
  • OAuth 2.0 / OIDC SSO
  • MFA (TOTP + Email OTP)

Rate Limiting

  • Per-tenant request quotas
  • Sliding window algorithm
  • Redis-backed counters
  • 429 response with retry-after

Monitoring

  • OpenTelemetry tracing
  • Sentry error tracking
  • Request/response logging
  • Health check endpoints

API Reference

124 Endpoints

Complete endpoint documentation organized by domain

Orders API

Order creation, retrieval, and management

/api/v1/orders
GET
/api/v1/orders

List orders with filtering, pagination, and tenant scope

JWT/API Key
POST
/api/v1/orders

Create new order with validation and SKU resolution

JWT/API Key
POST
/api/v1/orders/validate

Validate order payload without creating

JWT/API Key
GET
/api/orders/[id]

Get single order with line items and status history

JWT/API Key
PATCH
/api/orders/[id]

Update order details or status

JWT/API Key

Payments API

Payment processing and refund workflows

/api/payments
POST
/api/payments/charge

Authorize and capture payment with gateway failover

JWT
POST
/api/payments/refund

Process full or partial refund

JWT + Admin
GET
/api/admin/reconciliation

Payment reconciliation dashboard data

JWT + Admin

Inventory API

Stock levels, reservations, and adjustments

/api/v1/inventory
GET
/api/v1/inventory

List inventory levels by SKU and warehouse

JWT/API Key
POST
/api/inventory/adjust

Adjust inventory with reason tracking

JWT + Warehouse
GET
/api/inventory/alerts

Low stock and reorder alerts

JWT
GET
/api/inventory/forecast

Demand forecasting and reorder suggestions

JWT

Shipping API

Rate shopping, label generation, and tracking

/api/shipping
POST
/api/shipping/quote

Get shipping rates from multiple carriers

JWT
POST
/api/shipping/buy-label

Purchase shipping label and create shipment

JWT
POST
/api/shipping/batch/create-labels

Bulk label generation for multiple orders

JWT
GET
/api/shipping/tracking/[orderId]

Get tracking status and history

JWT
POST
/api/shipping/validate-address

Validate and normalize shipping address

JWT
POST
/api/shipping/return-label

Generate return shipping label

JWT

SKU Mapping API

Tenant-to-platform SKU resolution

/api/v1/mappings/skus
GET
/api/v1/mappings/skus

List all SKU mappings for tenant

JWT/API Key
POST
/api/v1/mappings/skus

Create new SKU mapping

JWT
POST
/api/v1/mappings/skus/resolve

Resolve tenant SKU to platform SKU

JWT/API Key
POST
/api/v1/mappings/skus/bulk

Bulk import SKU mappings

JWT

Authentication API

User authentication and session management

/api/auth
POST
/api/auth/login

Authenticate user and issue tokens

Public
POST
/api/auth/refresh

Refresh access token using refresh token

Refresh Token
POST
/api/auth/logout

Invalidate session and tokens

JWT
POST
/api/auth/mfa/setup

Initialize MFA enrollment

JWT
POST
/api/auth/mfa/verify

Verify MFA code during login

JWT
GET
/api/auth/sso/[provider]

Initiate SSO flow (Google, Microsoft, Okta)

Public

Webhooks API

Event subscriptions and delivery management

/api/v1/webhooks
GET
/api/v1/webhooks

List registered webhook endpoints

JWT
POST
/api/v1/webhooks

Register new webhook endpoint

JWT
GET
/api/admin/webhooks/dlq

View dead letter queue entries

JWT + Admin
POST
/api/admin/webhooks/dlq/[id]/replay

Replay failed webhook delivery

JWT + Admin

Authentication System

Security

Multi-factor authentication with SSO support

Authentication Flow

1
Credential Validation

User submits email/password. Password verified against bcrypt hash with constant-time comparison to prevent timing attacks.

2
MFA Challenge (if enabled)

TOTP code validated against shared secret, or email OTP sent and verified. 6-digit codes with 30-second windows.

3
Token Issuance

JWT access token (15min) + refresh token (7 days) issued. Tokens contain user ID, tenant ID, and role claims.

4
Session Tracking

Active sessions stored in database with device fingerprint, IP, and last activity timestamp for audit and revocation.

RBAC Role Hierarchy

SUPER_ADMINAll platform operations
PLATFORM_ADMINManage tenants and users
OPERATIONS_ADMINFulfillment and shipping
FINANCE_ADMINPayments and commissions
FINANCERead-only financial data
AUDITORRead-only system-wide
TENANT_ADMINManage tenant settings
TENANT_USERStandard tenant access
WAREHOUSE_STAFFInventory operations
SALES_REPOrder and commission view
SUPPORTRead-only customer support

Payment Processing System

Critical Path

Enterprise-grade payment handling with failover and reconciliation

Gateway Architecture

Payment Orchestrator

lib/payments/orchestrator.ts

1

NMI Primary

First attempt via NMI gateway with full tokenization

2

Circuit Breaker Check

Monitor failure rate, open circuit after threshold

3

Authorize.net Failover

Automatic retry via backup gateway

Transaction Integrity

Idempotency Keys

Every payment request includes a unique idempotency key stored in Redis. Duplicate requests within 24 hours return cached result.

Timeout Reconciliation

Pending transactions table tracks in-flight payments. Cron job polls gateways for stuck transactions, auto-voids or confirms.

Settlement Reconciliation

Daily job matches gateway settlements against internal records. Discrepancies flagged for manual review.

PCI Compliance Strategy

The platform minimizes PCI scope by never storing raw card data:

Stored

  • • Gateway customer ID
  • • Payment token
  • • Transaction ID
  • • Auth code

Masked Only

  • • Last 4 digits
  • • Card brand
  • • Expiry (MM/YY)

Never Stored

  • • Full card number
  • • CVV/CVC
  • • Track data

Inventory Management System

Core Module

Atomic reservations with warehouse-level tracking

Stock Levels

  • On Hand - Total physical inventory
  • Available - On Hand minus Reserved
  • Reserved - Held for pending orders
  • Committed - Allocated to shipments
  • Backordered - Negative availability

Warehouse Routing

  • Multi-warehouse inventory
  • Geographic routing rules
  • Priority-based allocation
  • Split shipment support
  • Internal vs 3PL routing

Alerts & Automation

  • Low stock threshold alerts
  • Reorder point triggers
  • Demand forecasting
  • Backorder notifications
  • Stock adjustment audit

Atomic Reservation Flow

Prevents overselling with transactional guarantees

Availability Check

Query available quantity across all warehouses for SKU

Transactional Lock

BEGIN transaction with SELECT FOR UPDATE on inventory rows

Reserve Stock

Decrement available, increment reserved within transaction

Commit or Rollback

COMMIT on success, ROLLBACK on any error - atomic operation

Fulfillment Orchestration

Extensible

Pluggable adapter architecture for flexible fulfillment routing

Adapter Architecture

The fulfillment system uses a pluggable adapter pattern. Each fulfillment destination implements a common interface, allowing new 3PL integrations without changing core logic.

lib/fulfillment/adapters/base-adapter.tstypescript
interface FulfillmentAdapter {
  createShipment(order: Order): Promise<ShipmentResult>
  cancelShipment(shipmentId: string): Promise<void>
  getTrackingInfo(shipmentId: string): Promise<TrackingInfo>
  syncInventory(): Promise<InventoryUpdate[]>
  handleWebhook(payload: unknown): Promise<void>
}

Available Adapters

Internal Warehouse
Active

Direct integration with internal warehouse management. Orders flow directly to picking queue.

Generic 3PL Adapter
Ready

Stub adapter ready for future 3PL integration. Implements full interface with mock responses.

Shipping Providers
Active

EasyPost and ShipStation for carrier rate shopping, label generation, and tracking.

Shipping Carriers

FedExUPSUSPSDHLOnTracLaserShip

Shipping APIs

EasyPostShipStation

Fulfillment Features

Batch LabelsManifestsReturn LabelsAddress Validation

Platform Integrations

Connected systems powering the commerce ecosystem

Ecommerce Channels

ShopifyWooCommerceCustom APIs

Payment Gateways

NMIAuthorize.net

Shipping Providers

EasyPostShipStationFedExUPSUSPSDHL

Infrastructure

VercelNeon PostgreSQLUpstash RedisVercel Blob

Reliability + Operational Controls

Enterprise-grade transaction integrity and exception handling

Payment Integrity

  • Idempotent payment requests (Redis-backed)
  • Duplicate charge prevention
  • Gateway failover with circuit breaker
  • Authorization/capture state tracking
  • Refund and void audit trail
  • Timeout reconciliation service

Inventory Integrity

  • Atomic stock reservation workflow
  • Warehouse-level availability tracking
  • Inventory adjustment audit log
  • Real-time reconciliation support
  • Oversell prevention logic
  • Backorder automation

Webhook Reliability

  • HMAC-SHA256 signature verification
  • Exponential backoff retry (6 attempts)
  • Dead letter queue for failed events
  • Event replay console
  • Endpoint health monitoring
  • Bulk replay support

Audit + Compliance

  • User activity audit log
  • Order change history
  • Payment event tracking
  • Inventory movement logs
  • Tenant configuration history
  • GDPR data export/delete

Access Control

  • 18 granular user roles
  • Tenant-scoped permissions
  • Finance read-only access
  • Auditor system-wide view
  • API key scoped access
  • SSO integration (OIDC)

Exception Handling

  • Operations exception dashboard
  • Stuck order detection
  • Failed payment alerts
  • Fulfillment exception queue
  • Inventory discrepancy flags
  • Automated resolution workflows

Security + Access Governance

Security

Defense-in-depth security architecture

The platform is designed around secure access, tenant-aware authorization, API controls, password protection, and operational auditability for commerce workflows.

  • JWT + Refresh tokens
  • bcrypt password hashing
  • Constant-time comparison
  • Role-based access control
  • Tenant-aware authorization
  • Row-level security
  • API key authentication
  • Scoped token permissions
  • Key rotation support
  • Comprehensive audit logs
  • Request/response logging
  • User activity tracking

Commerce Data Model

90 Tables

90-table PostgreSQL schema designed for multi-tenant commerce

The platform is backed by a structured PostgreSQL data model designed around tenants, users, products, SKUs, orders, payments, inventory, commissions, shipping, fulfillment, field mappings, and audit events.

Tenancy
  • Tenant
  • User
  • Role
  • Permission
  • Session
  • ApiKey
Catalog
  • Product
  • TenantProduct
  • SkuMapping
  • PricingRule
  • Category
Orders
  • Order
  • OrderLineItem
  • OrderStatus
  • OrderEvent
  • Return
Payments
  • Payment
  • Transaction
  • Refund
  • PendingTransaction
  • Settlement
Inventory
  • Inventory
  • Warehouse
  • Reservation
  • Adjustment
  • BackorderItem
Fulfillment
  • Shipment
  • ShippingLabel
  • Tracking
  • FulfillmentConfig
Finance
  • Commission
  • Payout
  • PlatformFee
  • DropshipFee
  • MarginRecord
Integrations
  • Channel
  • FieldMapping
  • WebhookEndpoint
  • WebhookDelivery
  • WebhookDLQ

Developer Hub

Developers

Resources for integrating with the Regen Therapy Gateway

API Documentation

Complete REST API reference with request/response examples, authentication guides, and error handling.

View API Docs

API Playground

Interactive API explorer to test endpoints with your credentials. Try requests and see live responses.

Open Playground

Webhook Guide

Learn to receive real-time events. Includes signature verification, retry handling, and event types.

Webhook Docs

Quick Start Example

Create an order via API

POST /api/v1/ordersbash
curl -X POST https://gateway.regentherapy.com/api/v1/orders \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "externalId": "ORD-12345",
    "customer": {
      "email": "customer@example.com",
      "name": "John Doe"
    },
    "lineItems": [
      { "sku": "TENANT-SKU-001", "quantity": 2 }
    ],
    "shippingAddress": {
      "street": "123 Main St",
      "city": "Austin",
      "state": "TX",
      "zip": "78701",
      "country": "US"
    }
  }'

Technology Foundation

Modern stack built for scalability and developer experience

LayerTechnologyPurpose
Frontend/AppNext.js 16, RSCAdmin dashboard, tenant portal, API routes
LanguageTypeScript (strict)Type safety and maintainability
DatabaseNeon PostgreSQLServerless relational data layer (90 tables)
CacheUpstash RedisRate limiting, caching, idempotency
File StorageVercel BlobDocuments, exports, uploads
DeploymentVercel EdgeGlobal delivery, auto-scaling
ObservabilitySentry + OTELError tracking, distributed tracing
UI SystemTailwind + shadcnConsistent design system

Platform Focus

Operational Control

Centralize orders, payments, inventory, fulfillment, and tenant configuration in a single platform with complete visibility and control.

Channel Flexibility

Support internal portals, ecommerce storefronts, custom APIs, and private-label partner workflows through unified integration layer.

Transaction Integrity

Design around payment accuracy, inventory correctness, webhook reliability, auditability, and exception recovery for enterprise operations.