# Token Management (System Advanced API)

Once the site enables the **"Site Advanced API"** plugin in the admin console, you can create an **Account Permission Key** (`tb_acct_...`) in Console **Settings -> Below Notifications -> Advanced API**, and programmatically manage your API tokens via the open endpoints below (query console-synced masked lists and details, create new tokens, update quota/call count limits/expiration/model and IP restrictions, toggle active status, reset used quota, and delete tokens).

> [!IMPORTANT]
> - **Security Tips**: Enable two-factor authentication (2FA), and configure IP whitelists and expiration times for your key (`tb_acct_...`); the plaintext key is shown only once upon creation—never expose it in frontend code.
> - **Masking Protection**: `token_key` returned by query, update, toggle, and reset endpoints is always masked with asterisks (e.g., `sk-aB12****xy9Z`). Retrieving the plaintext of existing keys is not supported.
> - **Token Identifier (`kid`)**: The console page identifies keys by `kid`; every single-token `{id}` path parameter below **accepts either the token `kid` (recommended, e.g., `086421`) or the numeric `id`**.
> - **Time Format**: Time fields are uniformly output in the **site operational timezone** (e.g., `2026-11-15 01:08:26 (UTC+8)`; visibility of the timezone suffix depends on site configuration).
> - **Concurrency Control**: When "API Call Security" is enabled, maximum concurrency is tiered based on available account funds; exceeding the limit returns HTTP `429`.

---

### 1. Base URL & Authentication

* **Base URL**: `https://www.whatstoken.ai/api/open/v1`
* **Authentication Header (Choose One)**:

```http
Authorization: Bearer tb_acct_your_account_key
```

Or:

```http
X-Account-Api-Key: tb_acct_your_account_key
```

---

### 2. List API Tokens (Masked · Console Synced)

Retrieve the list of personal API keys under the current account. **By default, the returned records and fields are fully synced with the Console "Tokens" page** (including system-dedicated keys, real-time periodic usage `current_*_quota_used`, call counts `usage_used`, and `unavailable_reason`), while every record's `token_key` is strictly masked.

* **Path**: `GET /api/open/v1/tokens`
* **Query Parameters (Query)**:

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `include_playground_2026` | `integer` | `1` | Whether to include system-dedicated keys (defaults to `1`, matching the console page; pass `0` to return regular keys only) |
| `kid` | `string` | None | Exact filter by token `kid` (e.g., `086421`) |
| `is_active` | `integer` | All | Filter by status: `1` active, `0` manually disabled, `2` disabled with account, `3` auto-disabled after 30 days idle |
| `keyword` | `string` | None | Fuzzy filter by key name or `kid` keyword |

* **Request Example (Curl)**:

```bash
curl -s "https://www.whatstoken.ai/api/open/v1/tokens?is_active=1" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

* **Response Example**:

```json
{
  "data": [
    {
      "id": 42,
      "user_id": "u_0196...",
      "team_id": 0,
      "kid": "086421",
      "name": "production-app",
      "token_key": "sk-9xA2****kP8Q",
      "quota_limit": 500.0,
      "quota_used": 12.45,
      "daily_quota_limit": 50.0,
      "daily_quota_used": 1.8,
      "current_daily_quota_used": 1.8,
      "weekly_quota_limit": -1.0,
      "weekly_quota_used": 6.2,
      "current_weekly_quota_used": 6.2,
      "monthly_quota_limit": 200.0,
      "monthly_quota_used": 12.45,
      "current_monthly_quota_used": 12.45,
      "usage_limit": 10000,
      "usage_used": 318,
      "rps_limit": 10,
      "rpm_limit": 300,
      "allowed_models": "[\"gpt-4o\",\"claude-sonnet-4-6\"]",
      "allowed_ips": "192.168.1.0/24",
      "only_playground": 0,
      "only_playground_2026": 0,
      "high_availability": 1,
      "is_active": 1,
      "unavailable_reason": null,
      "last_reset_day": "2026-11-15",
      "last_reset_week": "2026-46",
      "last_reset_month": "2026-11",
      "expires_at": "2026-12-31 23:59:59 (UTC+8)",
      "last_used_at": "2026-11-15 10:12:00 (UTC+8)",
      "created_at": "2026-11-10 16:00:00 (UTC+8)",
      "updated_at": "2026-11-15 09:30:00 (UTC+8)"
    }
  ],
  "total": 1
}
```

* **Key Response Fields**:
  * `kid`: The token identifier shown in the first column of the console page (e.g., `086421`), directly usable in detail, update, status, reset, and delete paths.
  * `quota_limit` / `daily_quota_limit` / `weekly_quota_limit` / `monthly_quota_limit` / `usage_limit`: `-1` means unlimited.
  * `quota_used` / `usage_used`: Cumulative consumed quota and call count; `current_daily_quota_used` / `current_weekly_quota_used` / `current_monthly_quota_used` reflect real-time usage for the active calendar period (matching the console rings).
  * `rps_limit` / `rpm_limit`: `0` means unlimited.
  * `unavailable_reason`: When `is_active = 1` but gateway calls would be rejected, returns the reason (`arrears` / `no_funds` / `expired` / `quota_total` / `quota_daily` / `quota_weekly` / `quota_monthly` / `quota_count`); otherwise `null`.

---

### 3. Get Single Token Details (Masked)

Query the configuration and current daily/weekly/monthly/total quota and call count statistics of a key by its `kid` (recommended) or numeric `id`. The returned `token_key` remains masked.

* **Path**: `GET /api/open/v1/tokens/{id}` (`{id}` accepts token `kid` or numeric `id`)
* **Request Example (Curl)**:

```bash
curl -s "https://www.whatstoken.ai/api/open/v1/tokens/086421" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

