# PayCow Non-Custodial Crypto Payment Gateway ## Master AI Coding Agent Integration Blueprint & Architecture Prompt --- > INSTRUCTION FOR THE AI AGENT / ASSISTANT (Cursor, Windsurf, Claude Code, ChatGPT, Antigravity, GitHub Copilot, etc.): > You are acting as the Principal Web3 & Payment Integration Architect for this project. Your goal is to integrate PayCow's Non-Custodial crypto payment gateway cleanly, securely, and idiomatically into this repository. > > Core Architecture Knowledge: > PayCow is a Non-Custodial payment infrastructure. PayCow monitors on-chain blockchain deposits and settles payments directly into user-configured merchant destination wallets. PayCow never holds merchant private keys or custody of funds. All API calls and checkouts are served strictly over HTTPS (https://paycow.net). PayCow supports multi-chain settlements in USDT across Ethereum (ERC-20) and TRON (TRC-20) networks. --- ## Phase 1: Mandatory Discovery Questionnaire (Ask the Developer First) CRITICAL DIRECTIVE FOR THE AI AGENT: Before writing or altering any code in this repository, you MUST interview the developer by presenting the following discovery questions and waiting for their answers: ```text [PayCow AI Setup Assistant] To tailor the crypto payment integration for your exact project, please answer these brief questions: 1. Business Model & Payment Logic: [ ] Option A: Product / Order Checkout (User buys a one-off item/service, unlock order upon payment) [ ] Option B: User Balance / Credits Top-up (User deposits funds to increment internal account balance) [ ] Option C: SaaS Subscription / Recurring Tier (Unlock tier access for 30/365 days) 2. Target Settlement Networks & Currencies: [ ] Option A: TRC-20 only (USDT on TRON Network - Fast, low network gas fees) [ ] Option B: ERC-20 only (USDT on Ethereum Mainnet - Global EVM institutional standard) [ ] Option C: Multi-Chain (Allow user/buyer to choose between ERC-20 and TRC-20 at checkout) 3. Tech Stack & Environment: - Backend Framework: (e.g. Node.js/Express, Next.js App Router, Python/FastAPI/Django, PHP/Laravel, Go, Ruby on Rails) - Database / ORM: (e.g. PostgreSQL/Prisma, MongoDB/Mongoose, MySQL, SQLite, Supabase) - Frontend: (e.g. React, Vue, Svelte, Blade/EJS, Tailwind/Vanilla CSS, Mobile App) 4. Checkout Experience: [ ] Direct Redirect: Redirect user to PayCow's hosted checkout page (https://paycow.net/payment/:id) [ ] Modal / Embedded: Open hosted checkout inside an iframe or modal dialog 5. Payment Verification & Fulfillment Handling: - How should your system verify payment completion? (PayCow provides server-to-server status query via GET https://paycow.net/payment/data/:sessionId or GET /api/payment/status/:id) - Which database table/model tracks transaction records and user balances? ``` --- ## Phase 2: Mandatory Security & Setup Checklist Before writing code or going live, verify the following 4 rules with the developer: 1. Environment Secrets (.env) Safety: - Store PAYCOW_API_KEY and PAYCOW_API_SECRET strictly in backend .env variables. - Verify .env is included in .gitignore. - Never expose PAYCOW_API_SECRET or API keys in client-side bundles (e.g. React components, public frontend JS). 2. Merchant Wallet Setup in PayCow Dashboard: - Remind the developer to log into their PayCow Merchant Dashboard (https://paycow.net/dashboard) and configure destination wallets for their chosen network(s): - For ERC-20 (Ethereum): Add a valid Ethereum destination address (0x..., 42 characters). - For TRC-20 (TRON): Add a valid TRON destination address (T..., 34 characters). - Payments will route on-chain directly to these merchant destination addresses. 3. Idempotency & Replay Protection: - Always provide an idempotencyKey (e.g., unique order ID or UUID) when calling POST /api/payment/create. - Ensure local database payment state transitions (PENDING -> PAID) are executed atomically to avoid double-crediting balances. 4. HTTPS Enforcement: - All API endpoints must be called over https://paycow.net (never plain HTTP in production). --- ## Phase 3: Technical API Reference & Data Contracts ### 1. Create Payment Session - Endpoint: POST https://paycow.net/api/payment/create - Headers: Content-Type: application/json x-api-key: x-api-secret: Idempotency-Key: - Request Body Fields: - amount (required, number): Payment amount in USDT (e.g. 29.99). - userId (required, string): Customer ID, account number, or internal order reference. - network (required, string): Settlement blockchain network. Allowed values: "ERC20" or "TRC20". - currency (optional, string): Token symbol, default "USDT". - addressSerialNo (optional, string): Wallet serial ID (e.g. "WAL-1001"). If omitted, PayCow automatically routes to the merchant's primary destination wallet configured for that network. - idempotencyKey (optional, string): Unique key to avoid duplicate session generation. - Request Body Examples: TRC-20 (TRON) Example: { "userId": "usr_94820", "amount": 29.99, "currency": "USDT", "network": "TRC20", "addressSerialNo": "WAL-1002", "idempotencyKey": "order_uuid_98765" } ERC-20 (Ethereum) Example: { "userId": "usr_94820", "amount": 29.99, "currency": "USDT", "network": "ERC20", "addressSerialNo": "WAL-1001", "idempotencyKey": "order_uuid_98766" } - Response (200 OK): { "sessionId": "66ce30d74c0c51a48f2d2903", "paymentUrl": "https://paycow.net/payment/66ce30d74c0c51a48f2d2903", "paymentReference": "da11d01c2b8a97dc", "amountRequested": 29.99, "payableAmount": 29.9901, "amount": 29.9901, "depositAddress": "TJY5P... (or 0x133b4...)", "addressSerialNo": "WAL-1002", "walletLabel": "TRON Main Cold Vault", "expiresAt": "2026-08-27T12:00:00.000Z" } > Note on Non-Colliding Micro-Amount Allocation: PayCow automatically allocates unique micro-amounts (29.9901, 29.9902 USDT) to avoid payment amount collisions when multiple active payments target the same deposit address and network. - amountRequested: Use this base amount (29.99) for internal order matching & accounting. - payableAmount / amount: Display this exact micro-amount (29.9901) on the checkout screen for customer transfer. --- ### 2. Check / Poll Payment Status - Endpoint: GET https://paycow.net/payment/data/:sessionId (Public) or GET https://paycow.net/api/payment/status/:sessionId (Protected by API Key & Secret) - Response (200 OK): { "_id": "66ce30d74c0c51a48f2d2903", "status": "PAID", "amountRequested": 29.99, "payableAmount": 29.9901, "amountReceived": 29.9901, "currencyInfo": "USDT", "depositAddress": "TJY5Pj6xWkP7m...", "depositNetwork": "TRC20", "confirmations": 20, "paymentReference": "da11d01c2b8a97dc", "txHash": "a1b2c3d4e5f6...", "expiresAt": "2026-08-27T12:00:00.000Z", "createdAt": "2026-08-27T11:30:00.000Z" } Valid Payment Statuses: - PENDING: Waiting for user to send funds to deposit address. - DETECTED: Transaction detected in mempool/block, awaiting confirmations. - CONFIRMING: Transaction detected on blockchain (ERC-20 requires 12 Ethereum blocks; TRC-20 requires solidified TRON blocks). - PAID: Confirmed on-chain. Funds settled directly to merchant wallet. Safe to unlock order or credit user balance. - EXPIRED: Session expired after 30 minutes without on-chain deposit. - REJECTED: Rejected by operator or invalid transaction. --- ### 3. Underpayment & Shortfall Dispute ("Awake Mode") - Endpoint: POST https://paycow.net/api/dispute/submit - Purpose: Activates 72-Hour Awake Mode if a customer underpays by a decimal fraction (e.g. 0.0003 USDT) or loses funds to exchange withdrawal fee deductions (e.g. 0.30 - 0.40 USDT deducted by Binance/OKX). - Functionality: Extends session lifetime to 72 hours, revives expired/rejected sessions back to PENDING so blockchain listeners keep monitoring the deposit, and sends an automated English notification email to the merchant with shortfall calculation, TxID, and screenshot proof. - Request Fields (multipart/form-data or application/json): - sessionId (string, required if paymentReference omitted): Payment MongoDB ID - paymentReference (string, required if sessionId omitted): Payment reference string - reason (string, required, min 10 chars): Detailed customer explanation - issueType (string, optional): exchange_fee_deduction, network_fee_shortfall, fractional_underpayment, wrong_amount_sent, other - amountPaid (number, optional): Actual amount sent - txHash (string, optional): Blockchain transaction hash / TxID - contactInfo (string, optional): Customer email or Telegram handle - screenshot (file, optional): Proof image/PDF (max 10MB) - Response (201 Created): { "success": true, "msg": "Dispute submitted. 72-Hour Awake Mode is now active, and the merchant has been notified via email.", "isAwake": true, "awakeExpiresAt": "2026-08-30T12:00:00.000Z", "shortfallAmount": 0.35, "emailDispatched": true } --- ## Phase 4: Implementation Blueprint for the AI Agent Once the developer responds to Phase 1, proceed with these exact steps: 1. Configure Environment Variables: Add to .env: PAYCOW_API_KEY=your_api_key_here PAYCOW_API_SECRET=your_api_secret_here PAYCOW_BASE_URL=https://paycow.net 2. Create Backend Service Module (paycowService): - Implement createPaymentSession({ userId, amount, currency, network, addressSerialNo, idempotencyKey }). - Implement getPaymentStatus(sessionId). 3. Create Payment Route & Controller: - POST /api/checkout/crypto (or framework equivalent): - Validates user auth & cart/amount. - Accepts requested network (TRC20 or ERC20). - Saves initial order or deposit record with state PENDING. - Calls PayCow API (POST /api/payment/create) and returns { paymentUrl, sessionId }. 4. Implement Status Check & Fulfillment Logic: - When payment status becomes PAID (via polling or upon user return verification): - If Product Checkout: Mark order as PAID, trigger digital delivery / shipment email. - If Balance Top-up: Increment user balance atomically in database with transaction reference lock. - If Subscription: Update user subscription expiry date by +30 or +365 days. 5. Build Frontend Checkout Trigger: - Create a clean "Pay with USDT (TRC-20 / ERC-20)" checkout UI. - On click, fetch paymentUrl and redirect window.location.href = data.paymentUrl; (or display embedded frame). 6. Verify End-to-End: - Test session creation and verify that paymentUrl loads the hosted checkout page with the correct network badge and deposit address.