# 001云盘 开放API开发文档

## 一、API概述

### 1.1 接口地址
```
生产环境: https://01pan.cn/api/openapi
```

实际入口以 `/api/openapi/*.php` 文件为准，例如 `/api/openapi/token.php`、`/api/openapi/files.php`、`/api/openapi/direct-links.php`。历史无 `.php` 的路径仅作为产品模块名说明，不建议第三方接入使用。

### 1.2 认证方式
第三方接入推荐先用 API Key 换取短期 `access_token`，业务请求只携带短 token，减少 `client_secret` 暴露窗口。

**Token 交换：**
```bash
curl -X POST https://01pan.cn/api/openapi/token.php \
  -H "Content-Type: application/json" \
  -H "X-Client-Id: {client_id}" \
  -H "X-Client-Secret: {client_secret}" \
  -d '{"grant_type":"client_credentials","scope":"direct_links.read stats.read","expires_in":900}'
```

**业务请求：**
```
Authorization: Bearer {access_token}
```

`access_token` 默认 15 分钟过期，最长 1 小时。撤销当前 token：

```bash
curl -X DELETE https://01pan.cn/api/openapi/token.php \
  -H "Authorization: Bearer {access_token}"
```

兼容模式仍支持直接携带 API Key 调用业务接口。

**Header 方式：**
```
X-Client-Id: {client_id}
X-Client-Secret: {client_secret}
```

**HTTP Basic 方式：**
```
Authorization: Basic base64({client_id}:{client_secret})
```

站内用户会话调用仍兼容 `Authorization: Bearer {user_jwt}`。API Key 和 OpenAPI `access_token` 都会按 `rate_limit` 做每分钟限流，并写入 `api_logs`。

### 1.3 请求格式
- Content-Type: application/json
- 字符编码: UTF-8

### 1.4 响应格式
```json
{
    "success": true,
    "code": 0,
    "message": "操作成功",
    "data": { ... }
}
```

### 1.5 错误码说明
| 错误码 | 说明 |
|-------|------|
| 0 | 成功 |
| 401 | 未授权/Token无效 |
| 403 | 权限不足 |
| 404 | 资源不存在 |
| 429 | 请求频率超限 |
| 500 | 服务器错误 |

---

## 二、API Key 与权限

### 2.1 创建 API Key
在开发者中心创建 API Key 后会得到 `client_id` 和 `client_secret`。`client_secret` 只在创建时完整展示，请妥善保存；服务端只保存密钥哈希，无法再次取回明文。

### 2.2 重置 Client Secret

在开发者中心可对指定 API Key 重置 `client_secret`。重置后旧 Secret 立即失效，该 Key 已签发的短期 `access_token` 会被撤销；新 Secret 仍只展示一次。

### 2.3 换取短期 Token

`POST /token.php` 支持 `client_credentials`：

| 参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `grant_type` | string | 否 | 固定为 `client_credentials`，默认值 |
| `scope` | string/array | 否 | 请求的权限范围，必须是 API Key 权限子集 |
| `expires_in` | int | 否 | 有效期秒数，60-3600，默认 900 |

响应：

```json
{
  "success": true,
  "data": {
    "access_token": "oat_xxx",
    "token_type": "Bearer",
    "expires_in": 900,
    "expires_at": "2026-05-30 12:15:00",
    "scope": "direct_links.read stats.read"
  }
}
```

### 2.4 Scope 权限

OpenAPI 支持细粒度读写 scope：`{模块}.read` 允许查询，`{模块}.write` 允许创建、更新、删除和执行动作。兼容旧的粗粒度 scope，例如 `direct_links` 仍等价于 `direct_links.read + direct_links.write`。

