Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript

docs: update ARCHITECTURE and DEPLOYMENT guides for dynamic branding architecture

ArunGupta15263dfbd91c5a1f
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 32bb7ad..9f13072 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -1,7 +1,7 @@
# ARCHITECTURE.md — Canonical System Architecture & Engineering Blueprint
> **YOUPI PG V2**
-> *Sovereign • Self-Hosted • Zero-Fee • Deterministic UPI Payment Gateway Suite*
+> _Sovereign • Self-Hosted • Zero-Fee • Deterministic UPI Payment Gateway Suite_
> **Architecture Reference:** Production Specification V2
> **Runtime Target:** Node.js `>= 20.0.0` (ESM Native) • SQLite WAL • Android Kotlin
@@ -12,14 +12,18 @@
**YOUPI PG** is a sovereign, self-hosted, white-label UPI and multi-modal payment gateway engineered for small-scale merchants, digital creators, and independent businesses in India.
### The Problem It Solves
+
Traditional Indian payment aggregators (Razorpay, Cashfree, PayU, Paytm) impose:
+
1. **Aggressive Fees:** 2.0% to 3.0% + 18% GST per transaction.
2. **Delayed Settlements:** T+2 to T+3 business day settlement cycles that choke operational cash flow.
3. **Arbitrary Account Freezes:** Unilateral merchant fund withholding and sudden KYC lockdowns.
4. **Phone Spoofing & Fraud:** Fraudulent orders placed using arbitrary fake phone numbers.
### The YOUPI PG Solution
+
YOUPI PG eliminates the aggregator intermediary completely:
+
- **0% Transaction Fees Forever:** Payments are settled directly into the merchant's bank account via peer-to-peer (P2P) UPI rails.
- **Sub-Second Direct Settlement:** Zero holdbacks. Funds land in the merchant's account instantly.
- **Deterministic Bank Observation:** Uses incoming cellular Bank SMS and Gmail notifications to verify payment credits cryptographically without official banking API licenses.
@@ -33,43 +37,58 @@ YOUPI PG eliminates the aggregator intermediary completely:
Every subsystem in YOUPI PG adheres to eight strict mathematical and operational invariants:
### Invariant 1 — Deterministic Amount-Only Attribution
+
Payment attribution enforces a strict equality invariant:
$$\text{expected\_amount} == \text{observed\_amount}$$
The system never uses fuzzy matching, probabilistic scoring, or guesswork. A payment session transitions to `SUCCESS` if and only if an observed banking credit exactly matches the session's expected amount on the assigned receiving account.
### Invariant 2 — Exclusive Single-Active-Slot FIFO Queue
+
Because standard P2P UPI transfers do not carry programmatic merchant transaction IDs in bank SMS alerts, multiple simultaneous transactions of identical amounts on the same VPA would cause attribution ambiguity.
+
- **The Invariant:** Exactly **ONE** customer payment session can occupy an `ACTIVE` or `PROCESSING` state on a given receiving VPA at any instant.
- **Concurrency Management:** Additional concurrent customers are serialized into a database-backed **FIFO Queue** (`QUEUED` state).
- **Live Promotion:** As soon as the active session succeeds, fails, or expires, the queue arbiter atomically promotes customer #1 to `ACTIVE` and pushes real-time Server-Sent Events (SSE) to update the customer's browser.
### Invariant 3 — Server-Authoritative Decoupled Dual Timers
+
Timing is governed exclusively by the backend state machine, not client-side JavaScript:
+
1. **5-Minute Payment Window (`ACTIVE`):** Countdown for the customer to scan the QR code and pay. Remains immutable across browser refreshes and server reboots.
-2. **30-Second Verification Window (`PROCESSING`):** Triggered when the customer clicks *"PAYMENT DONE — CHECK MY PAYMENT"*. Decoupled from the 5-minute timer to allow dedicated, high-frequency observer polling.
+2. **30-Second Verification Window (`PROCESSING`):** Triggered when the customer clicks _"PAYMENT DONE — CHECK MY PAYMENT"_. Decoupled from the 5-minute timer to allow dedicated, high-frequency observer polling.
### Invariant 4 — Pure Vector SVG QR Code Engine
+
Generates mathematically genuine ISO/IEC 18004 compliant vector SVG QR codes for standard UPI URIs (`upi://pay?pa=...&pn=...&am=...&cu=INR&tn=...`).
+
- Zero reliance on external Google Charts or third-party image generation APIs.
- Sub-second vector generation that scales crisply to any resolution.
### Invariant 5 — Integer Minor Units (Paise) Arithmetic
+
All financial calculations, database fields, and API contracts represent money strictly as 64-bit integer minor units (**Paise**).
+
- ₹1.00 = `100` paise | ₹499.00 = `49900` paise.
- Zero floating-point representation (`0.1 + 0.2` rounding errors are mathematically impossible).
### Invariant 6 — Gateway-Owned Pre-Checkout Identity
+
The Payment Gateway is the exclusive owner of customer authentication. Merchandising storefronts do not collect or verify customer mobile credentials:
+
- Customers authenticate via **WhatsApp OTP** powered by Berry Protocol / Baileys multi-device socket.
- Eliminates phone number spoofing, unauthenticated bot sessions, and fake orders before slot allocation.
### Invariant 7 — Pure Source & SQLite WAL Architecture
+
The active production persistence layer uses Node.js native `node:sqlite` (`DatabaseSync`) operating in Write-Ahead Logging (`WAL`) mode with foreign key constraints enabled (`PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`).
+
- Zero external database daemon dependencies.
- Zero Docker container overhead.
### Invariant 8 — Zero-Config Database Auto-Provisioning
+
On first system boot or after cloning, YOUPI PG guarantees zero-config database provisioning:
+
- Automatically detects if `data/youpi_pg.sqlite` and core tables exist (`SELECT count(*) FROM sqlite_master WHERE type='table' AND name='merchants'`).
- If missing, creates the parent directory `data/` and runs all schema DDL and baseline seeds idempotently before accepting HTTP traffic.
- Eliminates manual database creation scripts and avoids runtime `SqliteError: no such table` crashes entirely.
@@ -149,6 +168,7 @@ flowchart TB
## 4. Subsystem Deep-Dive
### 4.1 Invariant Single-Slot Queue Engine
+
The queue engine guarantees serialized, non-conflicting payment slot assignment.
```mermaid
@@ -156,19 +176,19 @@ stateDiagram-v2
[*] --> INITIATED : Merchant creates checkout session
INITIATED --> AUTH_PENDING : Customer arrives at portal
AUTH_PENDING --> AUTHENTICATED : WhatsApp OTP verified
-
+
AUTHENTICATED --> ACTIVE : Slot available (is_slot_busy = 0)
AUTHENTICATED --> QUEUED : Slot occupied (assigned FIFO position #1, #2...)
-
+
QUEUED --> ACTIVE : Prior session completes or expires
-
+
ACTIVE --> PROCESSING : Customer clicks "Payment Done" (30s timer)
ACTIVE --> EXPIRED : 5:00 payment window elapses
ACTIVE --> CANCELLED : Customer cancels session
-
+
PROCESSING --> SUCCESS : Bank credit verified (L1/L2/L3)
PROCESSING --> FAILED : 30s expires with zero credit match
-
+
SUCCESS --> [*]
FAILED --> [*]
EXPIRED --> [*]
@@ -176,34 +196,49 @@ stateDiagram-v2
```
#### Atomic Slot Acquisition Logic
+
```javascript
// packages/core/src/queue-engine.js (Abstracted Schema)
-db.exec('BEGIN IMMEDIATE TRANSACTION');
-const account = db.prepare('SELECT is_slot_busy FROM payment_receiving_accounts WHERE id = ?').get(accountId);
+db.exec("BEGIN IMMEDIATE TRANSACTION");
+const account = db
+ .prepare("SELECT is_slot_busy FROM payment_receiving_accounts WHERE id = ?")
+ .get(accountId);
if (!account.is_slot_busy) {
// Acquire Slot Immediately
- db.prepare('UPDATE payment_receiving_accounts SET is_slot_busy = 1 WHERE id = ?').run(accountId);
- db.prepare(`UPDATE payment_sessions SET
+ db.prepare(
+ "UPDATE payment_receiving_accounts SET is_slot_busy = 1 WHERE id = ?",
+ ).run(accountId);
+ db.prepare(
+ `UPDATE payment_sessions SET
status = 'ACTIVE',
expires_at = datetime('now', '+5 minutes'),
activated_at = datetime('now')
- WHERE id = ?`).run(sessionId);
+ WHERE id = ?`,
+ ).run(sessionId);
} else {
// Enqueue Customer
- const nextPos = db.prepare('SELECT COALESCE(MAX(queue_position), 0) + 1 AS pos FROM payment_sessions WHERE receiving_account_id = ? AND status = "QUEUED"').get(accountId).pos;
- db.prepare(`UPDATE payment_sessions SET
+ const nextPos = db
+ .prepare(
+ 'SELECT COALESCE(MAX(queue_position), 0) + 1 AS pos FROM payment_sessions WHERE receiving_account_id = ? AND status = "QUEUED"',
+ )
+ .get(accountId).pos;
+ db.prepare(
+ `UPDATE payment_sessions SET
status = 'QUEUED',
queue_position = ?
- WHERE id = ?`).run(nextPos, sessionId);
+ WHERE id = ?`,
+ ).run(nextPos, sessionId);
}
-db.exec('COMMIT');
+db.exec("COMMIT");
```
---
### 4.2 Customer Pre-Gateway WhatsApp Authentication Engine
+
To prevent phone spoofing, bots, and unauthenticated slot exhaustion, customer identity is owned exclusively by the gateway before payment timers begin:
+
1. **Step 1 — Mobile Input:** Customer enters 10-digit Indian mobile number.
2. **Step 2 — User Check:** Gateway checks `customers` table. If existing, dispatches OTP immediately; if new, captures full name and optional email first.
3. **Step 3 — 6-Digit WhatsApp OTP:** The gateway's Baileys multi-device socket generates a cryptographically secure 6-digit numeric OTP and delivers it directly to the customer's WhatsApp app.
@@ -212,16 +247,19 @@ To prevent phone spoofing, bots, and unauthenticated slot exhaustion, customer i
---
### 4.3 Tri-Channel Banking Observation Engine
+
YOUPI PG captures bank credit alerts across three redundant layers:
-| Layer | Component | Mechanism | Security & Integrity |
-| :--- | :--- | :--- | :--- |
+| Layer | Component | Mechanism | Security & Integrity |
+| :---------- | :-------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Layer 1** | **Native Android APK** (`com.youpi.observer`) | Intercepts cellular SMS (`android.provider.Telephony.SMS_RECEIVED`) and bank push notifications via `NotificationListenerService`. | Paired via ephemeral QR enrollment token. Dispatches payloads to `/api/v1/observers/sms` signed with **HMAC-SHA256(deviceSecret)** and anti-replay timestamp drift protection ($<60$s). |
-| **Layer 2** | **Gmail Observer** (Port 6003) | Google Cloud OAuth2 API polling (`users.messages.list`) or headless CDP Chrome inbox scraper (`@youpi/observer-sdk`). | Scans incoming bank transaction emails matching regex patterns (HDFC, ICICI, SBI, Axis, Kotak, PNB). |
-| **Layer 3** | **SMS Observer** (Port 6002) | Headless Chrome CDP automation pairing with Google Messages for Web (`messages.google.com/web`). | Real-time DOM text parsing extracting incoming SMS banking alerts without physical phone cables. |
+| **Layer 2** | **Gmail Observer** (Port 6003) | Google Cloud OAuth2 API polling (`users.messages.list`) or headless CDP Chrome inbox scraper (`@youpi/observer-sdk`). | Scans incoming bank transaction emails matching regex patterns (HDFC, ICICI, SBI, Axis, Kotak, PNB). |
+| **Layer 3** | **SMS Observer** (Port 6002) | Headless Chrome CDP automation pairing with Google Messages for Web (`messages.google.com/web`). | Real-time DOM text parsing extracting incoming SMS banking alerts without physical phone cables. |
#### Unified Normalization & Deduplication
+
Every incoming observation passes through `ObservationNormalizer`:
+
- Extracts normalized fields: `amountPaise`, `receivingAccount`, `utr`, `senderVpa`, `timestamp`.
- Computes observation cluster fingerprint:
$$\text{hash} = \text{SHA-256}(\text{receivingAccount} + \text{amountPaise} + \text{utr} + \text{timeBucket})$$
@@ -237,11 +275,11 @@ Every incoming observation passes through `ObservationNormalizer`:
```mermaid
graph TD
GatewayMode[Operational Modality]
-
+
GatewayMode --> OnlineMode[Online Selling Mode]
OnlineMode --> OnlineUPI[UPI Vector QR Code]
OnlineMode --> OnlineCOD[Cash on Delivery with WhatsApp Pre-Verification]
-
+
GatewayMode --> OfflineMode[Offline Store Counter Mode]
OfflineMode --> OfflineUPI[Customer-Facing Dynamic QR]
OfflineMode --> OfflineCash[Cash at Till Desk - CASH_COUNTER]
@@ -263,40 +301,51 @@ graph TD
YOUPI PG distributes a single, framework-independent universal browser bundle: [`/youpi.js`](apps/checkout-portal/src/sdk/youpi.js).
#### 1. Zero-JS Declarative Button Embedding
+
Merchants add the script and declarative attributes to any HTML button:
-```html
-<script src="https://pay.yourdomain.com/youpi.js" data-youpi-key="MERCHANT_PUBLIC_KEY"></script>
-<button data-youpi-pay
- data-order-id="ORD-1001"
- data-amount="499.00"
- data-currency="INR">
+```html
+<script
+ src="https://pay.yourdomain.com/youpi.js"
+ data-youpi-key="MERCHANT_PUBLIC_KEY"
+></script>
+
+<button
+ data-youpi-pay
+ data-order-id="ORD-1001"
+ data-amount="499.00"
+ data-currency="INR"
+>
Buy Now with YOUPI PG
</button>
```
#### 2. Programmatic Invocation (`Youpi.pay`)
+
For SPAs (React, Next.js, Vue, Nuxt, Angular):
+
```javascript
window.Youpi.pay({
checkoutUrl: session.checkoutUrl,
- order_id: 'ORD-1001',
- amount: 499.00,
- currency: 'INR',
- name: 'Acme Store',
- description: 'Digital License Top-Up',
- handler: function(response) {
+ order_id: "ORD-1001",
+ amount: 499.0,
+ currency: "INR",
+ name: "Acme Store",
+ description: "Digital License Top-Up",
+ handler: function (response) {
// response: { status: 'SUCCESS', order_id, amount_received, utr }
- console.log('Payment Confirmed! UTR:', response.utr);
+ console.log("Payment Confirmed! UTR:", response.utr);
+ },
+ onClose: function () {
+ console.log("Customer dismissed modal");
},
- onClose: function() {
- console.log('Customer dismissed modal');
- }
});
```
#### 3. Standardized Browser DOM CustomEvents
+
Driven directly on `window` for reactive UI animations:
+
- `youpi:payment:success` (`e.detail: { order_id, amount_received, utr }`)
- `youpi:payment:failed` (`e.detail: { order_id, reason }`)
- `youpi:payment:suspicious` (`e.detail: { order_id }`)
@@ -304,6 +353,7 @@ Driven directly on `window` for reactive UI animations:
- `youpi:payment:cancelled` (`e.detail: { order_id }`)
#### 4. Authoritative Webhook Security Contract
+
Frontend browser events are never trusted for order fulfillment or provisioning digital goods. Order completion requires verifying the authoritative server-to-server webhook:
- **Cryptographic Signature:** Generated via HMAC-SHA256 using the merchant's `webhookSecret` and delivered in header `X-Gateway-Signature: sha256=<64_char_hex_hash>`.
@@ -312,30 +362,40 @@ Frontend browser events are never trusted for order fulfillment or provisioning
- **Replay Protection & Idempotency:** Every delivery carries an `X-Gateway-Timestamp` (millisecond epoch) and unique `X-Gateway-Delivery-Id` (UUIDv4) to guarantee idempotent order fulfillment and prevent replay attacks.
```javascript
-import crypto from 'node:crypto';
-
-app.post('/api/youpi-webhook', express.raw({ type: 'application/json' }), (req, res) => {
- const signature = req.headers['x-gateway-signature'] || '';
- const secret = process.env.YOUPI_WEBHOOK_SECRET;
- const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(req.body).digest('hex');
-
- if (signature.length !== expected.length ||
- !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
- return res.status(401).json({ error: 'Signature mismatch' });
- }
-
- const event = JSON.parse(req.body.toString('utf8'));
- if (event.event === 'SUCCESS') {
- fulfillOrder(event.orderId, event.utr, event.amount);
- }
- res.json({ received: true });
-});
+import crypto from "node:crypto";
+
+app.post(
+ "/api/youpi-webhook",
+ express.raw({ type: "application/json" }),
+ (req, res) => {
+ const signature = req.headers["x-gateway-signature"] || "";
+ const secret = process.env.YOUPI_WEBHOOK_SECRET;
+ const expected =
+ "sha256=" +
+ crypto.createHmac("sha256", secret).update(req.body).digest("hex");
+
+ if (
+ signature.length !== expected.length ||
+ !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
+ ) {
+ return res.status(401).json({ error: "Signature mismatch" });
+ }
+
+ const event = JSON.parse(req.body.toString("utf8"));
+ if (event.event === "SUCCESS") {
+ fulfillOrder(event.orderId, event.utr, event.amount);
+ }
+ res.json({ received: true });
+ },
+);
```
---
### 4.6 5 Standardized Merchant Outcome Pages
+
To prevent broken 404 links and inconsistent customer experiences, YOUPI PG provides 5 canonical outcome pages served from Port 5000:
+
1. **`/order-success`:** Confirmed bank credit, displays verified UTR, provisions license/digital product.
2. **`/order-failed`:** Informs buyer that verification timed out and confirms zero funds were deducted.
3. **`/order-suspicious`:** Flagged by fraud heuristics; order held for manual merchant audit.
@@ -345,28 +405,36 @@ To prevent broken 404 links and inconsistent customer experiences, YOUPI PG prov
---
### 4.7 White-Label Customization Engine
-Configured via Tab 5 of the Merchant Admin dashboard and persisted in `merchants.branding` JSON:
+
+YOUPI PG implements a **3-Tier Hierarchical Branding Engine** ensuring platform instances can be fully customized or whitelisted per merchant:
+
+1. **Tier 1 (Global Environment Defaults):** Configured via `.env` (`DEFAULT_APP_NAME`, `DEFAULT_PRIMARY_COLOR`, `DEFAULT_SUPPORT_EMAIL`, `DEFAULT_SUPPORT_PHONE`, `DEFAULT_LOGO_URL`, `DEFAULT_TRUST_BADGE_TEXT`, `DEFAULT_FOOTER_GUARANTEE`, `WHATSAPP_SENDER_NAME`).
+2. **Tier 2 (Per-Merchant Database Record):** Configured via Tab 5 of the Merchant Admin dashboard and persisted in `merchants.branding` JSON (`appName`, `primaryColor`, `logoUrl`, `customCss`, etc.).
+3. **Tier 3 (Runtime Session Resolution):** Cascades dynamically: `session.branding || merchant.branding || env.DEFAULT_* || 'YOUPI PG'`.
+
+Key capabilities:
+
- **Merchant Brand Name & Subtitle**
-- **Custom Logo URL & Favicon**
+- **Custom Logo URL & Dynamic Monogram Fallback**
- **Custom Accent Color (`--primary`) & Header Gradients**
- **Trust Badges & Security Sub-banners**
- **Cloudflare Tunnel Custom Domain Binding (`pay.yourdomain.com`)**
-- **Complete Removal of "Powered by YouPI PG" Attribution**
+- **Complete Elimination of Default Platform Attribution (`DEFAULT_HIDE_POWERED_BY=true`)**
---
## 5. Network Topology & Port Bindings
-| Service | Port | Process Entrypoint | Health Route | Primary Purpose |
-| :--- | :---: | :--- | :--- | :--- |
-| **Payment Core API** | `6100` | `apps/payment-api/src/index.js` | `GET /health` | State machine, atomic DB transactions, REST API, SSE streams |
-| **Checkout Portal** | `7000` | `apps/checkout-portal/src/index.js` | `GET /health` | Customer iframe checkout, dynamic Vector QR, SDK bundle |
-| **Merchant Admin** | `6001` | `apps/merchant-admin/src/index.js` | `GET /health` | Admin dashboard, cashier desk, branding customizer, WhatsApp pairing |
-| **Showcase Demo Store** | `5000` | `apps/coin-wallet-store/src/index.js` | `GET /health` | Reference enterprise merchant store, outcome pages showcase, SDK testbed |
-| **Control Center** | `8090` | `apps/control-center/src/index.js` | `GET /health` | Local process supervisor for starting, stopping, and logging all services |
-| **SMS Observer** | `6002` | `apps/sms-observer/src/index.js` | `GET /health` | Google Messages Web CDP automation for cellular SMS parsing |
-| **Gmail Observer** | `6003` | `apps/gmail-observer/src/index.js` | `GET /health` | Google Cloud OAuth2 API & Chrome CDP inbox monitoring |
-| **Android SMS APK** | N/A | Native Android Device (Foreground) | N/A | Captures incoming cellular banking SMS & push notifications |
+| Service | Port | Process Entrypoint | Health Route | Primary Purpose |
+| :---------------------- | :----: | :------------------------------------ | :------------ | :------------------------------------------------------------------------ |
+| **Payment Core API** | `6100` | `apps/payment-api/src/index.js` | `GET /health` | State machine, atomic DB transactions, REST API, SSE streams |
+| **Checkout Portal** | `7000` | `apps/checkout-portal/src/index.js` | `GET /health` | Customer iframe checkout, dynamic Vector QR, SDK bundle |
+| **Merchant Admin** | `6001` | `apps/merchant-admin/src/index.js` | `GET /health` | Admin dashboard, cashier desk, branding customizer, WhatsApp pairing |
+| **Showcase Demo Store** | `5000` | `apps/coin-wallet-store/src/index.js` | `GET /health` | Reference enterprise merchant store, outcome pages showcase, SDK testbed |
+| **Control Center** | `8090` | `apps/control-center/src/index.js` | `GET /health` | Local process supervisor for starting, stopping, and logging all services |
+| **SMS Observer** | `6002` | `apps/sms-observer/src/index.js` | `GET /health` | Google Messages Web CDP automation for cellular SMS parsing |
+| **Gmail Observer** | `6003` | `apps/gmail-observer/src/index.js` | `GET /health` | Google Cloud OAuth2 API & Chrome CDP inbox monitoring |
+| **Android SMS APK** | N/A | Native Android Device (Foreground) | N/A | Captures incoming cellular banking SMS & push notifications |
---
@@ -391,10 +459,13 @@ data/youpi_pg.sqlite
## 7. Verification & Quality Assurance Suite
YOUPI PG enforces zero regression via a unified test runner:
+
```bash
node scripts/test-all.js
```
-The suite executes **31 curated test suites** across packages, applications, and chaos-concurrency harnesses in under 18 seconds:
+
+The suite executes **39 curated test suites** across packages, applications, and chaos-concurrency harnesses in under 35 seconds:
+
- **Common & Contracts:** Types, enums, paise minor units, UPI URIs, crypto builders.
- **Database & Repositories:** SQLite migrations, foreign keys, transaction rollbacks, auth matrix.
- **Core Engine:** Queue arbitration, dual timers, attribution normalizer, webhooks.
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index e94a9f8..73ea854 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -23,46 +23,61 @@ This document describes how to deploy and run the clean distributable **YOUPI PG
## 2. Installation Steps
### Step 1: Extract / Clone Package
+
Ensure you are in the package root directory:
+
```bash
cd "YOUPI PG PACKAGE"
```
### Step 2: Configure Environment
+
Copy the clean template to `.env`:
+
```bash
cp .env.example .env
```
+
Open `.env` in your editor and configure:
+
1. `ENCRYPTION_MASTER_KEY`: Generate a 64-character hex key (e.g. `node -e "console.log(crypto.randomBytes(32).toString('hex'))"`).
2. `JWT_SECRET`: Random string at least 32 characters.
3. `INITIAL_ADMIN_EMAIL` and `INITIAL_ADMIN_PASSWORD`: Credentials for your Merchant Admin dashboard.
4. `BASE_PAYMENT_API_URL` and `BASE_CHECKOUT_URL`: Your public domain or localhost URLs.
+5. `DEFAULT_APP_NAME`, `DEFAULT_PRIMARY_COLOR`, `DEFAULT_SUPPORT_EMAIL`: (Optional) White-label branding defaults (see `docs/WHITE_LABEL.md`).
### Step 3: Install Dependencies
+
```bash
npm install
```
### Step 4: Initialize Fresh Database
+
Run the automated database setup to initialize schema and seed the default merchant and receiving account:
+
```bash
npm run db:setup
```
-*(Creates `data/youpi_pg.sqlite` in clean state with 0 transactions).*
+
+_(Creates `data/youpi_pg.sqlite` in clean state with 0 transactions)._
### Step 5: Start the System
#### Development / Demonstration Mode:
+
```bash
npm run dev
```
+
Starts all services with live reload and console aggregation under the Control Center at `http://localhost:8090`.
#### Production Mode:
+
```bash
npm run start
```
+
Starts services in background daemon mode.
---
@@ -84,7 +99,8 @@ Starts services in background daemon mode.
## 4. Production Domain & SSL (Cloudflare / NGINX)
For production deployment:
+
1. Terminate SSL at your reverse proxy (NGINX, Caddy, or Cloudflare Tunnel).
2. Point your public domain (e.g. `pay.yourdomain.com`) to port `7000` (Checkout Portal) or `6100` (Payment API).
- *The Checkout Portal automatically proxies all `/api/*` requests to the Payment API.*
+ _The Checkout Portal automatically proxies all `/api/_` requests to the Payment API.\*
3. Update `BASE_PAYMENT_API_URL` and `BASE_CHECKOUT_URL` in `.env` to match your public HTTPS domain.