backend contracts

Guide for backend contracts

LoH E-commerce API Contracts & Backend Requirements

IMPORTANT
This document defines the interface between the Next.js Frontend (loh-website) and the Backend Game Services (loh-backend / loh-payments).

1. Security & Compliance Architecture

1.1 PCI Compliance

  • Requirement: SAQ A-EP or SAQ A.
  • Implementation:
    • Frontend never touches raw card data.
    • Use Hosted Fields (Adyen/Stripe Elements) or Redirect.
    • Backend only receives payment_method_nonce or token.
    • No credit card numbers in logs or DB.

1.2 Fraud & Bot Prevention

  • Rate Limiting:
    • Global: 100 req/min per IP.
    • Auth/Checkout: 5 req/min per IP.
    • Use Redis-backed sliding window limiter.
  • Bot Detection:
    • Cloudflare Turnstile or Google reCAPTCHA v3 on Login/Register/Checkout.
    • User-Agent Analysis: Reject known headless browsers.
    • Velocity Checks: Block IPs with >3 failed payments in 1 hour.
  • Fraud Checks:
    • 3D Secure 2.0 (SCA) mandatory for EU/likely fraud.
    • Address Verification (AVS).
    • Email Age/Reputation Check (Optional 3rd party).

1.3 Access Control (RBAC)

  • Roles:
    • SUPER_ADMIN: Full access to all endpoints.
    • SUPPORT_AGENT:
      • Can: GET /orders, GET /customers, POST /orders/:id/refund (Limit < $100).
      • Cannot: Modify Products, Coupons, or Infrastructure.
    • CONTENT_MANAGER:
      • Can: POST/PUT /products, POST/PUT /coupons.
      • Cannot: View PII (Customer data), Process Refunds.
  • Authentication Strategy:
    • Backoffice (/admin):
      • Protocol: OIDC (OpenID Connect).
      • Provider: Zoho Directory / Zoho One.
      • Flow: User clicks "Login with Zoho" -> Redirect to Zoho -> Callback to /api/auth/callback/zoho.
    • Storefront (/store):
      • Protocol: OAuth2 / JWT.
      • Providers: Email/Password, Discord, Google.
  • Implementation:
    • JWT Claims include role and permissions.
    • Frontend: ProtectRoute component checks role requirements.
    • Backend: Middleware validates scopes/roles per endpoint.

2. API Endpoints

2.1 Storefront API (/api/v1/store)

Products

  • GET /products
    • Returns active SKUs (Bronze, Silver, Gold).
    • Response: [{ id: "sku_123", name: "Gold Pack", price_cents: 9999, currency: "USD", metadata: {...} }]
  • GET /products/:id

Cart & Checkout

  • POST /cart/validate
    • Input: items: [{sku, qty}], coupon_code?.
    • Returns: subtotal, discount_amount, total, tax_estimate.
    • Logic: Validates coupon rules, product availability.
  • POST /checkout/intent
    • Input: cart_data, user_id.
    • Returns: payment_intent_token (for client-side SDK).
  • POST /checkout/finalize
    • Input: payment_token, payment_method_id.
    • Returns: order_id, status: "processing" | "success".
    • Trigger: Starts "Bond Generation" workflow async.

My Orders

  • GET /orders (Auth Required)
    • Returns list of past orders.
  • GET /orders/:id
    • Details: Items, Payment Status, Invoice PDF link.

2.2 Backoffice API (/api/v1/admin)

Requires role: "admin"

Product Management

  • POST /products (Create SKU)
  • PUT /products/:id (Update Pricing, Metadata)
    • Fields: name, price, active, inventory_cap (optional).
  • DELETE /products/:id (Soft delete)

Coupon Management

  • POST /coupons
    • Fields: code (e.g. FOUNDER20), type (% or flat), value, max_uses, expiry_date.
  • GET /coupons
  • PUT /coupons/:id/deactivate

Order Operations

  • GET /orders (Filter by status, date, user email)
  • POST /orders/:id/refund
    • Input: amount, reason.
    • Action: Calls Payment Gateway Refund API + Revokes Game items.
  • POST /orders/:id/fulfill_manual
    • Force triggers fulfillment (Bond generation).

2.3 Game Services Integration ("The Bond System")

Fulfillment Workflow

  1. Payment Success Webhook -> Backend.
  2. Backend verifies payment.
  3. Bond Generator:
    • Creates unique BondItem in loh-game DB.
    • Assigns to Player Inventory (if linked).
    • Or generates Redemption Key (sent via email).
  4. POST /game/deliver_bond
    • Internal service call.

2.4 Pricing Engine Rules

  • Bulk Membership Discounts:
    • Buying membership for 2 Characters: 15% OFF total membership cost.
    • Buying membership for 3+ Characters: 33% OFF total membership cost.
    • Logic applied automatically in /cart/validate.

