API 文档

快速开始

KeyAuth 提供简单的 REST API 来管理您的软件授权码。所有管理接口都需要通过 HTTP Header 传递 API Key。

API Key vs 授权码

API Key(sk_xxx...)

开发者服务端使用,用于调用管理接口。不要暴露给终端用户。

授权码(XXXX-XXXX-...)

售卖给终端用户,用于在应用中激活和验证。不需要 API Key。

Headers: x-api-key: sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

管理接口(需要 API Key)

POST/api/projects

创建新项目

请求体:

{
  "name": "My App",
  "description": "应用描述(可选)"
}

响应 201:

{
  "project": {
    "id": "cmsimvttm0000jz0k1fkcd4mt",
    "name": "My App",
    "description": "应用描述(可选)",
    "createdAt": "2025-01-01T00:00:00.000Z"
  }
}
GET/api/projects

获取当前用户的项目列表

响应 200:

{
  "projects": [
    {
      "id": "cmsimvttm0000jz0k1fkcd4mt",
      "name": "My App",
      "description": "",
      "licenseKeys": [...],
      "createdAt": "2025-01-01T00:00:00.000Z"
    }
  ]
}
DELETE/api/projects/[id]

删除项目

请求体:

{
  "disableKeys": false
}

参数说明:

  • disableKeys: false 保留授权码使其继续可用(默认),true 禁用所有授权码
POST/api/keys

批量生成授权码

请求体:

{
  "projectId": "cmsimvttm0000jz0k1fkcd4mt",
  "count": 10,
  "expiresInDays": 30,
  "maxDevices": 1
}

参数说明:

  • projectId: 项目 ID(必填)
  • count: 生成数量,默认 1,最大 100
  • expiresInDays: 过期天数,不传则永不过期
  • maxDevices: 最大激活设备数,默认 1
GET/api/keys?projectId=xxx&status=active

查询项目的授权码列表

查询参数:

  • projectId: 项目 ID(必填)
  • status: 筛选状态,unused / active / expired / disabled(可选)
PATCH/api/keys/[id]

更新授权码状态

请求体:

{
  "status": "disabled"
}
DELETE/api/keys/[id]

删除授权码

GET/api/user/api-key

获取当前用户的 API Key

响应 200:

{
  "apiKey": "sk_3xrf0gmry299kawr2sjlybh24xjbp057"
}
POST/api/user/api-key

重新生成 API Key(旧 Key 立即失效)

响应 200:

{
  "apiKey": "sk_newkeyxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

验证接口(公开,无需 API Key)

这些接口供终端用户的应用调用,直接使用授权码进行验证。

POST/api/verify

验证授权码(首次调用自动激活设备)

请求体:

{
  "key": "XXXX-XXXX-XXXX-XXXX",
  "deviceId": "unique-device-id"
}

响应示例:

// 验证通过(自动激活或已激活)
{ "valid": true }

// 授权码无效
{ "valid": false, "error": "Invalid license key" }

// 授权码已禁用
{ "valid": false, "error": "License key is disabled" }

// 授权码已过期
{ "valid": false, "error": "License key has expired" }

// 设备数已达上限
{ "valid": false, "error": "Device limit reached" }
GET/api/status?key=XXXX-XXXX-XXXX-XXXX

查询授权码详情

响应 200:

{
  "key": "XXXX-XXXX-XXXX-XXXX",
  "status": "active",
  "expiresAt": "2025-02-01T00:00:00.000Z",
  "maxDevices": 1,
  "activatedDevices": 1,
  "createdAt": "2025-01-01T00:00:00.000Z",
  "project": {
    "id": "cmsimvttm0000jz0k1fkcd4mt",
    "name": "My App"
  }
}

接入指南

客户端只需调用 /api/verify 接口即可完成验证和设备激活。

推荐流程

1.App 启动时,读取本地保存的授权码
2.如果有授权码 → 调用 /api/verify 验证
3.验证通过 → 正常使用;验证失败 → 提示用户重新输入授权码
4.如果没有授权码 → 弹出输入框 → 用户输入后调用 verify(自动激活设备)→ 保存到本地

完整示例

JavaScript / TypeScript — 完整示例
const API_BASE = 'https://your-domain.com'
const STORAGE_KEY = 'license_key'

// 生成设备唯一标识
// 推荐:优先使用硬件 UUID(如 Windows 的 wmic csproduct get uuid),
// 这样重装 app 后设备 ID 不变。取不到硬件 UUID 时再随机生成并持久化。
function getDeviceId() {
  let id = localStorage.getItem('device_id')
  if (!id) {
    id = crypto.randomUUID()
    localStorage.setItem('device_id', id)
  }
  return id
}

// 验证授权
async function verifyLicense(key) {
  const res = await fetch(`${API_BASE}/api/verify`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ key, deviceId: getDeviceId() })
  })
  return res.json()
}

