多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 接口管理控制器(V4.0.0版本新增) 豆信4.0.0版本开始支持插件Api控制器,用于为小程序开发提供接口。 在插件的Controller目录下新增ApiController,继承Mp模块的ApiBase控制器,即可方便的实现小程序数据交互接口。 如在Demo插件的ApiController中定义了一个getDataList()接口,则可以通过路由: `/addon/Demo/api/getDataList/mpid/2` 进行请求操作。 >[info] 注意:接口请求必须带上mpid参数,用于标识请求对接的是哪个账号(小程序mpid或公众号mpid),否则接口请求将会被拒绝。 ApiBase控制器封装了以下方法用于快速的实现接口交互逻辑。 ``` checkLogin(); // 如果接口需要限制小程序端用户登录后方可调用,则在接口方法开始处调用此方法。 login(); // 小程序用户登录接口 isLogin(); // 用于检测小程序端用户是否已登录 updateProfile(); // 用于更新小程序用户资料 getSettings(); // 用于获取插件配置 response(); // 用户返回接口响应数据 responseOk(); // 请求成功响应,响应码为:0 responseFail(); // 请求失败响应,响应码为:1001 ``` 插件Api控制器继承ApiBase控制器后,可以有两种方式调用上述封装的接口,比如Demo插件需要获取配置信息时,可以通过下面两种方式请求接口: `/addon/Demo/api/getSettings/mpid/1` 或者 `/Mp/ApiBase/getSettings/mpid/1` 我们推荐使用第一种基于插件的Api调用方式。 下面是Demo插件的Api控制器完整示例: ``` <?php /** * Demo插件Api控制器 * @author 艾逗笔<http://idoubi.cc> */ namespace Addons\Demo\Controller; use Mp\Controller\ApiBaseController; class ApiController extends ApiBaseController { public $model; public function __construct() { parent::__construct(); $this->model = M('demo_diary'); } // 新增日记 public function addDiary() { $this->checkLogin(); // 检测用户是否登录 $post = I('post.'); if (empty($post['title']) || empty($post['content'])) { $this->response(1001, '提交数据不完整'); } $post['openid'] = $this->openid; $post['mpid'] = $this->mpid; $post['created_at'] = time(); $id = $this->model->add($post); if ($id) { $this->response(0, '提交反馈成功'); } else { $this->response(1001, '提交反馈失败'); } } // 获取日记列表 public function getDiaryList() { $this->checkLogin(); $data = $this->model->where([ 'mpid' => $this->mpid, 'openid' => $this->openid, 'status' => 1 ])->field('id,title,content,created_at')->order('created_at desc')->select(); foreach ($data as &$v) { $v['created_at_format'] = date('Y-m-d H:i:s', $v['created_at']); } $this->response(0, '获取成功', $data); } // 修改日记 public function editDiary() { $this->checkLogin(); $post = I('post.'); if (empty($post['id']) || empty($post['title']) || empty($post['content'])) { $this->response(1001, '提交数据不完整'); } $id = $post['id']; $data = $this->model->where([ 'mpid' => $this->mpid, 'openid' => $this->openid, 'status' => 1 ])->find($id); if (empty($data)) { $this->response(1001, '要修改的数据不存在'); } $res = $this->model->where([ 'id' => $id ])->save([ 'title' => $post['title'], 'content' => $post['content'], 'updated_at' => time() ]); if ($res === false) { $this->response(1001, '修改失败'); } $this->response(0, '修改成功'); } // 删除日记 public function deleteDiary() { $this->checkLogin(); $id = I('post.id'); $data = $this->model->where([ 'mpid' => $this->mpid, 'openid' => $this->openid, 'status' => 1 ])->find($id); if (empty($data)) { $this->response(1001, '要删除的数据不存在'); } // 软删除 $res = $this->model->where([ 'id' => $id ])->save([ 'status' => -1, 'deleted_at' => time() ]); if ($res === false) { $this->response(1001, '删除失败'); } $this->response(0, '删除成功'); } } ```