# License Manager API Reference

许可证管理系统 API 完整参考文档。

## 目录

- [授权端 API (License Issuer)](#授权端-api-license-issuer)
- [被授权端 API (License Verifier)](#被授权端-api-license-verifier)
- [错误代码](#错误代码)
- [数据模型](#数据模型)

---

## 授权端 API (License Issuer)

授权端 API 用于生成和管理许可证。

### POST /api/licenses/generate

生成单个许可证。

**请求头**：

```http
Content-Type: application/json
Authorization: Bearer <admin-token>  // 如果需要认证
```

**请求体**：

```json
{
  "licenseId": "LIC-2024-001",
  "clientId": "customer-001",
  "type": "STANDARD",
  "customerName": "北京科技有限公司",
  "customerEmail": "contact@example.com",
  "features": {
    "aiAssistant": true,
    "advancedAnalytics": false,
    "customReports": true,
    "apiAccess": true
  },
  "limits": {
    "maxUsers": 200,
    "maxRequests": 1000000,
    "maxStorage": 51200
  },
  "bindings": {
    "domain": "*.example.com"
  },
  "duration": 365,
  "gracePeriodDays": 30,
  "metadata": {
    "salesperson": "张三",
    "contractId": "CT-2024-001"
  }
}
```

**字段说明**：

| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `licenseId` | string | 否 | 许可证唯一ID，系统自动生成（默认） |
| `clientId` | string | 是 | 客户ID |
| `type` | string | 是 | 许可证类型：`TRIAL`, `STANDARD`, `PROFESSIONAL`, `ENTERPRISE`, `CUSTOM` |
| `customerName` | string | 是 | 客户名称 |
| `customerEmail` | string | 否 | 客户邮箱 |
| `features` | object | 否 | 功能授权配置 |
| `limits` | object | 否 | 使用限制配置 |
| `bindings` | object | 否 | 绑定信息配置 |
| `duration` | number | 否* | 有效期（天），与 `expiresAt` 二选一 |
| `expiresAt` | string | 否* | 过期日期（ISO 8601），与 `duration` 二选一 |
| `gracePeriodDays` | number | 否 | 宽限期天数 |
| `metadata` | object | 否 | 自定义元数据 |

* `duration` 和 `expiresAt` 至少提供一个，都不提供则默认为365天。

**响应示例**：

```json
{
  "success": true,
  "data": {
    "licenseId": "LIC-2024-001",
    "licenseKey": "eyJkYXRhIjp7ImxpY2Vuc2VJZCI6IkxJQy0yMDI0LTAwMSIs...",
    "issuedAt": "2024-01-24T00:00:00.000Z",
    "expiresAt": "2025-01-24T00:00:00.000Z",
    "type": "STANDARD",
    "customerName": "北京科技有限公司"
  }
}
```

**错误响应**：

```json
{
  "success": false,
  "error": "INVALID_INPUT",
  "message": "缺少必需字段: clientId"
}
```

---

### POST /api/licenses/batch-generate

批量生成许可证。

**请求头**：

```http
Content-Type: application/json
```

**请求体**：

```json
{
  "customers": [
    {
      "clientId": "customer-001",
      "customerName": "公司A",
      "type": "STANDARD",
      "duration": 365
    },
    {
      "clientId": "customer-002",
      "customerName": "公司B",
      "type": "PROFESSIONAL",
      "duration": 365
    }
  ]
}
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "total": 2,
    "licenses": [
      {
        "clientId": "customer-001",
        "licenseId": "customer-001-1706102400000",
        "licenseKey": "eyJkYXRhIj...",
        "customerName": "公司A"
      },
      {
        "clientId": "customer-002",
        "licenseId": "customer-002-1706102400001",
        "licenseKey": "eyJkYXRhIj...",
        "customerName": "公司B"
      }
    ]
  }
}
```

---

### POST /api/licenses/renew

续费许可证（生成新许可证）。

**请求头**：

```http
Content-Type: application/json
```

**请求体**：

```json
{
  "oldLicenseKey": "eyJkYXRhIj...",
  "additionalDuration": 365
}
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "oldLicenseId": "LIC-2024-001",
    "newLicenseId": "LIC-2024-001-renewed",
    "newLicenseKey": "eyJkYXRhIj...",
    "newExpiresAt": "2026-01-24T00:00:00.000Z"
  }
}
```

---

### POST /api/licenses/upgrade

升级许可证类型。

**请求头**：

```http
Content-Type: application/json
```

**请求体**：

```json
{
  "oldLicenseKey": "eyJkYXRhIj...",
  "newType": "ENTERPRISE"
}
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "oldLicenseId": "LIC-2024-001",
    "oldType": "STANDARD",
    "newLicenseId": "LIC-2024-001-upgraded",
    "newType": "ENTERPRISE",
    "newLicenseKey": "eyJkYXRhIj..."
  }
}
```

---

### GET /api/licenses/:licenseId

查询许可证信息（授权端）。

**请求头**：

```http
Authorization: Bearer <admin-token>
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "licenseId": "LIC-2024-001",
    "clientId": "customer-001",
    "customerName": "北京科技有限公司",
    "customerEmail": "contact@example.com",
    "type": "STANDARD",
    "issuedAt": "2024-01-24T00:00:00.000Z",
    "expiresAt": "2025-01-24T00:00:00.000Z",
    "gracePeriodDays": 30,
    "features": {
      "aiAssistant": true,
      "advancedAnalytics": false,
      "customReports": true,
      "apiAccess": true
    },
    "limits": {
      "maxUsers": 200,
      "maxRequests": 1000000,
      "maxStorage": 51200
    },
    "bindings": {
      "domain": "*.example.com"
    },
    "metadata": {
      "salesperson": "张三",
      "contractId": "CT-2024-001"
    },
    "status": "active",
    "createdAt": "2024-01-24T00:00:00.000Z",
    "updatedAt": "2024-01-24T00:00:00.000Z"
  }
}
```

---

### GET /api/licenses

列出所有许可证（支持分页和过滤）。

**查询参数**：

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `page` | number | 否 | 页码，默认1 |
| `limit` | number | 否 | 每页数量，默认20 |
| `type` | string | 否 | 过滤许可证类型 |
| `clientId` | string | 否 | 过滤客户ID |
| `status` | string | 否 | 过滤状态：`active`, `expired`, `grace_period` |
| `search` | string | 否 | 搜索客户名称 |

**请求示例**：

```http
GET /api/licenses?page=1&limit=20&type=STANDARD&status=active
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "licenses": [
      {
        "licenseId": "LIC-2024-001",
        "clientId": "customer-001",
        "customerName": "北京科技有限公司",
        "type": "STANDARD",
        "status": "active",
        "expiresAt": "2025-01-24T00:00:00.000Z"
      }
    ],
    "pagination": {
      "total": 100,
      "page": 1,
      "limit": 20,
      "totalPages": 5
    }
  }
}
```

---

## 被授权端 API (License Verifier)

被授权端 API 用于验证许可证和获取许可证信息。

### GET /api/license/info

获取许可证信息。

**请求头**：

```http
X-License-Key: <license-key>
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "licenseId": "LIC-2024-001",
    "customerName": "北京科技有限公司",
    "customerEmail": "contact@example.com",
    "type": "professional",
    "issuedAt": "2024-01-24T00:00:00.000Z",
    "expiresAt": "2025-01-24T00:00:00.000Z",
    "isExpired": false,
    "isInGracePeriod": false,
    "gracePeriodDaysRemaining": 30,
    "features": {
      "aiAssistant": true,
      "advancedAnalytics": true,
      "customReports": true,
      "apiAccess": true,
      "whiteLabel": false,
      "multiTenant": false,
      "customIntegration": false,
      "premiumSupport": false
    },
    "limits": {
      "maxUsers": 200,
      "maxRequests": 1000000,
      "maxStorage": 51200,
      "concurrentSessions": null,
      "maxProjects": null,
      "maxTeams": null
    },
    "bindings": {
      "domain": "*.example.com",
      "ipAddress": null,
      "machineId": null,
      "macAddress": null
    }
  }
}
```

---

### GET /api/license/check-feature

检查特定功能权限。

**请求头**：

```http
X-License-Key: <license-key>
```

**查询参数**：

| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `feature` | string | 是 | 功能名称 |

**请求示例**：

```http
GET /api/license/check-feature?feature=aiAssistant
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "feature": "aiAssistant",
    "enabled": true,
    "availableFeatures": [
      "aiAssistant",
      "advancedAnalytics",
      "customReports",
      "apiAccess"
    ]
  }
}
```

---

### GET /api/license/usage

获取使用量信息。

**请求头**：

```http
X-License-Key: <license-key>
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "users": {
      "current": 150,
      "max": 200,
      "remaining": 50,
      "percentage": 75,
      "status": "ok"
    },
    "requests": {
      "current": 450000,
      "max": 1000000,
      "remaining": 550000,
      "percentage": 45,
      "status": "ok",
      "resetDate": "2024-02-01T00:00:00.000Z"
    },
    "storage": {
      "current": 25600,
      "max": 51200,
      "remaining": 25600,
      "percentage": 50,
      "status": "ok",
      "unit": "MB"
    }
  },
  "warnings": [
    {
      "type": "approaching_limit",
      "limit": "users",
      "message": "用户数即将达到上限（75%）"
    }
  ]
}
```

---

### POST /api/license/verify

验证许可证（显式验证端点）。

**请求头**：

```http
Content-Type: application/json
```

**请求体**：

```json
{
  "licenseKey": "eyJkYXRhIj..."
}
```

**响应示例（成功）**：

```json
{
  "success": true,
  "data": {
    "valid": true,
    "license": {
      "licenseId": "LIC-2024-001",
      "customerName": "北京科技有限公司",
      "type": "professional"
    },
    "warnings": []
  }
}
```

**响应示例（失败）**：

```json
{
  "success": false,
  "error": "LICENSE_EXPIRED",
  "message": "许可证已过期",
  "details": {
    "licenseId": "LIC-2024-001",
    "expiredAt": "2024-01-01T00:00:00.000Z",
    "gracePeriodAvailable": true,
    "gracePeriodDaysRemaining": 0
  }
}
```

---

### GET /api/license/status

获取许可证状态摘要。

**请求头**：

```http
X-License-Key: <license-key>
```

**响应示例**：

```json
{
  "success": true,
  "data": {
    "status": "active",
    "licenseId": "LIC-2024-001",
    "customerName": "北京科技有限公司",
    "type": "professional",
    "expiresAt": "2025-01-24T00:00:00.000Z",
    "daysUntilExpiry": 365,
    "inGracePeriod": false,
    "gracePeriodDaysRemaining": 0,
    "featuresCount": {
      "enabled": 4,
      "total": 8
    },
    "limitsSummary": {
      "users": "75% used",
      "requests": "45% used",
      "storage": "50% used"
    }
  }
}
```

---

## 错误代码

### 通用错误

| 代码 | HTTP状态码 | 说明 |
|------|-----------|------|
| `SUCCESS` | 200 | 请求成功 |
| `INVALID_REQUEST` | 400 | 请求参数无效 |
| `UNAUTHORIZED` | 401 | 未授权 |
| `FORBIDDEN` | 403 | 权限不足 |
| `NOT_FOUND` | 404 | 资源不存在 |
| `RATE_LIMIT_EXCEEDED` | 429 | 请求速率超限 |
| `INTERNAL_ERROR` | 500 | 内部服务器错误 |

### 许可证错误

| 代码 | HTTP状态码 | 说明 |
|------|-----------|------|
| `LICENSE_MISSING` | 401 | 许可证密钥缺失 |
| `LICENSE_INVALID` | 401 | 许可证无效（格式错误） |
| `LICENSE_SIGNATURE_INVALID` | 401 | 许可证签名无效 |
| `LICENSE_EXPIRED` | 403 | 许可证已过期 |
| `LICENSE_BINDING_MISMATCH` | 403 | 许可证绑定不匹配 |
| `FEATURE_NOT_AUTHORIZED` | 403 | 功能权限不足 |
| `LIMIT_EXCEEDED` | 429 | 使用量超限 |

### 错误响应格式

```json
{
  "success": false,
  "error": "LICENSE_EXPIRED",
  "message": "许可证已过期",
  "details": {
    "licenseId": "LIC-2024-001",
    "expiredAt": "2024-01-01T00:00:00.000Z",
    "suggestion": "请联系销售续费"
  },
  "timestamp": "2024-01-24T00:00:00.000Z",
  "requestId": "req-abc123"
}
```

---

## 数据模型

### LicenseData

许可证数据结构：

```typescript
interface LicenseData {
  // 基本信息
  licenseId: string;              // 许可证唯一ID
  clientId: string;               // 客户ID
  type: LicenseType;              // 许可证类型
  customerName: string;           // 客户名称
  customerEmail?: string;         // 客户邮箱

  // 功能授权
  features: LicenseFeatures;      // 功能配置

  // 使用限制
  limits: LicenseLimits;          // 限制配置

  // 绑定信息
  bindings: LicenseBindings;      // 绑定配置

  // 时间信息
  issuedAt: string;               // 发行日期（ISO 8601）
  expiresAt: string;              // 过期日期（ISO 8601）
  gracePeriodDays?: number;       // 宽限期天数

  // 元数据
  metadata?: Record<string, any>; // 自定义元数据
}
```

### LicenseFeatures

功能配置：

```typescript
interface LicenseFeatures {
  aiAssistant: boolean;           // AI助手
  advancedAnalytics: boolean;     // 高级分析
  customReports: boolean;         // 自定义报表
  apiAccess: boolean;             // API访问
  whiteLabel: boolean;            // 白标功能
  multiTenant: boolean;           // 多租户
  customIntegration: boolean;     // 自定义集成
  premiumSupport: boolean;        // 高级支持
  [key: string]: boolean | undefined;  // 其他自定义功能
}
```

### LicenseLimits

限制配置：

```typescript
interface LicenseLimits {
  maxUsers?: number;              // 最大用户数
  maxRequests?: number;           // 最大API请求数/月
  maxStorage?: number;            // 最大存储空间（MB）
  concurrentSessions?: number;    // 最大并发会话数
  maxProjects?: number;           // 最大项目数
  maxTeams?: number;              // 最大团队数
}
```

### LicenseBindings

绑定配置：

```typescript
interface LicenseBindings {
  domain?: string;                // 域名绑定（支持通配符）
  ipAddress?: string;             // IP地址绑定
  machineId?: string;             // 机器码绑定
  macAddress?: string;            // MAC地址绑定
}
```

### LicenseType

许可证类型枚举：

```typescript
enum LicenseType {
  TRIAL = 'trial',                // 试用版
  STANDARD = 'standard',          // 标准版
  PROFESSIONAL = 'professional',  // 专业版
  ENTERPRISE = 'enterprise',      // 企业版
  CUSTOM = 'custom'               // 自定义
}
```

---

## 示例代码

### cURL 示例

```bash
# 生成许可证
curl -X POST https://license-issuer.example.com/api/licenses/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-admin-token" \
  -d '{
    "clientId": "customer-001",
    "type": "STANDARD",
    "customerName": "示例客户",
    "duration": 365
  }'

# 验证许可证
curl https://app.example.com/api/license/info \
  -H "X-License-Key: eyJkYXRhIj..."

# 检查功能权限
curl https://app.example.com/api/license/check-feature?feature=aiAssistant \
  -H "X-License-Key: eyJkYXRhIj..."

# 获取使用量
curl https://app.example.com/api/license/usage \
  -H "X-License-Key: eyJkYXRhIj..."
```

### JavaScript 示例

```javascript
// 生成许可证
const response = await fetch('https://license-issuer.example.com/api/licenses/generate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-admin-token',
  },
  body: JSON.stringify({
    clientId: 'customer-001',
    type: 'STANDARD',
    customerName: '示例客户',
    duration: 365,
  }),
});

const { data } = await response.json();
console.log('License Key:', data.licenseKey);

// 验证许可证
const licenseInfo = await fetch('https://app.example.com/api/license/info', {
  headers: {
    'X-License-Key': data.licenseKey,
  },
}).then(r => r.json());

console.log('License Info:', licenseInfo);
```

### Python 示例

```python
import requests

# 生成许可证
response = requests.post(
    'https://license-issuer.example.com/api/licenses/generate',
    headers={
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-admin-token',
    },
    json={
        'clientId': 'customer-001',
        'type': 'STANDARD',
        'customerName': '示例客户',
        'duration': 365,
    }
)

data = response.json()['data']
print('License Key:', data['licenseKey'])

# 验证许可证
license_info = requests.get(
    'https://app.example.com/api/license/info',
    headers={
        'X-License-Key': data['licenseKey'],
    }
).json()

print('License Info:', license_info)
```

---

## 版本信息

- **当前版本**: v1.0.0
- **API 基础URL**: `https://api.example.com`
- **文档更新**: 2024-01-24

## 支持

- **技术文档**: https://docs.example.com
- **API 状态**: https://status.example.com
- **问题反馈**: https://github.com/example/license-manager/issues