// App 启动时调用
async function onAppStart() {
  // 1. 尝试读取本地授权码
  let key = localStorage.getItem(STORAGE_KEY)

  // 2. 没有授权码,要求用户输入
  if (!key) {
    key = prompt('请输入授权码')
    if (!key) return showUnauthorized()
  }

  // 3. 调用 verify 验证(首次会自动激活设备)
  const result = await verifyLicense(key)

  if (result.valid) {
    // 4. 验证通过,保存授权码到本地
    localStorage.setItem(STORAGE_KEY, key)
    startApp()
  } else {
    // 5. 验证失败,清除本地缓存
    localStorage.removeItem(STORAGE_KEY)
    alert(`授权失败: ${result.error}`)
    showUnauthorized()
  }
}
Python — 完整示例
import json, uuid, requests
from pathlib import Path

API_BASE = "https://your-domain.com"
CONFIG_FILE = Path.home() / ".myapp_license"

def get_device_id():
    """读取或生成设备唯一标识
    推荐:优先使用硬件 UUID(如 Linux 的 /sys/class/dmi/id/product_uuid),
    这样重装 app 后设备 ID 不变。取不到硬件 UUID 时再随机生成并持久化。
    """
    id_file = Path.home() / ".myapp_device_id"
    if id_file.exists():
        return id_file.read_text().strip()
    device_id = str(uuid.uuid4())
    id_file.write_text(device_id)
    return device_id

def verify_license(key):
    resp = requests.post(f"{API_BASE}/api/verify", json={
        "key": key,
        "deviceId": get_device_id()
    })
    return resp.json()

def on_app_start():
    # 1. 读取本地授权码
    key = None
    if CONFIG_FILE.exists():
        key = CONFIG_FILE.read_text().strip()

    # 2. 没有则要求输入
    if not key:
        key = input("请输入授权码: ").strip()
        if not key:
            return show_unauthorized()

    # 3. 验证(首次自动激活)
    result = verify_license(key)

    if result["valid"]:
        CONFIG_FILE.write_text(key)
        start_app()
    else:
        CONFIG_FILE.unlink(missing_ok=True)
        print(f"授权失败: {result['error']}")
        show_unauthorized()

快速调用

只需要验证授权码,不需要本地存储逻辑:

JavaScript
const response = await fetch('https://your-domain.com/api/verify', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    key: 'USER_LICENSE_KEY',
    deviceId: 'unique-device-id'
  })
})

const result = await response.json()
if (result.valid) {
  console.log('授权有效')
} else {
  console.error('授权无效:', result.error)
}
Python
import requests

response = requests.post('https://your-domain.com/api/verify', json={
    'key': 'USER_LICENSE_KEY',
    'deviceId': 'unique-device-id'
})

result = response.json()
if result['valid']:
    print('授权有效')
else:
    print('授权无效:', result['error'])
C#
using var client = new HttpClient();
var response = await client.PostAsJsonAsync(
    "https://your-domain.com/api/verify",
    new { key = "USER_LICENSE_KEY", deviceId = "unique-device-id" }
);

var result = await response.Content.ReadFromJsonAsync<VerifyResult>();
if (result.valid)
{
    Console.WriteLine("授权有效");
}