> ## Documentation Index
> Fetch the complete documentation index at: https://developers.zangsho.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 頻率限制

> 帳獸 API 頻率限制規則、回應標頭與超限處理

## 限制額度

帳獸 API 依認證狀態套用不同的頻率限制：

| 類型    | 額度             | 計算依據      |
| ----- | -------------- | --------- |
| 已認證請求 | **3,600 次/小時** | 依商家 ID 計算 |
| 未認證請求 | **10 次/分鐘**    | 依 IP 位址計算 |

## Rate Limit Headers

每個 API 回應都包含以下標頭，告知你目前的頻率限制狀態：

| 標頭                      | 說明                     | 範例           |
| ----------------------- | ---------------------- | ------------ |
| `X-RateLimit-Limit`     | 限制額度                   | `3600`       |
| `X-RateLimit-Remaining` | 剩餘可用次數                 | `3597`       |
| `X-RateLimit-Reset`     | 限制重置時間（Unix timestamp） | `1738915200` |

### 回應範例

```http theme={null}
HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Limit: 3600
X-RateLimit-Remaining: 3597
X-RateLimit-Reset: 1738915200
```

## 超過限制

當請求次數超過額度時，API 會回傳 `429 Too Many Requests`：

```json theme={null}
{
  "message": "Too Many Requests"
}
```

回應會包含 `Retry-After` 標頭，告知你應等待的秒數：

```http theme={null}
HTTP/1.1 429 Too Many Requests
Retry-After: 60
Content-Type: application/json
```

## 處理策略

### 基本重試

<CodeGroup>
  ```javascript Node.js theme={null}
  async function requestWithRetry(url, options, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      const response = await fetch(url, options);

      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        console.log(`頻率限制，等待 ${retryAfter} 秒後重試...`);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      return response;
    }

    throw new Error('超過最大重試次數');
  }
  ```

  ```php PHP (Laravel) theme={null}
  function requestWithRetry(string $url, array $data = [], int $maxRetries = 3)
  {
      for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
          $response = Http::withToken(config('services.zangsho.token'))
              ->get($url, $data);

          if ($response->status() === 429) {
              $retryAfter = (int) $response->header('Retry-After', 60);
              Log::info("頻率限制，等待 {$retryAfter} 秒後重試...");
              sleep($retryAfter);
              continue;
          }

          return $response;
      }

      throw new \RuntimeException('超過最大重試次數');
  }
  ```
</CodeGroup>

### 最佳實踐

<Tip>
  * **監控剩餘額度**：定期檢查 `X-RateLimit-Remaining`，在接近 0 時主動降速
  * **批次操作**：使用批次 API（如 `/customers/batch`）一次處理多筆資料，減少請求次數
  * **快取資料**：對於不常變動的資料，在客戶端快取以減少重複請求
  * **錯開請求**：避免在短時間內發送大量請求，適當分散請求時間
</Tip>

## 計算範例

已認證請求的 3,600 次/小時限制代表：

* 平均每秒可發送 **1 次** 請求
* 平均每分鐘可發送 **60 次** 請求

實際使用中，短時間內的突發流量是允許的，只要一小時內的總量不超過限制即可。