---

### 4. Create New Token

Create a personal API key with full parity to the console page, supporting total quota, daily/weekly/monthly periodic quotas, call count limits, RPS/RPM rate limits, model whitelists, IP whitelists, and expiration configuration.

* **Path**: `POST /api/open/v1/tokens`
* **Request Body Parameters (JSON)**:

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `name` | `string` | No | Key name (auto-generated by default) |
| `quota_limit` | `number \| null` | No | Total spending quota limit (in site billing units); `-1`, `null`, or omitted means unlimited |
| `daily_quota_limit` | `number \| null` | No | Daily spending quota limit; `-1` or `null` means unlimited |
| `weekly_quota_limit` | `number \| null` | No | Weekly spending quota limit; `-1` or `null` means unlimited |
| `monthly_quota_limit` | `number \| null` | No | Monthly spending quota limit; `-1` or `null` means unlimited |
| `usage_limit` | `integer \| null` | No | Total call count limit; `-1` or `null` means unlimited |
| `rps_limit` | `integer \| null` | No | Requests per second limit (RPS); `0` or `null` means unlimited |
| `rpm_limit` | `integer \| null` | No | Requests per minute limit (RPM); `0` or `null` means unlimited |
| `allowed_models` | `string[] \| null` | No | List of allowed model IDs; empty or `null` means unrestricted |
| `allowed_ips` | `string \| null` | No | Allowed source IPs / CIDRs (comma-separated) |
| `expires_at` | `string \| null` | No | Absolute expiration time (supports site timezone `YYYY-MM-DD HH:mm:ss`, `YYYY-MM-DD`, or ISO 8601); pass `""` for never expires |
| `expire_days` | `integer` | No | Validity days relative to the current time (e.g., `30` means expires in 30 days; cannot be combined with `expires_at`) |
| `high_availability` | `integer` | No | High-availability mode toggle: `1` on (default), `0` off |
| `is_active` | `integer` | No | Initial status: `1` enabled (default), `0` disabled |

* **Request Example (Curl)**:

```bash
curl -s -X POST "https://www.whatstoken.ai/api/open/v1/tokens" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "backend-worker-01",
    "quota_limit": 200.0,
    "daily_quota_limit": 25.0,
    "weekly_quota_limit": 100.0,
    "monthly_quota_limit": 200.0,
    "usage_limit": 5000,
    "rps_limit": 5,
    "rpm_limit": 120,
    "allowed_models": ["gpt-4o", "gemini-2.5-flash"],
    "allowed_ips": "203.0.113.10,10.0.0.0/8",
    "expire_days": 30,
    "is_active": 1
  }'
```

---

### 5. Update / Configure Existing Token (Including Quota & Call Count Limits)

Incrementally update an existing key's name, **total/daily/weekly/monthly quota limits, total call count limit**, RPS/RPM rate limits, expiration time, model whitelist, IP whitelist, high-availability toggle, and active status (only pass the fields to modify; omitted fields remain unchanged, and `token_key` in the response stays masked).

