第 07 章 API 接口开发
7.1 api 应用结构
application/api/ 是独立的接口应用,与后台共享同一套模型:
application/api/ ├── controller/ │ ├── Common.php # 基类控制器 │ ├── User.php # 用户接口(登录/注册/资料) │ └── ... ├── library/ ├── model/ └── config.php # api 独立配置
访问入口:/api/user/login。
7.2 基类与统一返回
API 控制器继承 app\common\controller\Api,统一返回格式:
- snippet.json
{"code": 1, "msg": "成功", "time": "1690000000", "data": {}}
- snippet.php
$this->success('登录成功', $data); // code = 1 $this->error('账号或密码错误'); // code = 0
前端约定:code=1 成功,code=0 失败,code=-1 需要登录。
7.3 免登录与鉴权
- snippet.php
// 整个控制器免登录 protected $noNeedLogin = ['index']; // 仅特定方法免登录 protected $noNeedLogin = 'index';
非免登录接口会校验请求头中的 token,对应 app\api\library\Auth:
- snippet.php
// 登录成功后签发 token $auth = \app\api\library\Auth::instance(); $auth->direct($user_id); $token = $auth->getToken();
Token 存储在 fa_user_token,默认有效期可在配置中调整。
7.4 用户接口实战
以登录为例:
- snippet.php
public function login() { $account = $this->request->post('account'); $password = $this->request->post('password'); if (!$account || !$password) { $this->error('参数不能为空'); } $user = \app\common\model\User::where('username|email|mobile', $account)->find(); if (!$user || $user->password !== \app\api\library\Auth::instance()->getEncryptPassword($password, $user->salt)) { $this->error('账号或密码错误'); } \app\api\library\Auth::instance()->direct($user->id); $this->success('登录成功', ['userinfo' => \app\api\library\Auth::instance()->getUserinfo()]); }
7.5 分页列表接口
- snippet.php
public function lists() { $page = $this->request->get('page', 1); $list = \app\common\model\Article::where('status', 1) ->order('weigh desc,id desc') ->paginate(10, false, ['page' => $page]); $this->success('', $list); }
返回结构自动包含 total、per_page、current_page、data。
7.6 接口安全要点
| 风险 | 对策 |
| SQL 注入 | 使用模型/查询构造器,不拼接原生 SQL |
| XSS | 输出前过滤,富文本使用 HTMLPurifier |
| 越权 | 每个涉及用户资源的接口校验 user_id 归属 |
| 暴力破解 | 登录接口增加验证码与失败次数限制 |
| 敏感信息 | 返回前过滤 password、salt、token 字段 |
7.7 调试工具
- 后台「系统 → 日志管理」查看接口报错
config.php中app_debug = true时错误返回详细堆栈(生产必须关闭)- 使用 Postman / Apifox 管理接口集,token 放在 Header 或参数中
本章小结
API 应用复用同一套模型与 RBAC 之外的独立 Token 体系,配合统一返回格式可快速对接 H5、小程序与 App。最后一章讲解部署上线与性能安全。