Skip to content

Payments & Wallet Integration (Enterprise Spec) โ€‹

The LuxurAI platform is backed by a transactional, secure virtual wallet operating on Lunar Coins (LC). Users purchase LC credits to run high-performance AI API calls, execute large agentic coding tasks, and synthesize real-time neural voice (322 models across 142 languages).

This document serves as an exhaustive integration guide detailing the coin-package economics, API payloads, complete transaction verification loops, and cryptographic webhook verification standards.


๐Ÿ“ˆ The Lunar Coin Economic Model โ€‹

Lunar Coins (LC) are structured to provide a highly flexible, subscription-free payment model. Credits are loaded onto user accounts via multiple secure Indian and global gateways.

1. Predefined Coin Packages โ€‹

Packages are parsed from a single source of truth within the backend to ensure zero price-hijacking. To support global users, the engine automatically detects geographic location and applies dual-currency configurations (INR for India, USD for international users):

Package IDLC CreditsPrice (INR)Converted Price (USD)*Real-world Use Case
trial60 LCโ‚น17.70~$0.62 USDTrying models and prompt testing
starter100 LCโ‚น29.50~$0.79 USDLight development and debugging
basic200 LCโ‚น53.10~$1.13 USDMedium scripting tasks
popular500 LCโ‚น129.09~$2.22 USDMost Popular: Standard dev workflow
pro1200 LCโ‚น300.90~$4.68 USDProfessional engineering tasks
luxpro13,333 LCโ‚น2,360.00~$34.18 USDBulk multi-agent cycles & team usage

*Note: Converted USD prices fluctuate dynamically based on the USD/INR conversion rate and PayPal gateway fees. The formula used is: $$\text{Final USD} = \frac{\frac{\text{Target INR}}{\text{USD_Rate} - 10} + 0.354}{0.956}$$

  • Custom Pack Operations: Users can purchase any custom amount above 20 LC at a flat rate of โ‚น0.35 per LC (or equivalent in USD calculated via the conversion formula).

2. The Saturday "Jumbo Week" Special โ€‹

The backend runs a dynamic time-locked discount validator:

  • Window: Every Saturday between 9:00 AM โ€“ 7:00 PM IST.
  • Offer: Unlocks the exclusive jumbo pack (5,050 LC for just โ‚น1,191.80, delivering a rate of โ‚น0.23/LC).
  • API Route: GET /api/payment/jumbo/status returns whether the offer is live, including the next opening/closing windows.

3. Neural Voice Duration Pricing (322 Voices) โ€‹

Voice synthesis on /api/tts/speak and via the Python SDK is charged strictly by duration:

  • Base Rate: 20.0 LC / hour of generated audio (equivalent to โ‚น5.00 / hour).
  • Per-Second Rate: Approx. 0.0055 LC / second (~โ‚น0.00138 / second).
  • Cache Hits: Identical synthesis queries served from the in-memory LRU cache incur 0 LC.
  • Billing Details: Exact duration and LC charged are returned in the X-Audio-Duration and X-LC-Charged response headers.

๐Ÿ”Œ API Endpoints Reference โ€‹

All transactions are managed securely under the /api/payment prefix.

1. Retrieve Available Packages (Geo-Aware) โ€‹

Fetch the live package configuration and pricing details. The server automatically detects the user's location via IP address and formats pricing accordingly.

  • Endpoint: GET /api/payment/packs
  • Success Response (200 OK - International Visitor):
    json
    {
      "currency": "USD",
      "symbol": "$",
      "gateway": "paypal",
      "txn_fee_pct": 10.0,
      "packs": [
        {
          "id": "starter",
          "lc": 100,
          "price": 0.79,
          "inr": 29.5,
          "label": "Starter",
          "per_lc": 0.0079,
          "savings_pct": 15.7
        }
      ],
      "custom": {
        "min_lc": 20.0,
        "rate": 0.0079,
        "note": "Buy any amount from 20 LC at $0.0079/LC"
      },
      "token_pricing": {
        "input_token_cost": 0.0000025,
        "output_line_cost": 0.00001
      }
    }