* **Path**: `PUT /api/open/v1/tokens/{id}` or `PATCH /api/open/v1/tokens/{id}` (`{id}` accepts token `kid` or numeric `id`)
* **Request Body Parameters (JSON, all optional for partial update)**:

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `name` | `string` | Key name (max 24 characters) |
| `quota_limit` | `number \| null` | Total spending quota limit; pass `-1` or `null` to remove the limit (unlimited), omit to keep unchanged |
| `daily_quota_limit` | `number \| null` | Daily spending quota limit; pass `-1` or `null` to remove, omit to keep unchanged |
| `weekly_quota_limit` | `number \| null` | Weekly spending quota limit; pass `-1` or `null` to remove, omit to keep unchanged |
| `monthly_quota_limit` | `number \| null` | Monthly spending quota limit; pass `-1` or `null` to remove, omit to keep unchanged |
| `usage_limit` | `integer \| null` | Total call count limit; pass `-1` or `null` to remove, omit to keep unchanged |
| `rps_limit` | `integer \| null` | Requests per second limit (RPS); pass `0` or `null` to remove, omit to keep unchanged |
| `rpm_limit` | `integer \| null` | Requests per minute limit (RPM); pass `0` or `null` to remove, omit to keep unchanged |
| `allowed_models` | `string[]` | Allowed model IDs; pass `[]` to allow all models |
| `allowed_ips` | `string` | Allowed source IPs / CIDRs (comma-separated); pass `""` to clear the whitelist |
| `expires_at` | `string \| null` | Absolute expiration time; pass `""`, `null`, or `"permanent"` for **never expire** |
| `expire_days` | `integer` | Relative validity days from now (`1..=36500`; cannot be combined with a non-empty `expires_at`) |
| `high_availability` | `integer` | High-availability toggle: `1` on, `0` off |
| `is_active` | `integer` | Active status: `1` enabled, `0` disabled (system-locked dedicated keys only accept this field) |

* **Request Example (Curl) — Updating Quota & Call Count Limits**:

```bash
curl -s -X PATCH "https://www.whatstoken.ai/api/open/v1/tokens/086421" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{
    "quota_limit": 1000.0,
    "daily_quota_limit": 80.0,
    "weekly_quota_limit": 300.0,
    "monthly_quota_limit": null,
    "usage_limit": 5000,
    "expires_at": "2027-06-30 23:59:59"
  }'
```

---

### 6. Quick Toggle Token Status

Quickly enable or disable a specified key without submitting the full configuration.

* **Path**: `PATCH /api/open/v1/tokens/{id}/status` or `POST /api/open/v1/tokens/{id}/status` (`{id}` accepts token `kid` or numeric `id`)
* **Request Body Parameters**: Pass `{ "is_active": 0 | 1 }` or `{ "enabled": true | false }`.
* **Request Example (Curl)**:

```bash
curl -s -X PATCH "https://www.whatstoken.ai/api/open/v1/tokens/086421/status" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{"is_active": 0}'
```

---

### 7. Reset Token Used Quota / Usage Count

Reset the consumed quota or call count of a key along a specified dimension (does not affect your actual account wallet ledger; only resets that token's limit counters).

* **Path**: `POST /api/open/v1/tokens/{id}/reset-usage` (`{id}` accepts token `kid` or numeric `id`)
* **Supported Targets (`target`)**: `all` (default, reset all), `total`, `daily`, `weekly`, `monthly`, `usage_count`.
* **Request Example (Curl)**:

```bash
curl -s -X POST "https://www.whatstoken.ai/api/open/v1/tokens/086421/reset-usage" \
  -H "Authorization: Bearer tb_acct_your_account_key" \
  -H "Content-Type: application/json" \
  -d '{"target": "daily"}'
```

---

### 8. Delete & Destroy Token

Permanently delete a specified personal key. Once destroyed, it immediately becomes unusable and cannot be recovered (except system-locked dedicated keys).

* **Path**: `DELETE /api/open/v1/tokens/{id}` (`{id}` accepts token `kid` or numeric `id`)
* **Request Example (Curl)**:

```bash
curl -s -X DELETE "https://www.whatstoken.ai/api/open/v1/tokens/086421" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

* **Response Example**:

```json
{
  "success": true,
  "id": 42,
  "deleted_id": 42,
  "kid": "086421",
  "message": "Token deleted successfully"
}
```

---

### 9. List Available Models

Retrieve the list of model IDs visible to the current user and backed by available channels, making it convenient to populate `allowed_models` when creating or configuring keys.

* **Path**: `GET /api/open/v1/models`
* **Request Example (Curl)**:

```bash
curl -s "https://www.whatstoken.ai/api/open/v1/models" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

---

### 10. Get Account ID & Real-Time Balance

Retrieve the account ID (`uid` / `id`), user level discount, and real-time balance breakdown (cash balance, gift balance, credit limit, and effective available funds) for the account bound to the key.

* **Path**: `GET /api/open/v1/account`
* **Request Example (Curl)**:

```bash
curl -s "https://www.whatstoken.ai/api/open/v1/account" \
  -H "Authorization: Bearer tb_acct_your_account_key"
```

* **Response Example**:

```json
{
  "user_id": "10086",
  "uid": "10086",
  "id": "u_0196...",
  "username": "alice",
  "nickname": "Alice",
  "user_group": "vip",
  "level_name": "VIP 1",
  "level_discount": 0.9,
  "balance": 500.0,
  "gift_balance": 20.0,
  "credit_limit": 0.0,
  "available_funds": 520.0,
  "cash_in_arrears": false,
  "used_quota": 128.5,
  "gift_used_quota": 5.0,
  "currency": "CNY",
  "currency_symbol": "¥",
  "currency_unit": "元",
  "site_name": "TokensByte"
}
```