2.5 Chargeback Workflow (Risk)

  • Trigger: Payment Gateway sends CHARGEBACK webhook.
  • Logic:
    1. Mark Transaction as DISPUTED.
    2. Check Usage:
      • If Membership active > 5 days OR Bond consumed: Action: FREEZE ACCOUNT.
      • If Membership active < 5 days: Action: CANCEL MEMBERSHIP (Revoke days).
    3. Apply Debt:
      • Add outstanding_debt_cents to the specific Character.
      • Character is LOCKED until debt is cleared.
    4. Recovery:
      • User logs in -> Prompted to pay "Outstanding Balance".
      • Payment Success -> Debt cleared -> Character Unlocked -> Account Unfrozen.

2.6 Growth Engine (Incentives)

A. "Bandhu" System (Player Referral)

  • Attribution: 1 Referral Credit per Unique Email (Account). Multiple characters do not count.
  • Constraint: Max 15 Days Membership reward every 6 Months per Account.
  • Anti-Fraud:
    • Recruits must complete Tutorial + 150 Total Level.
    • Trade Limit: Recruits capped at 1,000 Gold trades until 150 Total Level.
  • Rewards:
    • Signup: 10k Coins (Both).
    • Purchase: Referee gets 5% Off + 1 XP Orb.
    • Milestone 5: 7 Days Mem + 1 XP Orb.
    • Milestone 10: 8 Days Mem + 3 XP Orbs.

B. "Reserve Slot" (Pre-Registration)

  • Endpoint: POST /store/reserve
  • Body: { "email": "..." }
  • Response: { "position": 1243, "referral_code": "..." }

C. "Rajdoot" Program (Affiliates/Influencers)

  • Mechanic: Application required. Approval by Admin.
  • Incentive Options (Selectable per Payout):
    1. Cash: 10% Revenue Share (Net-60 Bank Transfer).
    2. Store Credit: 20% value (2x of Cash rate) in Bonds/Memberships.
    3. Gift Codes: 15-Day Membership Codes (Equivalent value to Store Credit).
      • Feature: Codes are transferable. Influencer can Giveaway or Resell to audience.
  • Dashboard: View earnings -> "Convert to Gift Codes" button.

3. Data Models (Schema Contracts)

User Account & Characters

{
  "account_id": "usr_123",
  "email": "hero@hastinapur.com",
  "is_founder": true,
  "founder_tier": "GOLD",
  "referral_code": "HERO123",
  "referred_by": "usr_999",
  "is_affiliate": true,
  "affiliate_settings": {
     "payout_method": "BANK",
     "rev_share_pct": 15,
     "total_earnings_cents": 50000
  },
  "status": "ACTIVE | FROZEN",
  "frozen_reason": "CHARGEBACK | BAN | SECURITY",
  "characters": [
    {
       "character_id": "char_A",
       "display_name": "Arjuna",
       "membership_expiry": "2026-01-01",
       "outstanding_debt_cents": 0,
       "game_stats": {...}
    },
    {
       "character_id": "char_B",
       "display_name": "Bhima",
       "membership_expiry": null,
       "outstanding_debt_cents": 1999
    }
  ]
}

SKU (Product)

{
  "sku_id": "string",
  "name": "string",
  "base_price_cents": "integer",
  "currency": "string",
  "active": "boolean",
  "sku_type": "MEMBERSHIP | ITEM | BUNDLE",
  "rewards": {
    "game_items": ["item_id_1"],
    "membership_days": 30,
    "bond_credits": 1
  }
}

New Standard SKUs

  • MEMBERSHIP_1M: 1 Month Access ($11.99)
  • MEMBERSHIP_1Y: 1 Year Access ($99.99) - Includes 2 month discount built-in
  • FOUNDER_BRONZE: Warrior Pack
  • FOUNDER_SILVER: Acharya Pack
  • FOUNDER_GOLD: Maharathi Pack

Order

{
  "order_id": "string",
  "user_id": "string",
  "status": "PENDING_PAYMENT | PAID | FAILED | REFUNDED",
  "fulfillment_status": "UNFULFILLED | FULFILLED | ERROR",
  "total_cents": "integer",
  "line_items": [...],
  "payment_provider_id": "string",
  "risk_score": 0.05,
  "created_at": "ISO8601",
  "transactions": [
    {
      "id": "txn_123",
      "psp_reference": "adyen_lvl2_890",
      "type": "AUTH | CAPTURE | REFUND | CHARGEBACK",
      "amount_cents": 1999,
      "status": "SUCCESS | FAILED",
      "timestamp": "ISO8601"
    }
  ],
  "audit_log": [
    {
      "event": "ORDER_CREATED",
      "timestamp": "...",
      "actor": "system | user | admin_id"
    },
    {
      "event": "PO_GENERATED",
      "metadata": { "po_id": "PO-999" }
    },
    {
      "event": "BOND_DELIVERED",
      "metadata": { "bond_id": "bond_777" }
    }
  ]
}

### Purchase Order (PO) - Internal
{
  "po_id": "PO-999",
  "order_id": "...",
  "status": "GENERATED | FULFILLED",
  "sku_snapshot": {...}
}

### Coupon
{
  "code": "string",
  "discount_type": "PERCENTAGE | FLAT",
  "value": 20,
  "usage_count": 0,
  "usage_limit": 1000,
  "expires_at": "ISO8601"
}