Mcp.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\outapi\controller;
  12. use think\facade\Db;
  13. use think\Request;
  14. /**
  15. * MCP (Model Context Protocol) 控制器
  16. * 提供 AI 助手调用 CRMEB API 的标准接口
  17. *
  18. * 认证方式:account + password
  19. * 通过请求头传递账号和密码进行认证
  20. */
  21. class Mcp extends AuthController
  22. {
  23. /**
  24. * 初始化
  25. * MCP 接口不走 Token 中间件,直接使用 appid + appsecret 认证
  26. */
  27. protected function initialize()
  28. {
  29. // 不调用父类 initialize,因为 MCP 不走 Token 中间件
  30. $this->authByAppSecret();
  31. }
  32. /**
  33. * 通过 appid + appsecret 认证
  34. * 参考 AuthTokenMiddleware 的验证流程
  35. */
  36. private function authByAppSecret()
  37. {
  38. $account = $this->request->header('account', '');
  39. $password = $this->request->header('password', '');
  40. if (empty($account) || empty($password)) {
  41. $this->authFail('认证失败:缺少 account 或 password');
  42. return;
  43. }
  44. try {
  45. // 查询账号信息
  46. $accountInfo = Db::name('out_account')
  47. ->where('appid', $account)
  48. ->where('is_del', 0)
  49. ->find();
  50. // 账号不存在
  51. if (!$accountInfo) {
  52. $this->authFail('账号不存在');
  53. return;
  54. }
  55. // 验证密码
  56. if (!password_verify($password, $accountInfo['appsecret'])) {
  57. $this->authFail('密码验证失败');
  58. return;
  59. }
  60. // 检查账号状态(status=0 或 status=2 表示禁用)
  61. if ($accountInfo['status'] == 0 || $accountInfo['status'] == 2) {
  62. $this->authFail('账号已被禁用');
  63. return;
  64. }
  65. // 认证成功,设置账号信息
  66. $this->outId = (int)$accountInfo['id'];
  67. $this->outInfo = $accountInfo;
  68. // 验证接口权限(参考 AuthTokenMiddleware)
  69. // $this->verifyAuth();
  70. } catch (\crmeb\exceptions\AuthException $e) {
  71. // AuthException 转换为友好错误
  72. $this->authFail('您暂时没有访问权限');
  73. } catch (\Exception $e) {
  74. // 不暴露具体错误信息
  75. $this->authFail('认证失败');
  76. }
  77. }
  78. /**
  79. * 验证接口权限
  80. * 参考 AuthTokenMiddleware 的 verifyAuth 逻辑
  81. * MCP 接口需要进行路由权限检查
  82. */
  83. private function verifyAuth()
  84. {
  85. try {
  86. // 注入 outId 和 outInfo 到 request(模拟中间件的行为)
  87. $outInfo = $this->outInfo;
  88. $this->request->macro('outId', function () use (&$outInfo) {
  89. return (int)$outInfo['id'];
  90. });
  91. $this->request->macro('outInfo', function () use (&$outInfo) {
  92. return $outInfo;
  93. });
  94. // 调用接口权限验证服务
  95. $outInterfaceServices = app()->make(\app\services\out\OutInterfaceServices::class);
  96. $outInterfaceServices->verifyAuth($this->request);
  97. } catch (\crmeb\exceptions\AuthException $e) {
  98. // 权限验证失败,抛出友好的错误信息
  99. throw new \crmeb\exceptions\AuthException(110000); // 无权限访问
  100. } catch (\Exception $e) {
  101. // 其他异常,统一返回无权限
  102. throw new \crmeb\exceptions\AuthException(110000);
  103. }
  104. }
  105. /**
  106. * 认证失败处理
  107. * 设置错误标识,在 index 方法中返回错误响应
  108. */
  109. private function authFail(string $message)
  110. {
  111. $this->outId = 0;
  112. $this->outInfo = ['error' => $message];
  113. }
  114. /**
  115. * 获取MCP工具定义列表
  116. * 定义所有可供AI助手调用的工具及其参数结构
  117. *
  118. * @return array 工具定义数组
  119. */
  120. private function getTools(): array
  121. {
  122. return [
  123. // 分类管理
  124. [
  125. 'name' => 'crmeb_category_list',
  126. 'description' => '获取商品分类列表,支持树形结构展示',
  127. 'inputSchema' => [
  128. 'type' => 'object',
  129. 'properties' => [
  130. 'page' => ['type' => 'number', 'description' => '页码(非树形模式时有效)'],
  131. 'limit' => ['type' => 'number', 'description' => '每页数量(非树形模式时有效)'],
  132. 'tree' => ['type' => 'boolean', 'description' => '是否返回树形结构,默认为true'],
  133. 'pid' => ['type' => 'number', 'description' => '父级ID,指定则只返回该父级下的分类'],
  134. ],
  135. ],
  136. ],
  137. [
  138. 'name' => 'crmeb_category_detail',
  139. 'description' => '获取分类详情',
  140. 'inputSchema' => [
  141. 'type' => 'object',
  142. 'properties' => [
  143. 'id' => ['type' => 'number', 'description' => '分类ID'],
  144. ],
  145. 'required' => ['id'],
  146. ],
  147. ],
  148. // 商品管理
  149. [
  150. 'name' => 'crmeb_product_list',
  151. 'description' => '获取商品列表',
  152. 'inputSchema' => [
  153. 'type' => 'object',
  154. 'properties' => [
  155. 'page' => ['type' => 'number', 'description' => '页码'],
  156. 'limit' => ['type' => 'number', 'description' => '每页数量'],
  157. 'cate_id' => ['type' => 'number', 'description' => '分类ID'],
  158. 'keyword' => ['type' => 'string', 'description' => '搜索关键词'],
  159. 'stock_min' => ['type' => 'number', 'description' => '最小库存'],
  160. 'stock_max' => ['type' => 'number', 'description' => '最大库存'],
  161. ],
  162. ],
  163. ],
  164. [
  165. 'name' => 'crmeb_product_detail',
  166. 'description' => '获取商品详情',
  167. 'inputSchema' => [
  168. 'type' => 'object',
  169. 'properties' => [
  170. 'id' => ['type' => 'number', 'description' => '商品ID'],
  171. ],
  172. 'required' => ['id'],
  173. ],
  174. ],
  175. // 订单管理
  176. [
  177. 'name' => 'crmeb_order_list',
  178. 'description' => '获取订单列表',
  179. 'inputSchema' => [
  180. 'type' => 'object',
  181. 'properties' => [
  182. 'page' => ['type' => 'number', 'description' => '页码'],
  183. 'limit' => ['type' => 'number', 'description' => '每页数量'],
  184. 'status' => ['type' => 'number', 'description' => '订单状态'],
  185. 'keyword' => ['type' => 'string', 'description' => '搜索关键词'],
  186. ],
  187. ],
  188. ],
  189. [
  190. 'name' => 'crmeb_order_detail',
  191. 'description' => '获取订单详情',
  192. 'inputSchema' => [
  193. 'type' => 'object',
  194. 'properties' => [
  195. 'order_id' => ['type' => 'string', 'description' => '订单号'],
  196. ],
  197. 'required' => ['order_id'],
  198. ],
  199. ],
  200. [
  201. 'name' => 'crmeb_order_express_list',
  202. 'description' => '获取物流公司列表',
  203. 'inputSchema' => [
  204. 'type' => 'object',
  205. 'properties' => new \stdClass(),
  206. ],
  207. ],
  208. // 售后管理
  209. [
  210. 'name' => 'crmeb_refund_list',
  211. 'description' => '获取售后订单列表',
  212. 'inputSchema' => [
  213. 'type' => 'object',
  214. 'properties' => [
  215. 'page' => ['type' => 'number', 'description' => '页码'],
  216. 'limit' => ['type' => 'number', 'description' => '每页数量'],
  217. ],
  218. ],
  219. ],
  220. [
  221. 'name' => 'crmeb_refund_detail',
  222. 'description' => '获取售后订单详情',
  223. 'inputSchema' => [
  224. 'type' => 'object',
  225. 'properties' => [
  226. 'order_id' => ['type' => 'string', 'description' => '售后订单号'],
  227. ],
  228. 'required' => ['order_id'],
  229. ],
  230. ],
  231. // 优惠券管理
  232. [
  233. 'name' => 'crmeb_coupon_list',
  234. 'description' => '获取优惠券列表',
  235. 'inputSchema' => [
  236. 'type' => 'object',
  237. 'properties' => [
  238. 'page' => ['type' => 'number', 'description' => '页码'],
  239. 'limit' => ['type' => 'number', 'description' => '每页数量'],
  240. ],
  241. ],
  242. ],
  243. // 用户管理
  244. [
  245. 'name' => 'crmeb_user_list',
  246. 'description' => '获取用户列表',
  247. 'inputSchema' => [
  248. 'type' => 'object',
  249. 'properties' => [
  250. 'page' => ['type' => 'number', 'description' => '页码'],
  251. 'limit' => ['type' => 'number', 'description' => '每页数量'],
  252. 'keyword' => ['type' => 'string', 'description' => '搜索关键词'],
  253. ],
  254. ],
  255. ],
  256. [
  257. 'name' => 'crmeb_user_detail',
  258. 'description' => '获取用户详情',
  259. 'inputSchema' => [
  260. 'type' => 'object',
  261. 'properties' => [
  262. 'uid' => ['type' => 'number', 'description' => '用户ID'],
  263. ],
  264. 'required' => ['uid'],
  265. ],
  266. ],
  267. ];
  268. }
  269. /**
  270. * 处理工具调用
  271. * 根据工具名称分发到对应的处理方法
  272. *
  273. * @param string $name 工具名称
  274. * @param array $args 工具参数
  275. * @return array 处理结果
  276. * @throws \Exception 未知工具或参数错误时抛出异常
  277. */
  278. private function handleToolCall(string $name, array $args = [])
  279. {
  280. switch ($name) {
  281. // 分类管理
  282. case 'crmeb_category_list':
  283. return $this->categoryList($args);
  284. case 'crmeb_category_detail':
  285. if (!isset($args['id']) || !is_numeric($args['id'])) {
  286. throw new \Exception('参数错误:缺少 id 或格式不正确');
  287. }
  288. return $this->categoryDetail((int)$args['id']);
  289. // 商品管理
  290. case 'crmeb_product_list':
  291. return $this->productList($args);
  292. case 'crmeb_product_detail':
  293. if (!isset($args['id']) || !is_numeric($args['id'])) {
  294. throw new \Exception('参数错误:缺少 id 或格式不正确');
  295. }
  296. return $this->productDetail((int)$args['id']);
  297. // 订单管理
  298. case 'crmeb_order_list':
  299. return $this->orderList($args);
  300. case 'crmeb_order_detail':
  301. if (empty($args['order_id'])) {
  302. throw new \Exception('参数错误:缺少 order_id');
  303. }
  304. return $this->orderDetail($args['order_id']);
  305. case 'crmeb_order_express_list':
  306. return $this->orderExpressList();
  307. // 售后管理
  308. case 'crmeb_refund_list':
  309. return $this->refundList($args);
  310. case 'crmeb_refund_detail':
  311. if (empty($args['order_id'])) {
  312. throw new \Exception('参数错误:缺少 order_id');
  313. }
  314. return $this->refundDetail($args['order_id']);
  315. // 优惠券管理
  316. case 'crmeb_coupon_list':
  317. return $this->couponList($args);
  318. // 用户管理
  319. case 'crmeb_user_list':
  320. return $this->userList($args);
  321. case 'crmeb_user_detail':
  322. if (!isset($args['uid']) || !is_numeric($args['uid'])) {
  323. throw new \Exception('参数错误:缺少 uid 或格式不正确');
  324. }
  325. return $this->userDetail((int)$args['uid']);
  326. default:
  327. throw new \Exception("未知工具: {$name}");
  328. }
  329. }
  330. // ==================== 分类管理 ====================
  331. /**
  332. * 获取商品分类列表
  333. *
  334. * @param array $args 查询参数
  335. * - page: 页码,默认1(非树形模式时有效)
  336. * - limit: 每页数量,默认10,最大100(非树形模式时有效)
  337. * - tree: 是否返回树形结构,默认false
  338. * - pid: 父级ID,指定则只返回该父级下的分类
  339. * @return array 分类列表和总数
  340. */
  341. private function categoryList(array $args): array
  342. {
  343. $page = max(1, (int)($args['page'] ?? 1));
  344. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  345. $isTree = $args['tree'] ?? true;
  346. $pid = $args['pid'] ?? null;
  347. // 构建基础查询
  348. $query = Db::name('store_category')->where('is_show', 1);
  349. // 如果指定了父级ID
  350. if ($pid !== null) {
  351. $query = $query->where('pid', $pid);
  352. }
  353. // 树形模式:获取所有分类并构建树
  354. if ($isTree) {
  355. $allList = Db::name('store_category')
  356. ->where('is_show', 1)
  357. ->order('sort desc, id desc')
  358. ->select()
  359. ->toArray();
  360. // 如果有指定pid,从该节点开始构建树
  361. if ($pid !== null) {
  362. $tree = $this->buildCategoryTree($allList, $pid);
  363. return ['list' => $tree, 'count' => count($tree)];
  364. }
  365. // 否则构建完整树(从根节点pid=0开始)
  366. $tree = $this->buildCategoryTree($allList, 0);
  367. return ['list' => $tree, 'count' => count($tree)];
  368. }
  369. // 普通列表模式
  370. $list = $query
  371. ->order('sort desc, id desc')
  372. ->page($page, $limit)
  373. ->select()
  374. ->toArray();
  375. $count = $query->count();
  376. return ['list' => $list, 'count' => $count];
  377. }
  378. /**
  379. * 构建分类树形结构
  380. *
  381. * @param array $list 所有分类数据
  382. * @param int $pid 父级ID
  383. * @return array 树形结构
  384. */
  385. private function buildCategoryTree(array $list, int $pid): array
  386. {
  387. $tree = [];
  388. foreach ($list as $item) {
  389. if ($item['pid'] == $pid) {
  390. $children = $this->buildCategoryTree($list, $item['id']);
  391. if (!empty($children)) {
  392. $item['children'] = $children;
  393. }
  394. $tree[] = $item;
  395. }
  396. }
  397. return $tree;
  398. }
  399. /**
  400. * 获取分类详情
  401. *
  402. * @param int $id 分类ID
  403. * @return array 分类详细信息
  404. * @throws \Exception 分类不存在时抛出异常
  405. */
  406. private function categoryDetail(int $id): array
  407. {
  408. $info = Db::name('store_category')->where('id', $id)->find();
  409. if (!$info) {
  410. throw new \Exception('分类不存在');
  411. }
  412. return $info;
  413. }
  414. // ==================== 商品管理 ====================
  415. /**
  416. * 获取商品列表
  417. * 支持按分类、关键词、库存范围筛选
  418. *
  419. * @param array $args 查询参数
  420. * - page: 页码,默认1
  421. * - limit: 每页数量,默认10,最大100
  422. * - cate_id: 分类ID(可选)
  423. * - keyword: 搜索关键词(可选)
  424. * - stock_min: 最小库存(可选)
  425. * - stock_max: 最大库存(可选)
  426. * @return array 商品列表和总数
  427. */
  428. private function productList(array $args): array
  429. {
  430. $page = max(1, (int)($args['page'] ?? 1));
  431. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  432. $where = [['is_show', '=', 1]];
  433. // 分类筛选:通过关联表查询
  434. if (!empty($args['cate_id'])) {
  435. $cateId = (int)$args['cate_id'];
  436. // 验证分类是否存在
  437. $categoryExists = Db::name('store_category')->where('id', $cateId)->where('is_show', 1)->count();
  438. if (!$categoryExists) {
  439. throw new \Exception('分类不存在');
  440. }
  441. // 通过关联表查询商品ID
  442. $productIds = Db::name('store_product_cate')
  443. ->where('cate_id', $cateId)
  444. ->column('product_id');
  445. if (empty($productIds)) {
  446. return ['list' => [], 'count' => 0];
  447. }
  448. $where[] = ['id', 'in', $productIds];
  449. }
  450. // 关键词搜索:转义通配符防止注入
  451. if (!empty($args['keyword'])) {
  452. $keyword = addcslashes($args['keyword'], '%_');
  453. $where[] = ['store_name', 'like', '%' . $keyword . '%'];
  454. }
  455. if (isset($args['stock_min'])) {
  456. $where[] = ['stock', '>=', (int)$args['stock_min']];
  457. }
  458. if (isset($args['stock_max'])) {
  459. $where[] = ['stock', '<=', (int)$args['stock_max']];
  460. }
  461. $list = Db::name('store_product')
  462. ->where($where)
  463. ->field('id,store_name,cate_id,price,stock,image,sales,is_show')
  464. ->order('id desc')
  465. ->page($page, $limit)
  466. ->select()
  467. ->toArray();
  468. $count = Db::name('store_product')->where($where)->count();
  469. return ['list' => $list, 'count' => $count];
  470. }
  471. /**
  472. * 获取商品详情
  473. *
  474. * @param int $id 商品ID
  475. * @return array 商品详细信息(已过滤敏感字段)
  476. * @throws \Exception 商品不存在时抛出异常
  477. */
  478. private function productDetail(int $id): array
  479. {
  480. $info = Db::name('store_product')->where('id', $id)->find();
  481. if (!$info) {
  482. throw new \Exception('商品不存在');
  483. }
  484. // 过滤敏感字段,只返回必要信息
  485. return [
  486. 'id' => $info['id'],
  487. 'store_name' => $info['store_name'] ?? '',
  488. 'cate_id' => $info['cate_id'] ?? 0,
  489. 'price' => $info['price'] ?? 0,
  490. 'stock' => $info['stock'] ?? 0,
  491. 'image' => $info['image'] ?? '',
  492. 'slider_image' => $info['slider_image'] ?? '',
  493. 'sales' => $info['sales'] ?? 0,
  494. 'unit_name' => $info['unit_name'] ?? '',
  495. 'content' => $info['content'] ?? '',
  496. 'is_show' => $info['is_show'] ?? 1,
  497. ];
  498. }
  499. // ==================== 订单管理 ====================
  500. /**
  501. * 获取订单列表
  502. * 支持按状态和关键词筛选
  503. *
  504. * @param array $args 查询参数
  505. * - page: 页码,默认1
  506. * - limit: 每页数量,默认10,最大100
  507. * - status: 订单状态(可选)
  508. * - keyword: 搜索关键词,匹配订单号/姓名/手机号(可选)
  509. * @return array 订单列表和总数
  510. */
  511. private function orderList(array $args): array
  512. {
  513. $page = max(1, (int)($args['page'] ?? 1));
  514. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  515. $where = [['is_del', '=', 0]];
  516. if (isset($args['status'])) {
  517. $where[] = ['status', '=', (int)$args['status']];
  518. }
  519. // 关键词搜索:转义通配符防止注入
  520. if (!empty($args['keyword'])) {
  521. $keyword = addcslashes($args['keyword'], '%_');
  522. $where[] = ['order_id|real_name|user_phone', 'like', '%' . $keyword . '%'];
  523. }
  524. $list = Db::name('store_order')
  525. ->where($where)
  526. ->field('id,order_id,uid,total_price,pay_price,paid,status,delivery_type,add_time')
  527. ->order('id desc')
  528. ->page($page, $limit)
  529. ->select()
  530. ->toArray();
  531. $count = Db::name('store_order')->where($where)->count();
  532. return ['list' => $list, 'count' => $count];
  533. }
  534. /**
  535. * 获取订单详情
  536. *
  537. * @param string $orderId 订单号
  538. * @return array 订单详细信息(已过滤敏感字段)
  539. * @throws \Exception 订单不存在时抛出异常
  540. */
  541. private function orderDetail(string $orderId): array
  542. {
  543. $info = Db::name('store_order')->where('order_id', $orderId)->find();
  544. if (!$info) {
  545. throw new \Exception('订单不存在');
  546. }
  547. // 过滤敏感字段,只返回必要信息
  548. return [
  549. 'id' => $info['id'],
  550. 'order_id' => $info['order_id'],
  551. 'uid' => $info['uid'],
  552. 'real_name' => $info['real_name'] ?? '',
  553. 'user_phone' => $info['user_phone'] ?? '',
  554. 'user_address' => $info['user_address'] ?? '',
  555. 'total_price' => $info['total_price'] ?? 0,
  556. 'pay_price' => $info['pay_price'] ?? 0,
  557. 'pay_type' => $info['pay_type'] ?? '',
  558. 'paid' => $info['paid'] ?? 0,
  559. 'status' => $info['status'] ?? 0,
  560. 'delivery_type' => $info['delivery_type'] ?? '',
  561. 'delivery_name' => $info['delivery_name'] ?? '',
  562. 'delivery_id' => $info['delivery_id'] ?? '',
  563. 'refund_status' => $info['refund_status'] ?? 0,
  564. 'add_time' => $info['add_time'] ?? 0,
  565. ];
  566. }
  567. /**
  568. * 获取物流公司列表
  569. * 返回所有启用的快递公司信息
  570. *
  571. * @return array 物流公司列表
  572. */
  573. private function orderExpressList(): array
  574. {
  575. $list = Db::name('express')->where('is_show', 1)->field('id,name,code')->select()->toArray();
  576. return ['list' => $list];
  577. }
  578. // ==================== 售后管理 ====================
  579. /**
  580. * 获取售后订单列表
  581. * 返回所有有退款状态的订单
  582. *
  583. * @param array $args 查询参数
  584. * - page: 页码,默认1
  585. * - limit: 每页数量,默认10,最大100
  586. * @return array 售后订单列表和总数
  587. */
  588. private function refundList(array $args): array
  589. {
  590. $page = max(1, (int)($args['page'] ?? 1));
  591. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  592. $list = Db::name('store_order')
  593. ->where('refund_status', '>', 0)
  594. ->field('id,order_id,uid,total_price,pay_price,refund_status,refund_reason')
  595. ->order('id desc')
  596. ->page($page, $limit)
  597. ->select()
  598. ->toArray();
  599. $count = Db::name('store_order')->where('refund_status', '>', 0)->count();
  600. return ['list' => $list, 'count' => $count];
  601. }
  602. /**
  603. * 获取售后订单详情
  604. *
  605. * @param string $orderId 售后订单号
  606. * @return array 售后订单详细信息(已过滤敏感字段)
  607. * @throws \Exception 售后订单不存在时抛出异常
  608. */
  609. private function refundDetail(string $orderId): array
  610. {
  611. $info = Db::name('store_order')
  612. ->where('order_id', $orderId)
  613. ->where('refund_status', '>', 0)
  614. ->find();
  615. if (!$info) {
  616. throw new \Exception('售后订单不存在');
  617. }
  618. // 过滤敏感字段,只返回必要信息
  619. return [
  620. 'id' => $info['id'],
  621. 'order_id' => $info['order_id'],
  622. 'uid' => $info['uid'],
  623. 'total_price' => $info['total_price'] ?? 0,
  624. 'pay_price' => $info['pay_price'] ?? 0,
  625. 'refund_status' => $info['refund_status'] ?? 0,
  626. 'refund_reason' => $info['refund_reason'] ?? '',
  627. 'refund_price' => $info['refund_price'] ?? 0,
  628. 'refund_explain' => $info['refund_explain'] ?? '',
  629. 'refund_img' => $info['refund_img'] ?? '',
  630. 'add_time' => $info['add_time'] ?? 0,
  631. ];
  632. }
  633. // ==================== 优惠券管理 ====================
  634. /**
  635. * 获取优惠券列表
  636. *
  637. * @param array $args 查询参数
  638. * - page: 页码,默认1
  639. * - limit: 每页数量,默认10,最大100
  640. * @return array 优惠券列表和总数
  641. */
  642. private function couponList(array $args): array
  643. {
  644. $page = max(1, (int)($args['page'] ?? 1));
  645. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  646. $list = Db::name('store_coupon_issue')
  647. ->where('is_del', 0)
  648. ->field('id,coupon_title,coupon_price,use_min_price,start_time,end_time')
  649. ->order('id desc')
  650. ->page($page, $limit)
  651. ->select()
  652. ->toArray();
  653. $count = Db::name('store_coupon_issue')->where('is_del', 0)->count();
  654. return ['list' => $list, 'count' => $count];
  655. }
  656. // ==================== 用户管理 ====================
  657. /**
  658. * 获取用户列表
  659. * 支持按昵称或手机号搜索
  660. *
  661. * @param array $args 查询参数
  662. * - page: 页码,默认1
  663. * - limit: 每页数量,默认10,最大100
  664. * - keyword: 搜索关键词,匹配昵称/手机号(可选)
  665. * @return array 用户列表和总数
  666. */
  667. private function userList(array $args): array
  668. {
  669. $page = max(1, (int)($args['page'] ?? 1));
  670. $limit = min(100, max(1, (int)($args['limit'] ?? 10))); // 限制最大100
  671. $where = [];
  672. // 关键词搜索:转义通配符防止注入
  673. if (!empty($args['keyword'])) {
  674. $keyword = addcslashes($args['keyword'], '%_');
  675. $where[] = ['nickname|phone', 'like', '%' . $keyword . '%'];
  676. }
  677. $list = Db::name('user')
  678. ->where($where)
  679. ->field('uid,nickname,avatar,phone,balance,integral,add_time')
  680. ->order('uid desc')
  681. ->page($page, $limit)
  682. ->select()
  683. ->toArray();
  684. $count = Db::name('user')->where($where)->count();
  685. return ['list' => $list, 'count' => $count];
  686. }
  687. /**
  688. * 获取用户详情
  689. *
  690. * @param int $uid 用户ID
  691. * @return array 用户详细信息(已过滤敏感字段)
  692. * @throws \Exception 用户不存在时抛出异常
  693. */
  694. private function userDetail(int $uid): array
  695. {
  696. $info = Db::name('user')->where('uid', $uid)->find();
  697. if (!$info) {
  698. throw new \Exception('用户不存在');
  699. }
  700. // 过滤敏感字段,只返回必要信息
  701. return [
  702. 'uid' => $info['uid'],
  703. 'nickname' => $info['nickname'] ?? '',
  704. 'avatar' => $info['avatar'] ?? '',
  705. 'phone' => $info['phone'] ?? '',
  706. 'now_money' => $info['now_money'] ?? 0,
  707. 'integral' => $info['integral'] ?? 0,
  708. 'level' => $info['level'] ?? 0,
  709. 'add_time' => $info['add_time'] ?? 0,
  710. 'last_time' => $info['last_time'] ?? 0,
  711. ];
  712. }
  713. // ==================== MCP 接口 ====================
  714. /**
  715. * MCP 服务入口方法
  716. * 处理所有 MCP 协议请求,包括:
  717. * - initialize: 初始化连接,返回服务信息和能力
  718. * - tools/list: 获取可用工具列表
  719. * - tools/call: 调用指定工具执行操作
  720. *
  721. * @param Request $request HTTP请求对象
  722. * @return \think\response\Json JSON-RPC 2.0 格式响应
  723. */
  724. public function index(Request $request)
  725. {
  726. $input = file_get_contents('php://input');
  727. $data = json_decode($input, true);
  728. $id = $data['id'] ?? null;
  729. if (!$data) {
  730. return json(['jsonrpc' => '2.0', 'error' => ['code' => -32700, 'message' => 'Parse error'], 'id' => null]);
  731. }
  732. // 认证检查
  733. if (empty($this->outId)) {
  734. $errorMsg = $this->outInfo['error'] ?? '认证失败';
  735. return json([
  736. 'jsonrpc' => '2.0',
  737. 'id' => $id,
  738. 'error' => ['code' => -32600, 'message' => $errorMsg]
  739. ]);
  740. }
  741. $method = $data['method'] ?? '';
  742. $params = $data['params'] ?? [];
  743. try {
  744. switch ($method) {
  745. case 'initialize':
  746. return json([
  747. 'jsonrpc' => '2.0',
  748. 'id' => $id,
  749. 'result' => [
  750. 'protocolVersion' => '2024-11-05',
  751. 'capabilities' => ['tools' => new \stdClass()],
  752. 'serverInfo' => [
  753. 'name' => 'crmeb-mcp-server',
  754. 'version' => '1.0.0',
  755. ],
  756. ],
  757. ]);
  758. case 'tools/list':
  759. return json([
  760. 'jsonrpc' => '2.0',
  761. 'id' => $id,
  762. 'result' => ['tools' => $this->getTools()],
  763. ]);
  764. case 'tools/call':
  765. $toolName = $params['name'] ?? '';
  766. $toolArgs = $params['arguments'] ?? [];
  767. $result = $this->handleToolCall($toolName, $toolArgs);
  768. return json([
  769. 'jsonrpc' => '2.0',
  770. 'id' => $id,
  771. 'result' => [
  772. 'content' => [
  773. [
  774. 'type' => 'text',
  775. 'text' => json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
  776. ],
  777. ],
  778. ],
  779. ]);
  780. default:
  781. return json([
  782. 'jsonrpc' => '2.0',
  783. 'id' => $id,
  784. 'error' => ['code' => -32601, 'message' => "Method not found: {$method}"],
  785. ]);
  786. }
  787. } catch (\Exception $e) {
  788. // 生产环境返回通用错误信息,避免泄露内部细节
  789. $errorMessage = $e->getMessage();
  790. // 对于业务异常(如"商品不存在"),返回具体错误
  791. // 对于系统异常(如SQL错误),返回通用错误
  792. $safeErrors = ['商品不存在', '订单不存在', '售后订单不存在', '用户不存在', '分类不存在', '父分类不存在',
  793. '同级分类下已存在同名分类', '分类名称不能超过50个字符',
  794. '参数错误', '未知工具'];
  795. $isSafeError = false;
  796. foreach ($safeErrors as $safeError) {
  797. if (strpos($errorMessage, $safeError) !== false) {
  798. $isSafeError = true;
  799. break;
  800. }
  801. }
  802. return json([
  803. 'jsonrpc' => '2.0',
  804. 'id' => $id,
  805. 'error' => ['code' => -32603, 'message' => $isSafeError ? $errorMessage : '服务器内部错误'],
  806. ]);
  807. }
  808. }
  809. }