Appearance
场景示例
下面的示例用 Python 3.8+ 和 requests 库编写(pip install requests),Node.js 只给出客户端封装。账户 API 密钥从环境变量 FASTAITOKEN_ACCOUNT_KEY 读取:
bash
export FASTAITOKEN_ACCOUNT_KEY=user-0123456789abcdef...客户端封装
统一处理认证、错误和 429 重试,后面的示例都基于它。
python
import os
import time
import requests
BASE = "https://www.fastaitoken.com/api/v1"
class AccountAPIError(Exception):
def __init__(self, status, body):
self.status = status
self.code = body.get("code")
self.reason = body.get("reason")
self.message = body.get("message") or body.get("error")
super().__init__(f"HTTP {status} {self.reason or self.code}: {self.message}")
class AccountAPI:
def __init__(self, key=None, base=BASE, max_retries=3):
self.base = base
self.max_retries = max_retries
self.session = requests.Session()
self.session.headers["x-api-key"] = key or os.environ["FASTAITOKEN_ACCOUNT_KEY"]
def request(self, method, path, **kwargs):
for attempt in range(self.max_retries + 1):
resp = self.session.request(method, self.base + path, timeout=30, **kwargs)
# 429 表示请求没有被处理,按 Retry-After 等待后重试是安全的
if resp.status_code == 429 and attempt < self.max_retries:
time.sleep(int(resp.headers.get("Retry-After", "5")))
continue
try:
body = resp.json()
except ValueError:
body = {"message": resp.text[:200]}
if resp.status_code >= 400:
raise AccountAPIError(resp.status_code, body)
return body.get("data")
def get(self, path, **params):
return self.request("GET", path, params=params)
def post(self, path, json=None, headers=None):
return self.request("POST", path, json=json, headers=headers)
def put(self, path, json):
return self.request("PUT", path, json=json)
def delete(self, path):
return self.request("DELETE", path)
api = AccountAPI()Node.js 18+(内置 fetch):
js
const BASE = 'https://www.fastaitoken.com/api/v1'
export async function api(method, path, { query, body, headers } = {}) {
const url = new URL(BASE + path)
for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, String(v))
for (let attempt = 0; ; attempt++) {
const resp = await fetch(url, {
method,
headers: {
'x-api-key': process.env.FASTAITOKEN_ACCOUNT_KEY,
...(body ? { 'Content-Type': 'application/json' } : {}),
...headers
},
body: body ? JSON.stringify(body) : undefined
})
if (resp.status === 429 && attempt < 3) {
const wait = Number(resp.headers.get('Retry-After') ?? 5)
await new Promise((resolve) => setTimeout(resolve, wait * 1000))
continue
}
const data = await resp.json().catch(() => ({}))
if (!resp.ok) {
throw new Error(`HTTP ${resp.status} ${data.reason ?? data.code ?? ''}: ${data.message ?? data.error ?? ''}`)
}
return data.data
}
}
// 用法:const profile = await api('GET', '/user/profile')给员工批量发密钥
从 CSV 读员工名单,每人建一把带总额度和日限额的密钥,结果写进另一个 CSV。Idempotency-Key 用员工编号生成,脚本中途失败后重跑(24 小时内)不会重复建密钥。
python
import csv
import time
# employees.csv 的列:employee_id,name,group_id,quota,daily_limit
with open("employees.csv", newline="", encoding="utf-8") as src, \
open("issued_keys.csv", "w", newline="", encoding="utf-8") as dst:
writer = csv.writer(dst)
writer.writerow(["employee_id", "name", "key_id", "key"])
for row in csv.DictReader(src):
key = api.post(
"/keys",
json={
"name": row["name"],
"group_id": int(row["group_id"]),
"quota": float(row["quota"]),
"rate_limit_1d": float(row["daily_limit"]),
"expires_in_days": 365,
},
headers={"Idempotency-Key": f"onboard-{row['employee_id']}"},
)
writer.writerow([row["employee_id"], row["name"], key["id"], key["key"]])
time.sleep(0.5)- 每小时最多新建 60 把密钥,人多时分批执行;超过 24 小时后重跑,先用
GET /keys?search=姓名确认是否已经建过。 issued_keys.csv里是明文密钥,请通过安全渠道分发,发完即删。- 要用几家厂商的模型就为每人建几把(每把绑一个分组),分组 ID 见 可用分组。
每日费用对账
每天凌晨导出前一天(北京时间)每把密钥的实际扣费,写成 Excel 能直接打开的 CSV。
python
import csv
from datetime import datetime, timedelta, timezone
CN = timezone(timedelta(hours=8))
day = (datetime.now(CN) - timedelta(days=1)).strftime("%Y-%m-%d")
params = {"start_date": day, "end_date": day, "timezone": "Asia/Shanghai"}
total = api.get("/usage/stats", **params)
ranking = api.get("/usage/key-ranking", sort_by="actual_cost", limit=200, **params)
with open(f"cost-{day}.csv", "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["日期", "密钥ID", "密钥名称", "已删除", "请求数", "总token", "实际扣费(USD)"])
for k in ranking["keys"]:
writer.writerow([day, k["api_key_id"], k["name"], k["deleted"],
k["requests"], k["total_tokens"], round(k["actual_cost"], 6)])
print(f"{day}:{total['total_requests']} 次请求,实际扣费 {total['total_actual_cost']:.4f} USD")key-ranking 一次最多返回 200 把密钥。密钥更多时,按 api_key_id 逐把查 /usage/stats,或按天分页拉 使用记录 自行汇总。
余额与预算预警
定时检查账户余额、各密钥当天的花费和订阅额度,接近上限时通知负责人。
python
def notify(text):
print(text) # 换成企业微信、钉钉、飞书或邮件通知
profile = api.get("/user/profile")
if profile["balance"] < 100:
notify(f"账户余额只剩 {profile['balance']:.2f} USD,请及时充值")
# 每把密钥的日预算(USD),超过 80% 时提醒
budgets = {3721: 20.0, 3722: 50.0}
stats = api.post("/usage/dashboard/api-keys-usage", json={"api_key_ids": list(budgets)})["stats"]
for key_id, budget in budgets.items():
spent = stats.get(str(key_id), {}).get("today_actual_cost", 0)
if spent >= budget * 0.8:
notify(f"密钥 {key_id} 今天已花 {spent:.2f} USD,预算 {budget:.2f} USD")
for item in api.get("/subscriptions/progress"):
daily = item["progress"].get("daily")
if daily and daily["percentage"] >= 90:
notify(f"订阅「{item['progress']['group_name']}」今日额度已用 {daily['percentage']:.0f}%")预警只负责提醒。需要硬性封顶时,直接给密钥设置 rate_limit_1d、quota 等上限(见 修改 API 密钥),到达上限后调用会被拒绝。
员工离职回收密钥
按名称找到员工的密钥并停用;确认不再需要后再删除。
python
def disable_keys(name, delete=False):
keys = api.get("/keys", search=name, page_size=100)["items"]
for k in keys:
if k["name"] != name: # search 是模糊匹配,这里按名称精确比较
continue
if delete:
api.delete(f"/keys/{k['id']}")
print("已删除", k["id"], k["name"])
elif k["status"] == "active":
api.put(f"/keys/{k['id']}", json={"status": "inactive"})
print("已停用", k["id"], k["name"])
disable_keys("研发-张三")名称里的 <、>、&、引号保存时会被转成 HTML 实体,按名称比较时请注意。停用通常几秒内生效,最长约 5 分钟。
月底开票
找出某个月可开票的订单和兑换码,提交一张普票申请。
python
import re
from datetime import datetime, timedelta, timezone
CN = timezone(timedelta(hours=8))
def to_cn_time(ts):
ts = re.sub(r"\.\d+", "", ts).replace("Z", "+00:00")
return datetime.fromisoformat(ts).astimezone(CN)
def list_invoiceable():
items, page = [], 1
while True:
data = api.get("/payment/orders/my", statuses="PAID,COMPLETED",
include_redeem="true", page=page, page_size=100)
items += data["items"]
if page >= data["pages"]:
return items
page += 1
def can_invoice(o):
if o["invoice_status"] != "unissued" or o["payment_type"] == "balance":
return False
if o["order_type"] == "subscription" and o.get("currency") not in (None, "", "CNY"):
return False
return True
month = "2026-11"
chosen = [o for o in list_invoiceable()
if can_invoice(o) and to_cn_time(o.get("paid_at") or o["created_at"]).strftime("%Y-%m") == month]
total = sum(o["amount"] - o["bonus_amount"] for o in chosen)
if not chosen or total < 100:
raise SystemExit(f"{month} 可开票金额 {total:.2f},不足 100,暂不提交")
ticket = api.post("/tickets", json={
"category": "finance",
"order_ids": [o["id"] for o in chosen][:100],
"invoice_type": "general",
"invoice_title": "示例科技有限公司",
"invoice_email": "[email protected]",
"tax_no": "91310000MA1XXXXXXX",
"content": f"{month} 信息技术服务费",
})
print("已提交开票申请,工单号", ticket["id"])- 一张申请最多 100 个条目,多于 100 个时分几张提交。
- 兑换码条目的
id是负数,原样提交即可。 - 开票规则和专票所需字段见 开票与工单。
命令行速查
装好 curl 和 jq 后,可以在终端里快速查看:
bash
export BASE=https://www.fastaitoken.com/api/v1
H="x-api-key: $FASTAITOKEN_ACCOUNT_KEY"
# 余额
curl -s "$BASE/user/profile" -H "$H" | jq '.data.balance'
# 今天花费最多的 10 把密钥
curl -s "$BASE/usage/key-ranking?period=today&sort_by=actual_cost&limit=10" -H "$H" \
| jq -r '.data.keys[] | "\(.name)\t\(.actual_cost)"'
# 所有正常状态的密钥:ID、名称、已用额度
curl -s "$BASE/keys?status=active&page_size=1000" -H "$H" \
| jq -r '.data.items[] | "\(.id)\t\(.name)\t\(.quota_used)"'
# 停用某把密钥
curl -s -X PUT "$BASE/keys/3721" -H "$H" -H "Content-Type: application/json" -d '{"status": "inactive"}'