---
name: nodegate-payments
description: Integrate the self-hosted NodeGate USDT gateway (TRC-20/BEP-20; https://nodegate.space, testnet https://testnet.nodegate.space) into this codebase. Covers deposits (invoices with category + customer_id, hosted checkout, signed webhooks, idempotent crediting), withdrawals (requests approved from either side, payout webhooks, refunds on reject) and keeping both sides in sync. Use when adding or changing USDT payments, withdrawals, NodeGate webhooks or reconciliation.
---

<!-- nodegate-payments skill · version 2 (2026-10-17) · matches gateway D23 + D24 -->
<!-- Install or update: mkdir -p .claude/skills/nodegate-payments && curl -fsSL "$NODEGATE_URL/docs/skill.md" -o .claude/skills/nodegate-payments/SKILL.md -->

# NodeGate payment integration

NodeGate is a self-hosted USDT gateway. Live: `https://nodegate.space` (keys `ng_live_…`). Testnet: `https://testnet.nodegate.space` (keys `ng_test_…`). The full OpenAPI spec is at `{NODEGATE_URL}/docs/json`; fetch it for any field not listed here. **The latest version of this skill is always at `{NODEGATE_URL}/docs/skill.md`.**

## What changed in v2 (apply when updating an existing integration)
1. **Invoices** accept `category` (one of the merchant's categories, set up in the gateway panel), `customer_id` (your user ID) and `metadata` (small flat key/value). They are echoed in the response and the `invoice.paid` webhook (null when not sent). An unknown category → `400`.
2. **Withdrawals go through the gateway.** `POST /api/v1/payouts` creates a **withdrawal request** (`PENDING_APPROVAL`). It is **no longer refused with 403** in manual mode. Either your admin (`POST /api/v1/payouts/{id}/approve|reject`) or the gateway admin approves or rejects it; whichever acts first wins.
3. **New webhooks:** `payout.approved` and `payout.rejected`. A rejection is now `payout.rejected`, **not** `payout.failed`. All payout webhooks carry `category`, `customer_id` and `metadata`.
4. **Payout responses** add `approved_by`, `approved_at`, `rejected_by`, `reject_reason`, `category`, `customer_id` and `metadata`. A new request returns `201`, a replay `200`.
5. **Migration checklist** for an existing v1 integration:
   - Send `category` + `customer_id` on every invoice.
   - Route user withdrawals through `POST /payouts` instead of paying by hand and typing the tx hash in your own admin.
   - Wire your admin's Approve/Reject buttons to the gateway endpoints.
   - Handle the 4 payout webhooks.
   - Stop treating `payout.failed` as "rejected".

## Configuration (server-side env only; add to `.env.example`; never in browser or mobile code)
`NODEGATE_URL`, `NODEGATE_API_KEY`, `NODEGATE_WEBHOOK_SECRET`. Testnet ↔ mainnet = changing these three values, never code.

## Categories
The merchant's categories are created by the gateway operator (panel → Merchants → Categories). For Binary Fund Pro: `affiliate`, `live_trading`, `fund_trading`, `personal`. Map every money flow to one:

| Flow (example) | Category | Direction |
|---|---|---|
| Partner/affiliate activation fee | `affiliate` | invoice (deposit) |
| Affiliate commission withdrawal | `affiliate` | payout |
| Challenge / funded-account purchase | `fund_trading` | invoice |
| Funded-account profit payout | `fund_trading` | payout |
| Live account deposit / withdrawal | `live_trading` | invoice / payout |
| Anything else for a user's own wallet | `personal` | either |

Keep the mapping in **one** function/constant, so a typo can't reach the API. Always send `customer_id` = your stable user ID (not the email).

## Deposits (invoices)
1. **Data:** per order (or in a `payments` table) store `nodegate_invoice_id` (UNIQUE), `network`, `status`, `amount_usd` (decimal, never float), `tx_hash`, `paid_at`.
2. **Create** (backend):
   ```http
   POST {NODEGATE_URL}/api/v1/invoices
   x-api-key: {NODEGATE_API_KEY}
   content-type: application/json

   {"order_id":"<unique per payment attempt>","amount_usd":"49.99","network":"TRC20",
    "category":"fund_trading","customer_id":"<your user id>","customer_email":"optional","metadata":{"tier":"10K"}}
   ```
   - The response is `{ success, data: { invoice_id, deposit_address, amount_crypto, network, qr_code_base64, checkout_url, expires_at, status, category, customer_id, metadata } }`.
   - `201` = created; `200` = same `order_id` replayed. On timeout or 5xx, retry with the **same** `order_id`.
   - `409` = same `order_id` with a different amount, network, category or customer.
   - Invoices expire after 60 min; a new attempt needs a new `order_id`.
   - `amount_usd`: a string with ≤ 2 decimals. `metadata`: ≤ 20 keys, ≤ 2 KB, values are strings ≤ 200, numbers, booleans or null.
3. **Show:** redirect to (or open in a new tab) `checkout_url`. It does **not** redirect back, so your order page polls **your own** backend for status. Alternatively, render `deposit_address`, `amount_crypto`, `network` and `qr_code_base64` yourself, and warn: exact amount, that network only, before `expires_at`.

## Withdrawals (payouts)
```
user asks ─▶ (your DB: debit balance + withdrawal row, one transaction) ─▶ POST /api/v1/payouts ─▶ PENDING_APPROVAL
  approve (your admin → POST /payouts/{id}/approve, or the gateway admin) ─▶ QUEUED (gateway sends automatically)
                                                                          or AWAITING_SEND (operator sends by hand)
  your approval over the gateway's limits ─▶ HELD (only the gateway admin can decide)
  reject (either side; you only while PENDING_APPROVAL/HELD) ─▶ REJECTED ─▶ refund the user
  ─▶ COMPLETED (payout.completed with tx_hash) │ FAILED (automatic send failed, nothing moved ─▶ refund)
```
- **Request:**
  ```json
  POST /api/v1/payouts
  {"reference_id":"<your withdrawal id>","recipient_address":"T…|0x…","amount":"250","network":"TRC20",
   "category":"affiliate","customer_id":"<user id>","approve":false}
  ```
  `reference_id` is the idempotency key. Retry with the same one; a payout is never sent twice. Use `approve: true` when your admin already approved it, or if your product auto-approves.
- **Your admin's buttons:**
  - Approve: `POST /api/v1/payouts/{payout_id}/approve`.
  - Reject: `POST /api/v1/payouts/{payout_id}/reject` with `{"reason":"…"}`.
  - `409` = the other side already decided. Re-read with `GET /api/v1/payouts/{payout_id}` and show that status; it's not an error for the user.
- **Store** `nodegate_payout_id` (UNIQUE) and mirror the gateway status on your withdrawal row. Your own status column must not move backwards (guarded updates).

## Webhooks (one endpoint, e.g. `POST /api/webhooks/nodegate`; register its URL in the gateway panel)
- **Verify:**
  1. Use the **raw body**.
  2. Compute `hex(HMAC_SHA256(NODEGATE_WEBHOOK_SECRET, X-NodeGate-Timestamp + "." + rawBody))` and compare it in **constant time** with `X-NodeGate-Signature`.
  3. Reject if `|now − timestamp| > 300 s`.
  4. Invalid → 401.
- **At-least-once:** every handler is idempotent (guarded `UPDATE … WHERE status = '<expected>'`, or a processed-events table keyed on `(event, invoice_id|payout_id)`). Answer 2xx within 10 s and do slow work in a job. Failed deliveries are retried at 30 s, 2 m, 10 m and 30 m.

| Event | Do |
|---|---|
| `invoice.paid` | If the order exists, is unpaid, and `amount_paid ≥ total` (**decimal** compare; 6 decimals on TRC20, **18** on BEP20): mark paid and fulfil **once**. |
| `payout.approved` | Withdrawal → approved/processing (`status` is `QUEUED` or `AWAITING_SEND`). Keep the balance debited. |
| `payout.rejected` | Withdrawal → rejected; **refund** the user's balance once; show `reason`. |
| `payout.completed` | Withdrawal → paid; store `tx_hash`. |
| `payout.failed` | Withdrawal → failed; **refund** once (nothing moved). Retry only with a **new** `reference_id`. |

## Reconcile (scheduled, e.g. every 10 min)
For each local invoice still pending and each withdrawal not final, read `GET /api/v1/invoices/{id}` or `GET /api/v1/payouts/{id}`, and apply the result through the **same** idempotent handlers as the webhooks. A lost webhook can then never leave a user stuck.

## Rules
- Credit or pay out **only** from verified webhooks or API reads. Never on `CONFIRMING`, never on a tx hash a user pastes.
- No floats for money anywhere (Decimal, bcmath/brick, decimal.js, Prisma `Decimal`).
- Users never choose `callback_url`. Webhook routes are excluded from CSRF and session middleware, but still verified.
- One refund per withdrawal: guard it (status transition, or a unique ledger entry keyed on the payout).

## Reference verifiers
Node.js:
```js
import crypto from 'node:crypto';
export function verifyNodeGate(rawBody, headers, secret) {
  const ts = headers['x-nodegate-timestamp'], sig = headers['x-nodegate-signature'];
  if (!ts || !sig || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return null;
  const expected = crypto.createHmac('sha256', secret).update(`${ts}.`).update(rawBody).digest();
  const given = Buffer.from(String(sig), 'hex');
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
  return JSON.parse(rawBody.toString('utf8'));
}
// Express: express.raw({ type: 'application/json' }) on the route · Next.js: Buffer.from(await req.arrayBuffer())
// Fastify: register a raw-body content-type parser for this route (or use fastify-raw-body).
```
PHP (Laravel: `$request->getContent()`):
```php
function verify_nodegate(string $raw, string $ts, string $sig, string $secret): ?array {
    if ($ts === '' || $sig === '' || abs(time() - (int)$ts) > 300) return null;
    if (!hash_equals(hash_hmac('sha256', $ts . '.' . $raw, $secret), strtolower($sig))) return null;
    return json_decode($raw, true);
}
```
Python (Django: `request.body`; Flask: `request.get_data()`):
```python
import hmac, hashlib, json, time
def verify_nodegate(raw: bytes, ts: str, sig: str, secret: str):
    if not ts or not sig or abs(time.time() - int(ts)) > 300: return None
    exp = hmac.new(secret.encode(), ts.encode() + b"." + raw, hashlib.sha256).hexdigest()
    return json.loads(raw) if hmac.compare_digest(exp, sig.lower()) else None
```

## Tests to write
- Signature: valid, invalid, stale.
- A duplicate `invoice.paid` credits once.
- An underpayment is not credited.
- An invoice-create retry reuses `order_id`.
- `payout.rejected` and `payout.failed` refund exactly once.
- `payout.approved` after a local reject doesn't resurrect it.
- A `409` on approve shows the gateway's status.
- The category mapping covers every flow.

## Testing against testnet
- Use the testnet gateway and an `ng_test_` key.
- Get test USDT from the TRON Nile faucet (TronLink on Nile).
- Expose your local webhook with `cloudflared tunnel --url http://localhost:<port>` and ask the operator to set that URL for the test merchant.