2. Retrieve Token Pricing Model โ€‹

Fetch the current token charging metrics in the user's local currency:

  • Endpoint: GET /api/payment/token-pricing
  • Success Response (200 OK):
    json
    {
      "country": "US",
      "currency": "USD",
      "symbol": "$",
      "gateway": "paypal",
      "txn_fee_pct": 10.0,
      "input_token_cost": 0.0000025,
      "output_line_cost": 0.00001
    }

2. Initialize Cashfree Order โ€‹

Initiate a transaction session at Cashfree to process UPI, Net Banking, or Cards.

  • Endpoint: POST /api/payment/cashfree/create-order
  • Request Headers:Content-Type: application/jsonAuthorization: Bearer <your_session_token>
  • Request Body:
    json
    {
      "pack_id": "popular",
      "custom_lc": null,
      "promo_code": "WELCOME50"
    }
  • Success Response (200 OK):
    json
    {
      "order_id": "cf_L9K28hJ29dKm812",
      "payment_session_id": "session_A889xH203JcKk981",
      "cashfree_mode": "production",
      "amount_inr": 116.18,
      "lc_amount": 500,
      "pack_label": "Popular",
      "discount_pct": 10,
      "original_inr": 129.09,
      "promo_applied": {
        "valid": true,
        "code": "WELCOME50",
        "discount_type": "percent",
        "discount_value": 10,
        "final_inr": 116.18
      },
      "expires_in_seconds": 900
    }

3. Initialize PayPal Order (International) โ€‹

Initiate a transaction session at PayPal to process global card payments. Converted amounts are calculated in USD using the live conversion formula.

  • Endpoint: POST /api/payment/paypal/create-order
  • Request Headers:Content-Type: application/jsonAuthorization: Bearer <your_session_token>
  • Request Body:
    json
    {
      "pack_id": "popular",
      "custom_lc": null,
      "promo_code": null
    }
  • Success Response (200 OK):
    json
    {
      "order_id": "PP-9K28hJ29dKm812",
      "approve_url": "https://www.sandbox.paypal.com/checkoutnow?token=PP-9K28hJ29dKm812",
      "amount_usd": 2.22,
      "fee_usd": 0.45,
      "lc_amount": 500,
      "gateway": "paypal"
    }

4. Capture PayPal Order โ€‹

Capture the payment after the user approves the transaction on the PayPal checkout screen. This completes the transaction and credits the user's virtual wallet.

  • Endpoint: POST /api/payment/paypal/capture/{order_id}
  • Request Headers:Content-Type: application/jsonAuthorization: Bearer <your_session_token>
  • Success Response (200 OK):
    json
    {
      "status": "success",
      "lc_credited": 500.0,
      "new_balance": 1820.5,
      "gateway": "paypal"
    }

3. Verify Transaction Status โ€‹

Verify payment state by polling after redirect:

  • Endpoint: GET /api/payment/verify/{order_id}
  • Success Response (200 OK):
    json
    {
      "status": "fulfilled",
      "lc_credited": 500.0,
      "new_balance": 1820.5
    }

๐Ÿ”’ Cryptographic Webhook Security โ€‹

To prevent "man-in-the-middle" hacks, all webhooks sent by gateways must be cryptographically validated.

๐Ÿ›ก๏ธ Cashfree Webhook Signature Check โ€‹

Cashfree sends a signature header inside successful webhook captures. Here is the actual Python server implementation used to verify signature payloads:

python
import hmac
import hashlib
import json

