# TREVO Reseller API v1

Base URL: `https://<your-domain>/api/v1`. JSON only. All responses carry an `X-Request-Id` header (also in the body).
Example values below are illustrative; real responses contain your own data.

## Authentication
Create a key in the panel (**API Keys**). Send it on every request:

```
Authorization: Bearer trv_ab12cd34_<40 characters>
```
- Keys in query strings are **not** accepted.
- The full key is shown **once**. TREVO stores only a SHA-256 hash. Lost key → rotate it.
- Keep keys on your server. Never ship them in browser or mobile app code.
- A key can be disabled, rotated (old secret stops instantly) or deleted at any time.
- Optional **IP allowlist** per key (IPv4/IPv6, single IPs or CIDR). Empty list = any IP. Requests from other IPs get `ip_not_allowed`.

## Response shapes
Success: `{"data": ..., "request_id": "01J..."}`

Error: `{"error": {"code": "invalid_api_key", "message": "...", "request_id": "01J...", "details": {...}}}`
(`details` only for `validation_failed`.)

| HTTP | code | Meaning |
|---|---|---|
| 401 | `missing_api_key` | No `Authorization: Bearer` header |
| 401 | `invalid_api_key` | Malformed, unknown, revoked or deleted key |
| 403 | `api_key_disabled` | Key exists but is disabled |
| 403 | `account_suspended` | Reseller account suspended |
| 403 | `email_not_verified` | Email verification required and not done |
| 403 | `ip_not_allowed` | Caller IP is not on the key's allowlist |
| 404 | `not_found` | Unknown endpoint |
| 405 | `method_not_allowed` | Wrong HTTP method (see `Allow` header) |
| 422 | `validation_failed` | Invalid input (`details` lists fields) |
| 429 | `rate_limited` | Per-reseller or per-IP limit exceeded (see `Retry-After`) |
| 429 | `too_many_failed_attempts` | Too many failed authentications from your IP |
| 500 | `internal_error` | Our fault. Quote `request_id` to support |

## Rate limits
- Per reseller (shared by all your keys): the `rate_limit_per_minute` of your best active package, otherwise the platform default (`TREVO_API_DEFAULT_RATE_LIMIT`, 30/min).
- Per client IP across all API traffic: `TREVO_API_IP_RATE_LIMIT` (120/min).
- Failed authentications per IP: `TREVO_API_FAILED_AUTH_LIMIT` (20/min). While locked out, even a valid key from that IP waits.
- Headers on authenticated responses: `X-RateLimit-Limit`, `X-RateLimit-Remaining`. On 429: `Retry-After` (seconds).

## Endpoints

### GET /balance
```json
{"data": {"currency": "BDT", "available": "200.25", "reserved": "50.25"}, "request_id": "..."}
```
Amounts are decimal **strings** (never floats). `reserved` is money held for in-flight orders.

### GET /packages
```json
{"data": {
  "catalog": [{"slug": "starter", "name": "Starter", "description": null, "price": "500.00", "currency": "BDT",
               "validity_days": 30, "request_quota": 1000, "rate_limit_per_minute": 60, "allowed_services": []}],
  "owned":   [{"package": "starter", "status": "active", "starts_at": "2026-12-01T10:00:00Z", "ends_at": "2026-12-31T10:00:00Z",
               "quota_total": 1000, "quota_used": 0, "quota_remaining": 1000}]
}, "request_id": "..."}
```
`catalog` = active packages you can buy in the panel. `owned` = your purchases. `request_quota: null` = unlimited; `allowed_services: []` = no restriction.
`status` is one of `active`, `expired`, `exhausted`, `cancelled`.

### GET /services
```json
{"data": [{"slug": "free-fire.unipin", "name": "Free Fire Top-up (Unipin Voucher)", "description": "...",
           "requires_package": true, "requires_wallet": true, "package_requirement_met": true,
           "products": [{"code": "unipin-80uc", "name": "80 UC / 115 Diamond", "price": "100.00", "currency": "BDT"}]}],
 "request_id": "..."}
```
Lists **active** services only; the list is empty until an admin activates services. `products` contains only active, priced products,
at the price **you** would pay (base price, or a cheaper price tied to a package you hold). Unpriced products are never listed.

### POST /orders/free-fire/unipin  ·  POST /orders/free-fire/shell
Headers: `Authorization: Bearer ...`, **`Idempotency-Key: <8-100 chars: letters, digits, _ - : .>`** (required, unique per order you intend to place).

```json
{ "player_uid": "123456789",
  "items": [ {"product": "unipin-80uc", "quantity": 2} ],
  "reference": "your-own-order-ref",
  "region": "sgshell" }
```
- `player_uid` required (digits; default pattern `^[0-9]{5,15}$`, **assumption**). `reference` optional (max 64).
- `items`: 1+ lines, **at most 5 units in total** (**assumption**, from the provider's documented limit of five codes per call). A product code may appear once.
- `region`: **required for shell** (`shell`, `sgshell`, `myshell`, `indoshell`), **not allowed** for unipin.
- Prices are always computed by TREVO. Any price you send is ignored.

Flow: TREVO validates, prices the order, takes one package-quota unit (when the service requires a package), **reserves** the total from your wallet, saves the order and queues it for the provider. The wallet is then settled per item: successful items are **charged**, failed items are **released**.

Responses:
| HTTP | Meaning |
|---|---|
| 202 | Order accepted (`status: pending`). Poll `GET /orders/{order_id}` |
| 200 + `Idempotent-Replayed: true` | Same key and same request already accepted: the original order is returned, nothing new is reserved |
| 400 | `idempotency_key_required` / `idempotency_key_invalid` |
| 402 | `insufficient_funds` (nothing reserved) |
| 403 | `package_required` (an active package with quota that covers the service is needed) |
| 404 | `service_not_available` |
| 409 | `idempotency_key_reused` (same key, different request) · `out_of_stock` (Unipin voucher stock too low, nothing reserved) |
| 422 | `validation_failed`, `invalid_product`, `product_unavailable`, `too_many_units`, `shell_single_product` (Shell orders take exactly one product line) |
| 503 | `provider_unavailable`. **Ordering is refused until the upstream provider integration is live** |

Order object:
```json
{"data": {"order_id": "01J...", "service": "free-fire.unipin", "status": "pending", "player_uid": "123456789",
  "region": null, "reference": "your-own-order-ref", "currency": "BDT",
  "amount": {"reserved": "200.00", "charged": "0.00", "released": "0.00"},
  "items": [{"product": "unipin-80uc", "unit_price": "100.00", "status": "pending", "failure_code": null}],
  "failure_code": null, "created_at": "2026-12-01T10:00:00Z", "completed_at": null}, "request_id": "..."}
```
Order `status`: `pending` (accepted, reserved, not yet sent), `processing` (sent to the provider; wait for the result), `success`, `partial`, `failed`, `manual_review` (outcome uncertain; funds stay reserved until verified), `refunded`.
Item `status`: `pending`, `success`, `failed` (with a short `failure_code` such as `invalid_uid`, `unsupported_region`, `region_mismatch`, `out_of_stock`, `service_temporarily_unavailable`, `provider_failed`). Provider names, ids and raw provider messages are never returned.

### GET /orders/{order_id}
Returns the order object above (your own orders only). Unknown or someone else's id: 404 `order_not_found`.

## Not yet available
Reseller webhooks / signed callbacks to *your* server (Phase 7), refunds (Phase 6), order list endpoint. Ordering returns 503 `provider_unavailable` until the operator has completed the provider go-live checklist (`docs/PROVIDER.md`).