| Scope | 说明 | 已接入入口 |
| --- | --- | --- |
| `files.read` / `files.write` | 文件列表/详情/下载链接/上传回调 | `/files.php` |
| `direct_links.read` / `direct_links.write` | 直链空间查询/管理 | `/direct-links.php` |
| `offline_tasks.read` / `offline_tasks.write` | 离线下载查询/创建取消 | `/offline-tasks.php` |
| `stats.read` | API 调用统计 | `/stats.php` |
| `imagebed.read` / `imagebed.write` | 图床查询/上传删除 | `/imagebed.php` |
| `documents.read` / `documents.write` | 文档查询/编辑分享删除 | `/documents.php` |
| `safe_box.read` / `safe_box.write` | 保险箱状态文件/初始化解锁移入移出 | `/safe-box.php` |
| `transcode.read` / `transcode.write` | 视频转码查询/创建删除 | `/transcode-tasks.php` |
| `*` | 全部权限 | 全部 OpenAPI |

API Key 缺少对应 scope 时返回 `403`；超过每分钟限流时返回 `429`。

`/documents.php` 会限制标题不超过 120 个字符、内容不超过 1MB；`html`/`markdown` 内容中的脚本标签、事件属性和 `javascript:` 链接会在入库前清理。

`/transcode-tasks.php` 只负责创建、查询和删除任务；实际转码由服务器 CLI 任务 `api/controllers/TranscodeWorker.php` 执行。worker 会读取后台 `transcode_config`，调用 FFmpeg 输出到 OSS/当前存储驱动，完成后回写 `status=completed`、`progress=100`、`output_path` 和 `output_file_id`。保险箱/隐藏/已删除文件不能创建转码任务。

---

## 三、文件操作

OpenAPI 文件入口为 `/files.php`，默认只返回普通网盘文件；保险箱/隐藏文件不会出现在列表、详情和下载链接接口中。

### 3.1 获取文件列表
```
GET /files.php
```

**请求参数:**
| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| folder_id | int | 否 | 文件夹ID，默认0(根目录) |
| page | int | 否 | 页码，默认1 |
| limit | int | 否 | 每页数量，默认20 |
| keyword | string | 否 | 文件名关键词 |

**响应示例:**
```json
{
    "success": true,
    "data": {
        "list": [
            {
                "id": 12345,
                "file_name": "文档.pdf",
                "file_hash": "abc123def456",
                "file_size": 1048576,
                "file_type": "pdf",
                "mime_type": "application/pdf",
                "folder_id": 0,
                "is_folder": 0,
                "created_at": "2026-01-13 10:00:00",
                "updated_at": "2026-01-13 10:00:00"
            }
        ],
        "total": 100,
        "page": 1,
        "limit": 20
    }
}
```

### 3.2 获取文件详情
```
GET /files.php?action=get&id=12345
```

响应字段与列表单项一致。

### 3.3 获取下载链接
```
GET /files.php?action=download&id=12345
GET /files.php?action=download&id=12345&mode=preview
```

下载链接为短期 OSS 签名地址，`preview` 模式不强制 attachment；该接口不会返回永久 OSS 地址。

**响应示例:**
```json
{
    "success": true,
    "data": {
        "download_url": "https://001pan.oss-cn-hangzhou.aliyuncs.com/users/10001/2026/06/file.pdf?...",
        "file_name": "文档.pdf",
        "file_size": 1048576,
        "mode": "download",
        "expires_in": 600
    }
}
```

### 3.4 上传回调入库
```
POST /files.php?action=upload-callback
```

该接口用于“客户端已通过浏览器直传/分片上传把对象写入 OSS 后”登记文件记录。`object_name` 必须位于 `users/{user_id}/` 前缀下，系统会校验对象大小、文件名、扩展名、空间配额和目标文件夹。

**请求参数:**
```json
{
    "file_name": "uploaded.zip",
    "object_name": "users/10001/2026/06/uploaded.zip",
    "file_size": 5242880,
    "file_hash": "e3b0c44298fc1c149afbf4c8996fb924",
    "folder_id": 0,
    "mime_type": "application/zip"
}
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "file_id": 12346,
        "file_name": "uploaded.zip",
        "file_size": 5242880,
        "folder_id": 0
    }
}
```

---

## 四、分享功能

### 4.1 创建分享
```
POST /shares
```