def verify_cashfree_signature(payload_bytes: bytes, x_signature: str, client_secret: str) -> bool:
    """
    Computes HMAC-SHA256 of the raw body payload bytes using 
    the Cashfree Client Secret key and compares signatures.
    """
    computed = hmac.new(
        client_secret.encode('utf-8'),
        payload_bytes,
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(computed, x_signature)

๐Ÿ–ฅ๏ธ Complete Webhook Handler Integration Code โ€‹

Here is a complete, deployable FastAPI endpoint showing how to receive, verify, and credit user wallets using Python and SQLite:

python
from fastapi import FastAPI, Request, HTTPException, Header
import aiosqlite
import logging

app = FastAPI()
logger = logging.getLogger("payment_webhook")

CASHFREE_SECRET_KEY = "your_private_cashfree_secret_key"
DB_PATH = "backend/data/luxurai.db"

@app.post("/api/payment/cashfree/webhook")
async def handle_cashfree_webhook(
    request: Request,
    x_cloudflare_signature: str = Header(None) # signature sent by gateway
):
    # 1. Capture raw payload bytes
    raw_payload = await request.body()
    
    # 2. Verify signature authenticity
    if not verify_cashfree_signature(raw_payload, x_cloudflare_signature, CASHFREE_SECRET_KEY):
        logger.warning("โŒ Security Alert: Invalid Cashfree Webhook signature!")
        raise HTTPException(status_code=400, detail="Invalid signature")
        
    # 3. Process payload
    payload = json.loads(raw_payload)
    event_type = payload.get("type")
    
    if event_type == "PAYMENT_SUCCESS_WEBHOOK":
        data = payload.get("data", {})
        order_id = data.get("order", {}).get("order_id")
        cf_payment_id = data.get("payment", {}).get("cf_payment_id")
        
        print(f"๐Ÿ’ฐ Payment Verified! Order: {order_id} | Ref: {cf_payment_id}")
        
        # 4. Credit Wallet (Safe Transaction)
        async with aiosqlite.connect(DB_PATH) as db:
            # Check if order is already fulfilled to prevent double-crediting
            async with db.execute("SELECT status, user_id, lc_amount FROM payment_orders WHERE order_id = ?", (order_id,)) as cursor:
                order = await cursor.fetchone()
                if order and order[0] != 'fulfilled':
                    user_id, lc_amount = order[1], order[2]
                    
                    # Update order status
                    await db.execute("UPDATE payment_orders SET status='fulfilled', fulfilled_at=datetime('now') WHERE order_id=?", (order_id,))
                    # Credit wallet
                    await db.execute("UPDATE wallets SET balance_lc = balance_lc + ? WHERE user_id = ?", (lc_amount, user_id))
                    await db.commit()
                    print(f"โœ… Credited {lc_amount} LC to User: {user_id}")
                    
    return {"status": "accepted"}

๐Ÿ›ก๏ธ PayPal Webhook (IPN) Integration โ€‹

PayPal webhooks are handled under /api/payment/paypal/webhook. The gateway triggers a PAYMENT.CAPTURE.COMPLETED notification.

  • Payload Custom ID: PayPal orders carry a metadata tag custom_id formatted as user_id|pack_id|lc_amount (e.g. usr_8K28dK|popular|500.0).
  • Asynchronous Crediting: The webhook parses this custom_id and performs database ledger operations to credit the user's wallet, ensuring that even if the client browser exits early during the capture redirect, the coins are safely credited.

๐Ÿ”‘ Social Authentication Session Mapping โ€‹

To support social login identity (e.g., Google OAuth), the authentication system operates on two databases:

  1. luxurai.db (Primary database containing user details, ledger entries, and wallets)
  2. luxurai_social.db (Social identity login mapping)

If a session token's user ID is not found directly inside the main users table:

  1. The auth middleware queries luxurai_social.db to retrieve the corresponding social email.
  2. It then queries the primary users table in luxurai.db by email to resolve the user's main account ID.
  3. Once mapped, the server fetches the correct wallet balance and ledger records, assuring unified wallet states across email/password and social login portals.

Proprietary & Confidential ยท Powered by LuxurAI