{
"code": 200, // 業務狀態碼
"msg": "success", // 人類可讀信息
"data": { ... }, // 業務數據
"timestamp": 1699999999,
"request_id": "req_abc123" // 鏈路追蹤ID
}
| 範圍 | 含義 | 示例 |
|---|---|---|
| 200 | 成功 | 200 |
| 4xx | 客戶端錯誤 | 400 參數錯誤, 401 未授權, 403 禁止, 404 不存在, 422 驗證失敗 |
| 5xx | 服務端錯誤 | 500 內部錯誤, 503 服務不可用 |
| -xxx | 業務自定義錯誤 | -201 缺少動作參數, -401 UID 為空, -402 用戶不存在 |
<?php
header('Content-Type: application/json; charset=utf-8');
// 1. 參數獲取與基礎驗證
$action = $_GET['a'] ?? '';
$uid = (int)($_GET['uid'] ?? 0);
if (!$action) {
exit(json_encode(['code' => -201, 'msg' => '缺少動作參數', 'data' => null]));
}
// 2. 路由分發
switch ($action) {
case 'get_user':
handleGetUser($uid);
break;
case 'get_games':
handleGetGames();
break;
case 'upload_avatar':
handleUploadAvatar();
break;
default:
exit(json_encode(['code' => -400, 'msg' => '未知接口', 'data' => null]));
}
function handleGetUser($uid) {
if ($uid <= 0) {
exit(json_encode(['code' => -401, 'msg' => 'UID無效', 'data' => null]));
}
// 模擬數據源(實際對接 DB/Redis/微服務)
$users = [
10001 => ['uid'=>10001, 'nickname'=>'Shine', 'vip'=>5, 'gold'=>1500],
10002 => ['uid'=>10002, 'nickname'=>'Elva', 'vip'=>50, 'gold'=>14320],
];
if (!isset($users[$uid])) {
exit(json_encode(['code' => -402, 'msg' => '用戶不存在', 'data' => null]));
}
exit(json_encode([
'code' => 200,
'msg' => 'success',
'data' => [
'userInfo' => $users[$uid],
'isLogin' => true,
'unread' => 4,
'untask' => 3,
]
]));
}
function handleGetGames() {
exit(json_encode(['code' => 200, 'msg' => '調用 get_games_result', 'data' => []]));
}
function handleUploadAvatar() {
exit(json_encode(['code' => 200, 'msg' => '調用 upload_avatars', 'data' => []]));
}
// 使用 respect/validation 或自建驗證器
$v = new Validator();
$v->rule('required', $uid, 'UID不能為空');
$v->rule('integer', $uid, 'UID必須為整數');
$v->rule('min', $uid, 1, 'UID必須大於0');
if (!$v->validate()) {
exit(json_encode(['code' => 422, 'msg' => '驗證失敗', 'errors' => $v->errors()]));
}
try {
// 業務邏輯
} catch (BusinessException $e) {
exit(json_encode(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => null]));
} catch (\Throwable $e) {
log_error($e);
exit(json_encode(['code' => 500, 'msg' => '服務器內部錯誤', 'data' => null]));
}
function verifySign($params, $secret) {
ksort($params);
$sign = $params['sign'];
unset($params['sign']);
$str = http_build_query($params) . $secret;
return hash_hmac('sha256', $str, $secret) === $sign;
}
// Redis 滑動窗口限流
$key = "ratelimit:api:{$uid}:{$action}";
$count = $redis->incr($key);
if ($count === 1) $redis->expire($key, 60);
if ($count > 100) exit(json_encode(['code' => 429, 'msg' => '請求過於頻繁']));
zircote/swagger-php 或框架內建工具優秀的 API 核心在於:統一格式、清晰錯誤碼、嚴格驗證、完整日誌、可觀測性。本示例展示了從入參驗證到業務分發、響應封裝的最小閉環,生產環境建議接入框架(Laravel/ThinkPHP6/Hyperf)享受路由、中間件、驗證器、限流、熔斷等開箱即用能力。