**请求参数:**
```json
{
    "file_id": 12345,
    "password": "1234",
    "expire_days": 7,
    "download_limit": 100,
    "price": 0
}
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "share_code": "abc123",
        "share_url": "https://001pan.com/s/abc123",
        "password": "1234",
        "expire_at": "2026-01-20 10:00:00"
    }
}
```

### 4.2 获取分享列表
```
GET /shares
```

### 4.3 取消分享
```
DELETE /shares/{share_code}
```

### 4.4 获取分享统计
```
GET /shares/{share_code}/stats
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "view_count": 1000,
        "download_count": 500,
        "save_count": 200
    }
}
```

---

## 五、直链功能

直链入口统一为 `/direct-links.php` 管理，用户侧访问格式为 `https://{直链入口域名}/d/{link_code}`。访问 `/d/{link_code}` 时系统先校验过期、次数、Referer/IP 策略、保险箱限制和流量，再 302 到短期 OSS/CDN 分发地址。生产 Nginx 需将 `/d/{code}` 重写到 `/d/index.php?code={code}`。

### 5.1 生成直链
```
POST /direct-links.php
```

**请求参数:**
```json
{
    "file_id": 12345,
    "expire_hours": 24
}
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "id": 88,
        "link_code": "abc123",
        "direct_url": "https://dl.example.com/d/abc123",
        "expire_at": "2026-01-14 10:00:00",
        "max_access": 0,
        "distribution_ttl": 3600
    }
}
```

### 5.2 查询直链列表
```
GET /direct-links.php
```

返回字段包含 `direct_url`、`access_count`、`bandwidth_used`、`expire_at`、`max_access` 和关联文件信息。

### 5.3 删除直链
```
DELETE /direct-links.php
```

```json
{
    "id": 88
}
```

### 5.4 分发与安全配置

后台直链配置写入 `system_config.directlink_config`，核心字段包括：

| 字段 | 说明 |
| --- | --- |
| `customDomain` | 直链入口域名，影响生成的 `/d/{link_code}` |
| `urlAuth` / `authKey` / `signExpire` | 直链入口 URL 鉴权 |
| `cdnSignEnabled` / `cdnSignKey` | CDN 分发 URL 鉴权 |
| `distributionTtl` | 302 到 OSS/CDN 分发地址的短期有效期 |
| `cacheTtl` | 建议 CDN 缓存 TTL |
| `refererCheck` / `refererWhitelist` / `refererBlacklist` | Referer 白黑名单 |
| `ipBlacklist` / `ipBlacklistData` | IP 黑名单 |
| `rangeOrigin` / `privateBucketOrigin` / `httpsEnabled` | CDN 回源能力配置记录 |
| `refreshPreheatEnabled` | 刷新/预热能力开关 |

---

## 六、流量管理

### 6.1 查询流量余额
```
GET /traffic/balance
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "daily_free_mb": 2048,
        "daily_used_mb": 500,
        "daily_remain_mb": 1548,
        "package_total_mb": 10240,
        "package_used_mb": 2000,
        "package_remain_mb": 8240,
        "total_available_mb": 9788
    }
}
```

### 6.2 获取流量包列表
```
GET /traffic/packages
```

### 6.3 购买流量包
```
POST /traffic/buy
```

**请求参数:**
```json
{
    "package_id": 2,
    "pay_type": "alipay"
}
```

### 6.4 流量使用记录
```
GET /traffic/logs
```

---

## 七、图床功能

图床入口为 `/imagebed.php`。新上传图片默认写入当前存储驱动；当存储为 OSS 并配置 CDN 域名时，短链 `/i/{code}` 先统计访问次数，再 302 到 OSS/CDN 分发地址。历史本地图片仍兼容 `/uploads/imagebed/` 输出。生产 Nginx 需将 `/i/{code}` 重写到 `/i/index.php?code={code}`。

### 7.1 上传图片
```
POST /imagebed.php?action=upload
Content-Type: multipart/form-data
```

字段名为 `image`，仅允许真实 JPG/PNG/GIF/WEBP 图片，且扩展名必须与内容 MIME 匹配。

