API REST 认证 接口

API 概述

统一企业数字平台 API 接口概述,包括认证、请求格式、错误处理等

API 概述

统一企业数字平台提供完整的 RESTful API,支持所有平台功能的程序化访问。

基础信息

API 地址

环境地址
生产环境https://api.enterprise-platform.com/v1
测试环境https://api-test.enterprise-platform.com/v1
开发环境http://localhost:3000/v1

API 版本

当前版本:v1

API 版本通过 URL 路径指定,如 /v1/users。当发布不兼容的 API 变更时,会发布新版本。

认证方式

API Key 认证

适用于服务端调用:

curl -X GET "https://api.enterprise-platform.com/v1/users" \
  -H "Authorization: Bearer YOUR_API_KEY"

OAuth 2.0

适用于第三方应用集成:

┌─────────┐                              ┌─────────┐
│  应用   │                              │  平台   │
└────┬────┘                              └────┬────┘
     │  1. 重定向到授权页面                    │
     │ ─────────────────────────────────────> │
     │                                        │
     │  2. 用户登录并授权                      │
     │ <───────────────────────────────────── │
     │                                        │
     │  3. 返回授权码 (code)                   │
     │ <───────────────────────────────────── │
     │                                        │
     │  4. 用授权码换取 access_token           │
     │ ─────────────────────────────────────> │
     │                                        │
     │  5. 返回 access_token                  │
     │ <───────────────────────────────────── │
     │                                        │
     │  6. 使用 access_token 调用 API         │
     │ ─────────────────────────────────────> │

获取授权码

GET /oauth/authorize?
  response_type=code&
  client_id=YOUR_CLIENT_ID&
  redirect_uri=YOUR_REDIRECT_URI&
  scope=read write&
  state=RANDOM_STATE

获取访问令牌

curl -X POST "https://api.enterprise-platform.com/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET" \
  -d "redirect_uri=YOUR_REDIRECT_URI"

响应:

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4...",
  "scope": "read write"
}

刷新令牌

curl -X POST "https://api.enterprise-platform.com/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=YOUR_REFRESH_TOKEN" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

请求格式

请求头

头部必填说明
Authorization认证令牌,格式:Bearer {token}
Content-Type是*请求体格式,通常为 application/json
Accept响应格式,默认 application/json
X-Request-ID请求追踪 ID,用于问题排查
Accept-Language响应语言,如 zh-CNen-US

请求体

POST/PUT/PATCH 请求使用 JSON 格式:

curl -X POST "https://api.enterprise-platform.com/v1/customers" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "示例科技有限公司",
    "industry": "互联网",
    "contact": {
      "name": "张经理",
      "phone": "13800138000"
    }
  }'

查询参数

GET 请求支持以下通用参数:

参数类型说明示例
pagenumber页码,从 1 开始page=1
pageSizenumber每页数量,默认 20,最大 100pageSize=50
sortstring排序字段sort=createdAt
orderstring排序方向:asc/descorder=desc
fieldsstring返回字段,逗号分隔fields=id,name,status
searchstring搜索关键词search=科技

过滤参数

# 等于
GET /v1/customers?status=active

# 不等于
GET /v1/customers?status[ne]=inactive

# 大于/小于
GET /v1/customers?createdAt[gt]=2024-01-01
GET /v1/customers?amount[lte]=10000

# 包含
GET /v1/customers?industry[in]=互联网,金融

# 模糊匹配
GET /v1/customers?name[like]=科技

响应格式

成功响应

{
  "code": 0,
  "message": "success",
  "data": {
    "id": "cust_001",
    "name": "示例科技有限公司",
    "industry": "互联网",
    "createdAt": "2024-01-15T10:30:00Z"
  }
}

列表响应

{
  "code": 0,
  "message": "success",
  "data": {
    "items": [
      { "id": "cust_001", "name": "客户A" },
      { "id": "cust_002", "name": "客户B" }
    ],
    "pagination": {
      "page": 1,
      "pageSize": 20,
      "total": 100,
      "totalPages": 5
    }
  }
}

错误响应

{
  "code": 40001,
  "message": "参数验证失败",
  "errors": [
    {
      "field": "email",
      "message": "邮箱格式不正确"
    },
    {
      "field": "phone",
      "message": "手机号不能为空"
    }
  ],
  "requestId": "req_abc123"
}

错误码

HTTP 状态码

状态码说明
200成功
201创建成功
204删除成功(无返回内容)
400请求参数错误
401未认证
403无权限
404资源不存在
409资源冲突
422业务逻辑错误
429请求过于频繁
500服务器内部错误

业务错误码

错误码说明
40001参数验证失败
40002参数类型错误
40101Token 无效
40102Token 已过期
40301无操作权限
40302资源访问受限
40401资源不存在
40901数据已存在
42201业务规则校验失败

速率限制

API 请求受速率限制保护:

类型限制
标准 API1000 次/分钟
批量操作100 次/分钟
文件上传60 次/分钟

响应头包含限制信息:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1705312800

超出限制时返回 429 状态码:

{
  "code": 42901,
  "message": "请求过于频繁,请稍后重试",
  "retryAfter": 60
}

分页

偏移分页

适用于小数据量场景:

GET /v1/customers?page=2&pageSize=20

游标分页

适用于大数据量场景,性能更好:

# 首次请求
GET /v1/customers?limit=20

# 响应包含游标
{
  "data": { ... },
  "cursor": {
    "next": "eyJpZCI6MTAwfQ==",
    "hasMore": true
  }
}

# 下一页请求
GET /v1/customers?limit=20&cursor=eyJpZCI6MTAwfQ==

Webhook

配置 Webhook

curl -X POST "https://api.enterprise-platform.com/v1/webhooks" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhook",
    "events": ["customer.created", "order.paid"],
    "secret": "your_webhook_secret"
  }'

事件类型

事件说明
customer.created客户创建
customer.updated客户更新
order.created订单创建
order.paid订单支付
device.online设备上线
device.offline设备离线
device.alert设备告警

Webhook 签名验证

import crypto from 'crypto';

function verifyWebhook(payload: string, signature: string, secret: string): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

// 使用示例
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const isValid = verifyWebhook(JSON.stringify(req.body), signature, WEBHOOK_SECRET);
  
  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }
  
  // 处理事件
  const event = req.body;
  console.log('Received event:', event.type);
  
  res.status(200).send('OK');
});

SDK

JavaScript/TypeScript

npm install @enterprise-platform/sdk
import { Client } from '@enterprise-platform/sdk';

const client = new Client({
  apiKey: 'YOUR_API_KEY',
  baseUrl: 'https://api.enterprise-platform.com/v1'
});

// 获取客户列表
const customers = await client.customers.list({
  page: 1,
  pageSize: 20,
  status: 'active'
});

// 创建客户
const newCustomer = await client.customers.create({
  name: '新客户',
  industry: '互联网'
});

// IoT 设备控制
await client.iot.devices.sendCommand('device_001', {
  command: 'turnOn',
  params: { brightness: 80 }
});

Python

pip install enterprise-platform-sdk
from enterprise_platform import Client

client = Client(api_key='YOUR_API_KEY')

# 获取客户列表
customers = client.customers.list(page=1, page_size=20)

# 创建客户
new_customer = client.customers.create(
    name='新客户',
    industry='互联网'
)

# IoT 设备控制
client.iot.devices.send_command(
    device_id='device_001',
    command='turnOn',
    params={'brightness': 80}
)

下一步