Aller au contenu principal

Build with AI — Ready-to-Use Reseller Prompts

Paste any self-contained prompt below into ChatGPT, Claude, Cursor, or Copilot to bootstrap a production-grade GpkeysBot reseller integration.

Important Before Deploying

Replace all placeholders (YOUR_API_KEY, https://api.example.com) and carefully review all AI-generated code, error branches, secret handling, and tests before deploying to production. Never commit API keys into source control or ship them to browsers or mobile clients.


1. Node.js / Express Reseller Client & Purchase Route

Stack: Node.js 20+, TypeScript, Express, Vitest/Jest
Goal: Build a reusable GpkeysBot API v1 TypeScript client module and an Express backend endpoint that safely checks account balance before fulfilling product purchases with automatic retries and explicit 402 handling.

Context:
- API Base URL: process.env.GPKEYS_BASE_URL (placeholder: https://api.example.com, never hardcode real credentials)
- Authentication: Send API key from process.env.GPKEYS_API_KEY in header "x-api-key"
- Documented endpoints used:
- GET /api/v1/balance (Docs: /docs/endpoints/balance)
- GET /api/v1/catalog/products/{productId} (Docs: /docs/endpoints/get-product)
- POST /api/v1/purchases (Docs: /docs/endpoints/create-purchase)
- GET /api/v1/orders/{orderId} (Docs: /docs/endpoints/get-order)

Requirements:
1. Create src/gpkeysClient.ts exposing getBalance(), getProduct(productId), createPurchase({ productId, quantity, idempotencyKey }), and getOrder(orderId).
2. Before calling POST /api/v1/purchases, call getProduct(productId) and getBalance() to verify product availability and sufficient USDT balance using exact decimal arithmetic (no floating-point precision loss; e.g. decimal.js or BigInt scaled to 6 decimals).
3. Implement exponential backoff with jitter ONLY for HTTP 429 (honoring retryAfterSeconds / Retry-After) and HTTP 5xx responses (max 4 attempts), always reusing the exact same idempotencyKey on POST retries.
4. Create an Express router POST /api/reseller/checkout accepting { productId, quantity, orderReference }, validating inputs strictly with Zod, generating a deterministic idempotencyKey from orderReference (>= 8 chars), and returning delivered items on success.
5. Write automated unit tests using mocked fetch/HTTP covering: successful 201 purchase, 200 idempotent replay, 402 insufficient balance pre-check & upstream 402 mapping, 429 retry recovery, and invalid key 401 failure.

Security rules:
- Load GPKEYS_API_KEY only from process.env; throw startup error if missing. Never hardcode a real key or accept an API key from HTTP callers.
- Never log req.headers['x-api-key'], Authorization headers, or GPKEYS_API_KEY anywhere. Log at most safe order IDs and error codes.
- Never trust client-supplied prices; always read authoritative priceUsdt from GET /api/v1/catalog/products/{productId}.
- Do not allow browser code to call GpkeysBot directly; expose only your Express endpoint.
- If balance check fails or API returns 402, do not fulfill downstream customer items or record a paid order.

Error handling:
- 400 VALIDATION_ERROR: return 400 to caller without retry.
- 401 UNAUTHORIZED: log sanitized security alert, return 502 upstream auth misconfiguration (never expose key details).
- 402 INSUFFICIENT_BALANCE: stop purchase, trigger low-balance admin alert hook, return 402/503 clear billing hold without delivering product.
- 403 FORBIDDEN / API_KEY_CAP_EXCEEDED / FRAUD_DETECTED: do not retry; pause worker / alert ops with sanitized audit code.
- 404 NOT_FOUND / 409 PRODUCT_UNAVAILABLE / OUT_OF_STOCK: return clean unavailable/out-of-stock message without charging.
- 429 RATE_LIMITED & 5xx: retry with exponential backoff + jitter reusing same idempotencyKey.

Deliverables:
- src/gpkeysClient.ts
- src/routes/checkout.ts
- src/app.ts
- tests/gpkeysClient.test.ts
- Instructions in README snippet showing: npm install, GPKEYS_API_KEY=... GPKEYS_BASE_URL=... npm test, and curl verification.

Acceptance criteria:
- [ ] Missing GPKEYS_API_KEY fails fast on startup.
- [ ] Insufficient balance aborts cleanly with HTTP 402 handling and zero fulfilled items.
- [ ] All POST /api/v1/purchases retries reuse identical idempotencyKey values.
- [ ] Transient 429 and 500 responses recover cleanly in automated tests.
- [ ] Grep over codebase confirms no hardcoded keys or unredacted header logging.

2. Python FastAPI Typed Client & Checkout Service

Stack: Python 3.11+, FastAPI, Pydantic v2, requests, pytest
Goal: Build a strongly typed FastAPI microservice and reusable requests client wrapping GpkeysBot API v1 with balance verification, Decimal arithmetic, 429/5xx retries, and HTTP 402 handling.

Context:
- Base URL env var: GPKEYS_BASE_URL (placeholder: https://api.example.com)
- Auth header: "x-api-key" populated strictly from os.environ["GPKEYS_API_KEY"]
- Documented endpoints used:
- GET /api/v1/balance (/docs/endpoints/balance)
- GET /api/v1/catalog/products/{productId} (/docs/endpoints/get-product)
- POST /api/v1/purchases (/docs/endpoints/create-purchase)
- GET /api/v1/ledger (/docs/endpoints/ledger)

Requirements:
1. Define Pydantic v2 response/request models in models.py (BalanceResponse, Product, PurchaseRequest, PurchaseResponse, ErrorPayload) parsing monetary fields as decimal.Decimal (never float).
2. Implement GpkeysClient in client.py using requests.Session with timeouts (15s), shared x-api-key header injection, and bounded exponential backoff + jitter ONLY on HTTP 429 and 5xx (reusing identical idempotencyKey).
3. Implement buy_product_safely(product_id, quantity, idempotency_key): verify product exists & price via GET /api/v1/catalog/products/{productId} and check live funds via GET /api/v1/balance before POST /api/v1/purchases.
4. Expose FastAPI POST /reseller/orders delegating safely to GpkeysClient, validating request bounds (quantity 1..1000, idempotencyKey 8..128 chars).
5. Write pytest suite testing valid 201 purchase, balance pre-check rejection before POST, upstream 402 handling, 429 retry honoring retryAfterSeconds, and schema validation.

Security rules:
- Require GPKEYS_API_KEY via environment settings at boot; forbid hardcoded keys or default secrets.
- Configure logging filters so x-api-key or keys matching gpk_live_* are never printed to stdout or error logs.
- Never compute prices from request inputs; ignore/forbid client price overrides.
- Perform zero fulfillment or downstream side effects when balance is insufficient or 402 is raised.

Error handling:
- 400 VALIDATION_ERROR: raise HTTPException(400) immediately without retry.
- 401 UNAUTHORIZED: raise sanitized 502 upstream credential failure & emit critical ops log without key bytes.
- 402 INSUFFICIENT_BALANCE: raise dedicated InsufficientBalanceError mapped to HTTP 402 with shortfall details and no order execution.
- 403 FORBIDDEN / API_KEY_CAP_EXCEEDED / FRAUD_DETECTED: fail closed without retry and emit alert metric.
- 409 PRODUCT_UNAVAILABLE / OUT_OF_STOCK: return clean 409 unavailable state.
- 429 / 5xx: retry up to 4 times with jitter using identical idempotencyKey.

Deliverables:
- app/models.py
- app/client.py
- app/main.py
- tests/test_client.py
- Run commands: pip install fastapi uvicorn requests pydantic pytest && pytest -v

Acceptance criteria:
- [ ] All USDT amounts use decimal.Decimal with exact 6-decimal comparison.
- [ ] Pre-check + HTTP 402 prevent purchases when balance is insufficient.
- [ ] Retries trigger only on 429/5xx and preserve idempotencyKey.
- [ ] pytest suite passes offline via requests mocking.

3. PHP / Laravel Reseller Service & Controller

Stack: PHP 8.2+, Laravel 11+, Laravel Http Facade, PHPUnit/Pest
Goal: Implement a production-safe Laravel service, config file, and controller that calls GpkeysBot API v1 with balance verification, bcmath precision, 429/5xx retries, and 402 billing protection.

Context:
- Base URL configured via config/gpkeys.php from env('GPKEYS_BASE_URL', 'https://api.example.com')
- API Key configured strictly from env('GPKEYS_API_KEY') sent in header 'x-api-key'
- Documented endpoints used:
- GET /api/v1/balance (/docs/endpoints/balance)
- GET /api/v1/catalog/products/{productId} (/docs/endpoints/get-product)
- POST /api/v1/purchases (/docs/endpoints/create-purchase)

Requirements:
1. Create config/gpkeys.php reading base_url, api_key, timeout_seconds (15), and retry_attempts (4) purely from env().
2. Create App\Services\GpkeysClient wrapping Illuminate\Support\Facades\Http with retry logic strictly on 429 and 5xx HTTP responses, sending identical idempotencyKey on POST /api/v1/purchases retries.
3. Add purchaseWithBalanceGuard(string $productId, int $quantity, string $idempotencyKey) using bcmath (scale 6) to verify price * quantity <= available balance before submitting POST /api/v1/purchases.
4. Create FormRequest validation and ResellerPurchaseController rejecting invalid inputs cleanly.
5. Add PHPUnit / Pest feature tests using Http::fake() covering 201 purchase, 402 insufficient balance, 403 spend cap exceeded, and 429 retry recovery.

Security rules:
- Never reference env('GPKEYS_API_KEY') outside config/gpkeys.php (use config('gpkeys.api_key')). Never commit real keys or pass keys to Blade/Inertia/SPA frontend props.
- Redact x-api-key before logging any failed HTTP trace.
- Never perform fulfillment or mark local reseller orders paid if balance pre-check fails or HTTP 402 returns.
- Validate productId, quantity (1..1000), and idempotencyKey (8..128) cleanly on controller ingress.

Error handling:
- 400 VALIDATION_ERROR: fail immediately, map field validation errors safely.
- 401 UNAUTHORIZED: log sanitized credential alert and abort with 502 upstream gateway error.
- 402 INSUFFICIENT_BALANCE: throw GpkeysInsufficientBalanceException, fire low-balance notification event, return 402/503 without charging customer/fulfilling.
- 403 FORBIDDEN / API_KEY_CAP_EXCEEDED / FRAUD_DETECTED: abort immediately without retry.
- 409 PRODUCT_UNAVAILABLE / OUT_OF_STOCK: return 409 unavailable message cleanly.
- 429 / 5xx: retry via exponential backoff with jitter while preserving idempotencyKey.

Deliverables:
- config/gpkeys.php
- app/Services/GpkeysClient.php
- app/Http/Controllers/ResellerPurchaseController.php
- tests/Feature/GpkeysClientTest.php
- Run command: php artisan test --filter=GpkeysClientTest

Acceptance criteria:
- [ ] All money comparisons use bccomp(..., ..., 6) instead of floats.
- [ ] Client key never leaves server config/service layer.
- [ ] Http::fake() test suite verifies 201, 402, 403, and 429 behaviors.

4. Browser-Safe Backend-for-Frontend (BFF) Checkout Pattern

Stack: React/Next.js Frontend + Secure Server API Route (BFF)
Goal: Build a checkout architecture where the browser calls only your own authenticated backend API, which proxies GpkeysBot API v1 without ever exposing your API key to the browser.

Context:
- GpkeysBot Base URL: https://api.example.com (server-side env GPKEYS_BASE_URL)
- Auth: Server sends GPKEYS_API_KEY via x-api-key header exclusively from server memory
- Documented endpoints used (server-side only):
- GET /api/v1/catalog/products (/docs/endpoints/list-products)
- GET /api/v1/balance (/docs/endpoints/balance)
- POST /api/v1/purchases (/docs/endpoints/create-purchase)

Requirements:
1. Expose public/session-authenticated BFF routes GET /api/store/products and POST /api/store/buy on your own server.
2. In GET /api/store/products, fetch catalog from GpkeysBot GET /api/v1/catalog/products, apply your storefront markup safely on server, and strip internal account IDs / ledger fields from public JSON responses.
3. In POST /api/store/buy, verify the end-customer's own session & payment first, generate a server-side idempotencyKey tied to the local order ID, verify your GpkeysBot balance via GET /api/v1/balance, and execute POST /api/v1/purchases from the backend.
4. Build a minimal accessible React storefront UI calling ONLY /api/store/products and /api/store/buy over relative URLs.
5. Add automated static check + integration test confirming NEXT_PUBLIC_* / VITE_* bundles contain zero API keys and frontend never contacts GpkeysBot directly.

Security rules:
- STRICTLY FORBIDDEN: Never import, bundle, return, or reference GPKEYS_API_KEY in browser JavaScript, HTML, localStorage, NEXT_PUBLIC_*, VITE_*, or CORS-exposed headers.
- Do not expose raw GpkeysBot account balance or audit logs on unauthenticated storefront endpoints.
- Enforce strict server-side input validation and CSRF/session auth on /api/store/buy.
- Do not mark storefront checkout completed or reveal digital items if balance check fails or 402 is returned.

Error handling:
- 401 / 403 / 402 upstream errors: map to safe user-facing checkout unavailable error ("Store fulfillment temporarily unavailable — payment not captured") while alerting server operators privately.
- 409 OUT_OF_STOCK / PRODUCT_UNAVAILABLE: show clear out-of-stock UI state without charging the storefront buyer.
- 429 / 5xx: handled via backend retries keeping idempotencyKey constant.

Deliverables:
- server/routes/store.ts (backend proxy)
- client/StoreCheckout.tsx (browser UI calling only /api/store/*)
- tests/storeProxy.test.ts
- Verification checklist & grep script verifying zero key leakage in frontend assets.

Acceptance criteria:
- [ ] Frontend network calls go strictly to same-origin /api/store/* routes.
- [ ] Build artifacts under dist/.next contain zero references to x-api-key or GPKEYS_API_KEY.
- [ ] Upstream 402 returns safe error without double-charging customer or leaking balance figures.

5. Reseller Balance Monitoring & Ledger Dashboard

Stack: Node.js Backend + React Dashboard Widget
Goal: Implement an internal reseller operations dashboard displaying current GpkeysBot USDT balance, active key spend caps, recent ledger entries, and automated low-balance warnings.

Context:
- API Base URL: process.env.GPKEYS_BASE_URL (placeholder: https://api.example.com)
- Auth: Server-side only x-api-key header via GPKEYS_API_KEY
- Documented endpoints used:
- GET /api/v1/balance (/docs/endpoints/balance)
- GET /api/v1/key (/docs/endpoints/key-metadata)
- GET /api/v1/ledger (/docs/endpoints/ledger)
- GET /api/v1/audit (/docs/endpoints/audit)

Requirements:
1. Build backend endpoint GET /api/ops/treasury-summary (protected by your admin auth) that queries GET /api/v1/balance, GET /api/v1/key, and GET /api/v1/ledger?limit=25.
2. Compute remaining monthly spend headroom (monthlySpendCap - monthlySpent using exact decimal subtraction when monthlySpendCap != null) and compare available balance against configurable env LOW_BALANCE_THRESHOLD_USDT (e.g. "25.000000").
3. Render an accessible dashboard panel showing: current USDT balance, low-balance warning banner (accessible role="status" / alert with sufficient color contrast), monthly cap progress bar, and paginated ledger table (timestamp, requestType, signed amount, balanceAfter, referenceId).
4. Format all amounts cleanly to 6 decimal places without float rounding bugs.
5. Write tests checking threshold calculation, cap utilization edge cases (null cap), and pagination cursor forwarding.

Security rules:
- Fetch all GpkeysBot endpoints from backend /api/ops/treasury-summary; never call GpkeysBot from dashboard browser code.
- Restrict /api/ops/treasury-summary behind admin authentication.
- Never log GPKEYS_API_KEY; return only maskedKey metadata from /api/v1/key.

Error handling:
- 401 / 403: surface "API Key Invalid / Disabled / Suspended" urgent ops banner and pause auto-refresh polling.
- 402: display critical red balance banner requiring immediate top-up.
- 429 / 5xx: back off dashboard polling interval safely rather than hammering the API.

Deliverables:
- server/treasuryService.ts
- ui/TreasuryDashboard.tsx
- tests/treasuryService.test.ts
- Run command: npm test

Acceptance criteria:
- [ ] Low-balance alert activates accurately when available <= LOW_BALANCE_THRESHOLD_USDT.
- [ ] Monthly cap remaining math handles both capped and uncapped (null) keys.
- [ ] Ledger entries display requestType, signed amount, balanceAfter, and timestamp accurately.

6. Purchase Status Reconciliation & Polling Worker

Stack: TypeScript / Node.js Worker (Database/Queue Safe)
Goal: Build an idempotent background reconciler that polls GpkeysBot order endpoints to resolve uncertain purchase states without duplicate charges.

Context:
- API Base URL: https://api.example.com (from env GPKEYS_BASE_URL)
- Auth: Server-side x-api-key header via GPKEYS_API_KEY
- Documented endpoints used:
- GET /api/v1/orders (/docs/endpoints/list-orders)
- GET /api/v1/orders/{orderId} (/docs/endpoints/get-order)
- POST /api/v1/purchases (/docs/endpoints/create-purchase)
- Webhook status note (TODO verify): Current backend executes /api/v1/purchases synchronously and exposes authenticated polling via GET /api/v1/orders and GET /api/v1/orders/{orderId}; it does not currently emit outbound purchase webhook events or webhook signature headers. Do NOT invent undocumented webhook signature verification unless your deployment adds outbound webhooks.

Requirements:
1. Build a polling worker reconcilePendingOrders() that inspects local orders stuck in "SUBMITTING" / unknown state after network timeouts.
2. For orders lacking an upstream orderId, replay POST /api/v1/purchases using the stored idempotencyKey (expecting HTTP 200 created:false if previously succeeded, or 201 if never executed) after checking balance via GET /api/v1/balance.
3. For orders that already recorded an orderId, poll GET /api/v1/orders/{orderId} (and fallback scan GET /api/v1/orders?limit=50) to fetch deliveredPayload and update local status atomically.
4. Pace polling cleanly under the 60/min general and 10/min purchase key limits with jittered backoff, storing cursor/checkpoint timestamps durably.
5. Write tests simulating timed-out checkout recovered cleanly via idempotent replay (created: false) and polling synchronization.

Security rules:
- Store GPKEYS_API_KEY strictly in worker env vars; redact secrets from worker logs.
- Never issue a new idempotencyKey when recovering an ambiguous timed-out purchase—always reuse the persisted one.
- Enforce local DB transactional state guards so a reconciled order triggers customer delivery notification at most once.

Error handling:
- 401 UNAUTHORIZED / 403 FORBIDDEN / 403 FRAUD_DETECTED: pause worker with exponential circuit breaker and page operator.
- 402 INSUFFICIENT_BALANCE: mark local order halted-for-funds; do not fulfill or retry without top-up.
- 404 NOT_FOUND on orderId: mark discrepancy for manual reconciliation; do not re-create with a different idempotencyKey blindly.
- 429 RATE_LIMITED & 5xx: pause worker cleanly using retryAfterSeconds + jitter.

Deliverables:
- worker/reconciler.ts
- worker/backoff.ts
- tests/reconciler.test.ts
- Run command: npm test

Acceptance criteria:
- [ ] Ambiguous timeout resolves cleanly without double debiting balance.
- [ ] Worker respects per-key rate limits and handles 402/401/403 without tight spin loops.
- [ ] All polling targets only GET /api/v1/orders, GET /api/v1/orders/{orderId}, and POST /api/v1/purchases.