**响应示例:**
```json
{
    "success": true,
    "data": {
        "id": 12,
        "url": "https://01pan.cn/i/abc123def456",
        "origin_url": "https://oss.example.com/imagebed/10001/2026/06/abc123.png",
        "markdown": "![image.png](https://01pan.cn/i/abc123def456)"
    }
}
```

### 7.2 图片列表与统计
```
GET /imagebed.php
GET /imagebed.php?action=stats
```

### 7.3 删除图片
```
DELETE /imagebed.php
```

```json
{
    "id": 12
}
```

---

## 八、用户信息

### 8.1 获取用户信息
```
GET /user/info
```

**响应示例:**
```json
{
    "success": true,
    "data": {
        "id": 10001,
        "username": "user123",
        "email": "user@example.com",
        "vip_level": 1,
        "vip_expire_at": "2026-12-31 23:59:59",
        "storage_used": 5368709120,
        "storage_quota": 6597069766656,
        "created_at": "2025-01-01 00:00:00"
    }
}
```

### 8.2 获取存储统计
```
GET /user/storage
```

---

## 九、Webhook回调

### 9.1 配置Webhook
```
POST /webhooks
```

**请求参数:**
```json
{
    "url": "https://your-server.com/webhook",
    "events": ["file.uploaded", "file.deleted", "share.created"],
    "secret": "your_webhook_secret"
}
```

### 9.2 事件类型
| 事件 | 说明 |
|-----|------|
| file.uploaded | 文件上传完成 |
| file.deleted | 文件被删除 |
| share.created | 分享创建 |
| share.accessed | 分享被访问 |
| order.paid | 订单支付成功 |

### 9.3 回调数据格式
```json
{
    "event": "file.uploaded",
    "timestamp": 1736755200,
    "data": {
        "file_id": 12345,
        "name": "uploaded.zip",
        "size": 1048576
    },
    "signature": "sha256=abc123..."
}
```

---

## 十、SDK下载

### 10.1 官方SDK
- PHP SDK: `composer require 001pan/sdk`
- Python SDK: `pip install 001pan-sdk`
- Node.js SDK: `npm install @001pan/sdk`
- Go SDK: `go get github.com/001pan/sdk-go`

### 10.2 SDK使用示例

**PHP:**
```php
<?php
use Pan001\Client;

$client = new Client('your_client_id', 'your_client_secret');

// 获取文件列表
$files = $client->files->list(['parent_id' => 0]);

// 上传文件
$result = $client->files->upload('/path/to/file.zip');

// 创建分享
$share = $client->shares->create([
    'file_id' => 12345,
    'expire_days' => 7
]);
```

**Python:**
```python
from pan001 import Client

client = Client('your_client_id', 'your_client_secret')

# 获取文件列表
files = client.files.list(parent_id=0)

# 上传文件
result = client.files.upload('/path/to/file.zip')

# 创建分享
share = client.shares.create(file_id=12345, expire_days=7)
```

**Node.js:**
```javascript
const { Client } = require('@001pan/sdk');

const client = new Client('your_client_id', 'your_client_secret');

// 获取文件列表
const files = await client.files.list({ parentId: 0 });

// 上传文件
const result = await client.files.upload('/path/to/file.zip');

// 创建分享
const share = await client.shares.create({ fileId: 12345, expireDays: 7 });
```

---

## 十、频率限制

| 接口类型 | 普通用户 | VIP用户 | SVIP用户 |
|---------|---------|--------|---------|
| 文件列表 | 60次/分钟 | 120次/分钟 | 300次/分钟 |
| 文件上传 | 10次/分钟 | 30次/分钟 | 100次/分钟 |
| 文件下载 | 30次/分钟 | 60次/分钟 | 200次/分钟 |
| 分享操作 | 20次/分钟 | 60次/分钟 | 200次/分钟 |
| 直链生成 | 10次/分钟 | 30次/分钟 | 100次/分钟 |

超出限制返回 HTTP 429 状态码。

---

## 十一、更新日志

### v1.0.0 (2026-01-13)
- 初始版本发布
- 支持文件基础操作
- 支持分享功能
- 支持流量管理

---

*文档版本: v1.0.0*
*更新时间: 2026-01-13*
