Config.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use Illuminate\Http\JsonResponse;
  4. use App\Constants\HttpStatus;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\Config as ConfigModel;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Validation\ValidationException;
  10. use Exception;
  11. use Telegram\Bot\Api;
  12. use Telegram\Bot\Exceptions\TelegramSDKException;
  13. use Telegram\Bot\FileUpload\InputFile;
  14. use App\Services\ConfigService;
  15. use App\Services\UsdtRechargeConfigService;
  16. class Config extends Controller
  17. {
  18. public function usdt(UsdtRechargeConfigService $service): JsonResponse
  19. {
  20. return $this->success($service->get())->header('Cache-Control', 'no-store');
  21. }
  22. public function saveUsdt(UsdtRechargeConfigService $service): JsonResponse
  23. {
  24. try {
  25. return $this->success($service->save(request()->all()))->header('Cache-Control', 'no-store');
  26. } catch (ValidationException $e) {
  27. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  28. }
  29. }
  30. /** 设置配置
  31. */
  32. public function setField()
  33. {
  34. try {
  35. $params = request()->validate([
  36. 'field' => ['required', 'string', 'max:255'],
  37. 'val' => ['nullable'],
  38. 'remark' => ['nullable'],
  39. ]);
  40. $val = $params['val'] ?? '';
  41. if ($params['field'] === 'sport_list') $val = self::normalizeSportList($val);
  42. $update_data=[
  43. 'val' => $val,
  44. ];
  45. if (isset($params['remark'])) {
  46. $update_data['remark'] = $params['remark'];
  47. }
  48. ConfigModel::updateOrCreate(['field' => $params['field']], $update_data);
  49. } catch (ValidationException $e) {
  50. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  51. } catch (Exception $e) {
  52. return $this->error(intval($e->getCode()));
  53. }
  54. return $this->success();
  55. }
  56. /** Sport codes become maintenance scopes (self:sport:<code>), so they must be stable and unique. */
  57. private static function normalizeSportList($val): string
  58. {
  59. $list = is_string($val) ? json_decode($val, true) : $val;
  60. if (!is_array($list) || !array_is_list($list)) throw ValidationException::withMessages(['val' => '体育列表格式错误']);
  61. $codes = [];
  62. foreach ($list as $item) {
  63. $code = is_array($item) ? strtolower(trim((string) ($item['code'] ?? ''))) : '';
  64. if (!preg_match('/^[a-z0-9]{1,32}$/', $code)) throw ValidationException::withMessages(['val' => '体育代码只能是1-32位小写字母或数字']);
  65. if (isset($codes[$code])) throw ValidationException::withMessages(['val' => "体育代码 {$code} 重复"]);
  66. if (trim((string) ($item['name'] ?? '')) === '') throw ValidationException::withMessages(['val' => '体育名称不能为空']);
  67. $codes[$code] = true;
  68. }
  69. return json_encode($list, JSON_UNESCAPED_UNICODE);
  70. }
  71. /**
  72. * @api {post} /admin/config/pc28Switch 游戏切换(0:pc28 1:急速28)
  73. * @apiGroup 配置
  74. * @apiUse result
  75. * @apiUse header
  76. * @apiVersion 1.0.0
  77. *
  78. * @apiParam {int=0,1} val (0:pc28 1:极速28)
  79. */
  80. public function pc28Switch()
  81. {
  82. try {
  83. $params = request()->validate([
  84. 'val' => ['required', 'integer', 'min:0', 'in:0,1']
  85. ]);
  86. ConfigModel::updateOrCreate(['field' => 'pc28_switch'], ['val' => $params['val']]);
  87. Cache::put('pc28_switch', $params['val']);
  88. } catch (ValidationException $e) {
  89. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  90. } catch (Exception $e) {
  91. return $this->error(intval($e->getCode()));
  92. }
  93. return $this->success();
  94. }
  95. /**
  96. * @api {get} /admin/config/pcConfig 极速PC28相关配置
  97. * @apiGroup 配置
  98. * @apiUse result
  99. * @apiUse header
  100. * @apiVersion 1.0.0
  101. *
  102. * @apiParam {int} [page=1]
  103. * @apiParam {int} [limit=15]
  104. */
  105. public function pcConfig(): JsonResponse
  106. {
  107. try {
  108. $search['group_id'] = 4;
  109. $result = ConfigService::paginate($search);
  110. foreach ($result['data'] as $item) {
  111. if ($item['field'] == 'pc28_switch') {
  112. $item['val'] = Cache::get('pc28_switch', $item['val']);
  113. }
  114. }
  115. } catch (ValidationException $e) {
  116. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  117. } catch
  118. (Exception $e) {
  119. return $this->error(intval($e->getCode()));
  120. }
  121. return $this->success($result);
  122. }
  123. /**
  124. * @api {get} /admin/config/gameList 彩票配置
  125. */
  126. public function gameList(): JsonResponse
  127. {
  128. return $this->sortedList('game_list');
  129. }
  130. /**
  131. * @api {get} /admin/config/sportList F1体育配置(与 gameList 相同,用 setField 的 sport_list 保存)
  132. */
  133. public function sportList(): JsonResponse
  134. {
  135. return $this->sortedList('sport_list');
  136. }
  137. private function sortedList(string $field): JsonResponse
  138. {
  139. try {
  140. $data = ConfigService::sortedList($field);
  141. } catch (Exception $e) {
  142. return $this->error(intval($e->getCode()));
  143. }
  144. return $this->success($data);
  145. }
  146. /**
  147. * 分页数据
  148. *
  149. */
  150. function index()
  151. {
  152. try {
  153. request()->validate([
  154. 'field' => ['nullable', 'string'],
  155. 'id' => ['nullable', 'string'],
  156. ]);
  157. $search = request()->all();
  158. $search['in_group_id'] = [1, 3];
  159. $result = ConfigService::paginate($search);
  160. } catch (ValidationException $e) {
  161. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  162. } catch (Exception $e) {
  163. return $this->error(intval($e->getCode()));
  164. }
  165. return $this->success($result);
  166. }
  167. /**
  168. * 修改|新增
  169. *
  170. */
  171. public
  172. function store()
  173. {
  174. try {
  175. $id = request()->post('id', '');
  176. if ($id) {
  177. $validator = [
  178. 'id' => ['required', 'integer', 'min:1'],
  179. 'val' => ['required', 'string'],
  180. 'remark' => 'required|nullable|string',
  181. ];
  182. } else {
  183. $validator = [
  184. 'field' => 'required|string|max:50|alpha_dash|unique:config,field',
  185. 'val' => 'required|string',
  186. 'remark' => 'required|nullable|string',
  187. ];
  188. $field = request()->input("field", 'aaa');
  189. switch ($field) {
  190. case 'group_language':
  191. $validator['val'] = ['required', 'string', 'in:zh,vi,en'];
  192. break;
  193. case 'pc28_switch':
  194. $validator['val'] = ['required', 'integer', 'in:0,1'];
  195. break;
  196. case 'pc28_time':
  197. //格式如:09:00-21:00
  198. $validator['val'] = ['nullable', 'string', 'regex:/^\d{2}:\d{2}-\d{2}:\d{2}$/i'];
  199. break;
  200. }
  201. }
  202. $params = request()->validate($validator);
  203. if (!isset($params['id'])) $params['group_id'] = 3;
  204. $ret = ConfigService::submit($params);
  205. if ($ret['code'] == ConfigService::NOT) {
  206. throw new Exception(HttpStatus::CUSTOM_ERROR, $ret['code']);
  207. }
  208. } catch (ValidationException $e) {
  209. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  210. } catch (Exception $e) {
  211. return $this->error(intval($e->getCode()));
  212. }
  213. return $this->success([], $ret['msg']);
  214. }
  215. /**
  216. * 删除
  217. */
  218. public
  219. function destroy()
  220. {
  221. $id = request()->post('id');
  222. // 示例:通过 ID 删除
  223. $info = ConfigService::findOne(['id' => $id]);
  224. if (!$info) {
  225. return $this->error(HttpStatus::CUSTOM_ERROR, '配置不存在');
  226. }
  227. if ($info->group_id !== 3) {
  228. return $this->error(HttpStatus::CUSTOM_ERROR, '禁止删除');
  229. }
  230. $info->delete();
  231. return $this->success([], '删除成功');
  232. }
  233. /**
  234. * @api {get} /admin/config/get 获取指定配置
  235. * @apiGroup 配置
  236. * @apiUse result
  237. * @apiUse header
  238. * @apiVersion 1.0.0
  239. *
  240. * @apiParam {string} field 配置项
  241. * - base_score 房间底分数组
  242. * - brokerage 抽佣比例
  243. * - service_charge 提现手续费
  244. * - service_account 客服账号
  245. * - receiving_address 手动收款 的地址
  246. * - receiving_type 收款方式 1-自动 2-手动
  247. * - channel_message 频道消息
  248. *
  249. * @apiSuccess (data) {Object} data
  250. * @apiSuccess (data) {int[]} [data.base_score] 房间底分数组
  251. * @apiSuccess (data) {float} [data.brokerage] 抽佣比例
  252. * @apiSuccess (data) {int} [data.service_charge] 提现手续费
  253. * @apiSuccess (data) {string} [data.service_account] 客服账号
  254. * @apiSuccess (data) {string} [data.receiving_address] 手动收款 的地址
  255. * @apiSuccess (data) {int} [data.receiving_type] 收款方式 1-自动 2-手动
  256. * @apiSuccess (data) {Object} [data.channel_message] 频道消息
  257. * @apiSuccess (data) {string} data.channel_message.chatId 频道账号或频道ID
  258. * @apiSuccess (data) {string} data.channel_message.image 要发送频道消息 的图片URL
  259. * @apiSuccess (data) {string} data.channel_message.text 要发送频道消息文 的本内容
  260. * @apiSuccess (data) {array} data.channel_message.button 要发送频道消息 的内联按钮,具体结构见下方
  261. * @apiSuccessExample {js} 内联按钮结构
  262. * //button 的数据格式如下
  263. * [
  264. * [ //第一行
  265. * { //第一行按钮 的第一个按钮
  266. * "text": "百度", //按钮文字
  267. * "url": "https://baidu.com" //按钮跳转的链接
  268. * },
  269. * { //第一行按钮 的第二个按钮
  270. * "text": "百度",
  271. * "url": "https://baidu.com"
  272. * }
  273. * //更多按钮...
  274. * ],
  275. * [ //第二行
  276. * {
  277. * "text": "百度",
  278. * "url": "https://baidu.com"
  279. * }
  280. * ]
  281. * //更多行...
  282. * ]
  283. *
  284. */
  285. public function get()
  286. {
  287. try {
  288. request()->validate([
  289. 'field' => ['required', 'string', 'min:1'],
  290. ]);
  291. $field = request()->input('field');
  292. $config = ConfigModel::where('field', $field)->first();
  293. $res = [];
  294. if ($config) {
  295. $val = $config->val;
  296. switch ($field) {
  297. case "channel_message":
  298. case "base_score":
  299. $val = json_decode($config->val);
  300. break;
  301. case "brokerage":
  302. case "service_charge":
  303. $val = floatval($config->val);
  304. break;
  305. }
  306. $res[$field] = $val;
  307. }
  308. } catch (ValidationException $e) {
  309. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  310. } catch (Exception $e) {
  311. return $this->error(intval($e->getCode()));
  312. }
  313. return $this->success($res);
  314. }
  315. /**
  316. * @api {get} /admin/config/getAll 获取所有配置
  317. * @apiGroup 配置
  318. * @apiUse result
  319. * @apiUse header
  320. * @apiVersion 1.0.0
  321. */
  322. public
  323. function getAll()
  324. {
  325. $list = ConfigModel::where('id', '>', 0)->get();
  326. $arr = [];
  327. foreach ($list as $item) {
  328. $val = $item['val'];
  329. switch ($item['field']) {
  330. case "channel_message":
  331. case "base_score":
  332. $val = json_decode($item['val'], true);
  333. break;
  334. case "brokerage":
  335. case "service_charge":
  336. $val = floatval($item['val']);
  337. break;
  338. }
  339. $arr[$item['field']] = $val;
  340. }
  341. return $this->success($arr);
  342. }
  343. /**
  344. * @api {post} /admin/config/sendChannelMessage 发送频道消息
  345. * @apiGroup 配置
  346. * @apiUse result
  347. * @apiUse header
  348. * @apiVersion 1.0.0
  349. * @apiDescription 该接口会保存配置,并发送频道消息; 创建频道之后需要将 bot 拉进频道内,然后将 bot 设置为管理员
  350. *
  351. *
  352. * @apiParam {String} chatId 频道的username - 创建频道时候填写的 username
  353. * @apiParam {String} type 发送的类型 - image:图片 - video:视频
  354. * @apiParam {String} image 要发送的图片
  355. * @apiParam {String} text 要发送的文字
  356. * @apiParam {Array} button 消息中的按钮 具体结构请看示例代码
  357. * @apiParam {String} video 视频
  358. * @apiParam {String} video_caption 视频文案
  359. * @apiParam {Boolean} [isSend=true] 是否发送
  360. * @apiParam {Boolean} [isTop=true] 是否置顶
  361. */
  362. public function sendChannelMessage()
  363. {
  364. set_time_limit(0);
  365. DB::beginTransaction();
  366. try {
  367. $validate = [
  368. 'chatId' => ['required', 'string', 'min:1'],
  369. 'type' => ['required', 'string', 'in:image,video,text'],
  370. 'text' => ['nullable', 'string'],
  371. 'isSend' => ['nullable', 'boolean'],
  372. 'isTop' => ['nullable', 'boolean'],
  373. 'button' => ['array'],
  374. 'button.*' => ['required', 'array'],
  375. 'button.*.*.text' => ['required', 'string'],
  376. 'button.*.*.url' => ['required', 'url'],
  377. ];
  378. $type = request()->input('type');
  379. if (in_array($type, ['image', 'video'])) $validate[$type] = ['required', 'url'];
  380. $params = request()->validate($validate);
  381. $params['image'] = request()->input('image', '');
  382. $params['video'] = request()->input('video', '');
  383. $isSend = request()->input('isSend', false);
  384. $isTop = request()->input('isTop', false);
  385. unset($params['isTop'], $params['isSend']);
  386. ConfigModel::where('field', 'channel_message')->update(['val' => json_encode($params)]);
  387. DB::commit();
  388. } catch (ValidationException $e) {
  389. DB::rollBack();
  390. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  391. } catch (Exception $e) {
  392. DB::rollBack();
  393. return $this->error(intval($e->getCode()), $e->getMessage());
  394. }
  395. if ($isSend) {
  396. try {
  397. $config = ConfigModel::where('field', 'channel_message')->first()->val;
  398. $config = json_decode($config, true);
  399. $telegram = new Api(config('services.telegram.token'));
  400. $msg = [];
  401. $msg['chat_id'] = "@{$config['chatId']}";
  402. $msg['protect_content'] = false;
  403. if (!empty($config['button'])) {
  404. $msg['reply_markup'] = json_encode(['inline_keyboard' => $config['button']]);
  405. }
  406. switch ($type) {
  407. case 'image':
  408. $msg['photo'] = InputFile::create($config['image']);
  409. $msg['caption'] = $config['text'];
  410. $response = $telegram->sendPhoto($msg);
  411. break;
  412. case 'video':
  413. $msg['video'] = InputFile::create($config['video']);
  414. $msg['caption'] = $config['text'];
  415. $response = $telegram->sendVideo($msg);
  416. break;
  417. case 'text':
  418. $msg['text'] = $config['text'];
  419. $response = $telegram->sendMessage($msg);
  420. break;
  421. default:
  422. throw new Exception("保存成功,发送失败", HttpStatus::CUSTOM_ERROR);
  423. }
  424. // 置顶消息
  425. if ($isTop) {
  426. $messageId = $response->get('message_id');
  427. $telegram->pinChatMessage(['chat_id' => "@{$config['chatId']}", 'message_id' => $messageId]);
  428. }
  429. } catch (TelegramSDKException $e) {
  430. return $this->error(HttpStatus::CUSTOM_ERROR, '保存成功,发送失败', $e->getMessage());
  431. } catch (Exception $e) {
  432. return $this->error($e->getCode(), '保存成功,发送失败');
  433. }
  434. }
  435. return $this->success();
  436. }
  437. /**
  438. * @api {post} /admin/config/set 修改配置
  439. * @apiGroup 配置
  440. * @apiUse result
  441. * @apiUse header
  442. * @apiVersion 1.0.0
  443. *
  444. * @apiParam {int[]} base_score 房间底分数组
  445. * @apiParam {string} brokerage 抽佣比例
  446. * @apiParam {string} service_charge 提现手续费
  447. * @apiParam {string} service_account 客服账号
  448. * @apiParam {string} receiving_address 充值收款地址
  449. * @apiParam {string} receiving_type 收款方式 1-自动 2-手动
  450. *
  451. */
  452. public function set()
  453. {
  454. DB::beginTransaction();
  455. try {
  456. request()->validate([
  457. 'base_score' => ['required', 'array', 'min:1', 'max:30'],
  458. 'base_score.*' => ['integer', 'min:1'],
  459. 'brokerage' => ['required', 'numeric', 'min:0.01', 'max:1', 'regex:/^\d*(\.\d{1,2})?$/'],
  460. 'service_charge' => ['required', 'integer', 'min:1'],
  461. 'service_account' => ['required', 'string', 'min:1'],
  462. 'receiving_address' => ['required', 'string', 'min:34'],
  463. 'receiving_type' => ['required', 'integer', 'in:1,2']
  464. ]);
  465. $baseScore = request()->input('base_score');
  466. sort($baseScore);
  467. $baseScore = array_unique($baseScore);
  468. ConfigModel::where('field', 'base_score')
  469. ->update(['val' => json_encode($baseScore)]);
  470. $val = request()->input('brokerage');
  471. ConfigModel::where('field', 'brokerage')
  472. ->update(['val' => $val]);
  473. $val = request()->input('service_charge');
  474. ConfigModel::where('field', 'service_charge')
  475. ->update(['val' => $val]);
  476. $val = request()->input('service_account');
  477. ConfigModel::where('field', 'service_account')
  478. ->update(['val' => $val]);
  479. $val = request()->input('receiving_address');
  480. ConfigModel::where('field', 'receiving_address')
  481. ->update(['val' => $val]);
  482. $val = request()->input('receiving_type');
  483. ConfigModel::where('field', 'receiving_type')
  484. ->update(['val' => $val]);
  485. DB::commit();
  486. } catch (ValidationException $e) {
  487. DB::rollBack();
  488. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  489. } catch (Exception $e) {
  490. DB::rollBack();
  491. return $this->error(intval($e->getCode()), $e->getMessage());
  492. }
  493. return $this->success();
  494. }
  495. }