Config.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. $list = ConfigModel::where('group_id', 5)->where('field', $field)->value('val');
  141. $list = $list ? json_decode($list, true) : [];
  142. $data = [];
  143. $i = count($list);
  144. foreach($list as $v) {
  145. $i--;
  146. $temp_key = ($v['sort'] ?? 0)*10+$i;
  147. $data[$temp_key] = $v;
  148. }
  149. krsort($data);
  150. $data = array_values($data);
  151. } catch (Exception $e) {
  152. return $this->error(intval($e->getCode()));
  153. }
  154. return $this->success($data);
  155. }
  156. /**
  157. * 分页数据
  158. *
  159. */
  160. function index()
  161. {
  162. try {
  163. request()->validate([
  164. 'field' => ['nullable', 'string'],
  165. 'id' => ['nullable', 'string'],
  166. ]);
  167. $search = request()->all();
  168. $search['in_group_id'] = [1, 3];
  169. $result = ConfigService::paginate($search);
  170. } catch (ValidationException $e) {
  171. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  172. } catch (Exception $e) {
  173. return $this->error(intval($e->getCode()));
  174. }
  175. return $this->success($result);
  176. }
  177. /**
  178. * 修改|新增
  179. *
  180. */
  181. public
  182. function store()
  183. {
  184. try {
  185. $id = request()->post('id', '');
  186. if ($id) {
  187. $validator = [
  188. 'id' => ['required', 'integer', 'min:1'],
  189. 'val' => ['required', 'string'],
  190. 'remark' => 'required|nullable|string',
  191. ];
  192. } else {
  193. $validator = [
  194. 'field' => 'required|string|max:50|alpha_dash|unique:config,field',
  195. 'val' => 'required|string',
  196. 'remark' => 'required|nullable|string',
  197. ];
  198. $field = request()->input("field", 'aaa');
  199. switch ($field) {
  200. case 'group_language':
  201. $validator['val'] = ['required', 'string', 'in:zh,vi,en'];
  202. break;
  203. case 'pc28_switch':
  204. $validator['val'] = ['required', 'integer', 'in:0,1'];
  205. break;
  206. case 'pc28_time':
  207. //格式如:09:00-21:00
  208. $validator['val'] = ['nullable', 'string', 'regex:/^\d{2}:\d{2}-\d{2}:\d{2}$/i'];
  209. break;
  210. }
  211. }
  212. $params = request()->validate($validator);
  213. if (!isset($params['id'])) $params['group_id'] = 3;
  214. $ret = ConfigService::submit($params);
  215. if ($ret['code'] == ConfigService::NOT) {
  216. throw new Exception(HttpStatus::CUSTOM_ERROR, $ret['code']);
  217. }
  218. } catch (ValidationException $e) {
  219. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  220. } catch (Exception $e) {
  221. return $this->error(intval($e->getCode()));
  222. }
  223. return $this->success([], $ret['msg']);
  224. }
  225. /**
  226. * 删除
  227. */
  228. public
  229. function destroy()
  230. {
  231. $id = request()->post('id');
  232. // 示例:通过 ID 删除
  233. $info = ConfigService::findOne(['id' => $id]);
  234. if (!$info) {
  235. return $this->error(HttpStatus::CUSTOM_ERROR, '配置不存在');
  236. }
  237. if ($info->group_id !== 3) {
  238. return $this->error(HttpStatus::CUSTOM_ERROR, '禁止删除');
  239. }
  240. $info->delete();
  241. return $this->success([], '删除成功');
  242. }
  243. /**
  244. * @api {get} /admin/config/get 获取指定配置
  245. * @apiGroup 配置
  246. * @apiUse result
  247. * @apiUse header
  248. * @apiVersion 1.0.0
  249. *
  250. * @apiParam {string} field 配置项
  251. * - base_score 房间底分数组
  252. * - brokerage 抽佣比例
  253. * - service_charge 提现手续费
  254. * - service_account 客服账号
  255. * - receiving_address 手动收款 的地址
  256. * - receiving_type 收款方式 1-自动 2-手动
  257. * - channel_message 频道消息
  258. *
  259. * @apiSuccess (data) {Object} data
  260. * @apiSuccess (data) {int[]} [data.base_score] 房间底分数组
  261. * @apiSuccess (data) {float} [data.brokerage] 抽佣比例
  262. * @apiSuccess (data) {int} [data.service_charge] 提现手续费
  263. * @apiSuccess (data) {string} [data.service_account] 客服账号
  264. * @apiSuccess (data) {string} [data.receiving_address] 手动收款 的地址
  265. * @apiSuccess (data) {int} [data.receiving_type] 收款方式 1-自动 2-手动
  266. * @apiSuccess (data) {Object} [data.channel_message] 频道消息
  267. * @apiSuccess (data) {string} data.channel_message.chatId 频道账号或频道ID
  268. * @apiSuccess (data) {string} data.channel_message.image 要发送频道消息 的图片URL
  269. * @apiSuccess (data) {string} data.channel_message.text 要发送频道消息文 的本内容
  270. * @apiSuccess (data) {array} data.channel_message.button 要发送频道消息 的内联按钮,具体结构见下方
  271. * @apiSuccessExample {js} 内联按钮结构
  272. * //button 的数据格式如下
  273. * [
  274. * [ //第一行
  275. * { //第一行按钮 的第一个按钮
  276. * "text": "百度", //按钮文字
  277. * "url": "https://baidu.com" //按钮跳转的链接
  278. * },
  279. * { //第一行按钮 的第二个按钮
  280. * "text": "百度",
  281. * "url": "https://baidu.com"
  282. * }
  283. * //更多按钮...
  284. * ],
  285. * [ //第二行
  286. * {
  287. * "text": "百度",
  288. * "url": "https://baidu.com"
  289. * }
  290. * ]
  291. * //更多行...
  292. * ]
  293. *
  294. */
  295. public function get()
  296. {
  297. try {
  298. request()->validate([
  299. 'field' => ['required', 'string', 'min:1'],
  300. ]);
  301. $field = request()->input('field');
  302. $config = ConfigModel::where('field', $field)->first();
  303. $res = [];
  304. if ($config) {
  305. $val = $config->val;
  306. switch ($field) {
  307. case "channel_message":
  308. case "base_score":
  309. $val = json_decode($config->val);
  310. break;
  311. case "brokerage":
  312. case "service_charge":
  313. $val = floatval($config->val);
  314. break;
  315. }
  316. $res[$field] = $val;
  317. }
  318. } catch (ValidationException $e) {
  319. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  320. } catch (Exception $e) {
  321. return $this->error(intval($e->getCode()));
  322. }
  323. return $this->success($res);
  324. }
  325. /**
  326. * @api {get} /admin/config/getAll 获取所有配置
  327. * @apiGroup 配置
  328. * @apiUse result
  329. * @apiUse header
  330. * @apiVersion 1.0.0
  331. */
  332. public
  333. function getAll()
  334. {
  335. $list = ConfigModel::where('id', '>', 0)->get();
  336. $arr = [];
  337. foreach ($list as $item) {
  338. $val = $item['val'];
  339. switch ($item['field']) {
  340. case "channel_message":
  341. case "base_score":
  342. $val = json_decode($item['val'], true);
  343. break;
  344. case "brokerage":
  345. case "service_charge":
  346. $val = floatval($item['val']);
  347. break;
  348. }
  349. $arr[$item['field']] = $val;
  350. }
  351. return $this->success($arr);
  352. }
  353. /**
  354. * @api {post} /admin/config/sendChannelMessage 发送频道消息
  355. * @apiGroup 配置
  356. * @apiUse result
  357. * @apiUse header
  358. * @apiVersion 1.0.0
  359. * @apiDescription 该接口会保存配置,并发送频道消息; 创建频道之后需要将 bot 拉进频道内,然后将 bot 设置为管理员
  360. *
  361. *
  362. * @apiParam {String} chatId 频道的username - 创建频道时候填写的 username
  363. * @apiParam {String} type 发送的类型 - image:图片 - video:视频
  364. * @apiParam {String} image 要发送的图片
  365. * @apiParam {String} text 要发送的文字
  366. * @apiParam {Array} button 消息中的按钮 具体结构请看示例代码
  367. * @apiParam {String} video 视频
  368. * @apiParam {String} video_caption 视频文案
  369. * @apiParam {Boolean} [isSend=true] 是否发送
  370. * @apiParam {Boolean} [isTop=true] 是否置顶
  371. */
  372. public function sendChannelMessage()
  373. {
  374. set_time_limit(0);
  375. DB::beginTransaction();
  376. try {
  377. $validate = [
  378. 'chatId' => ['required', 'string', 'min:1'],
  379. 'type' => ['required', 'string', 'in:image,video,text'],
  380. 'text' => ['nullable', 'string'],
  381. 'isSend' => ['nullable', 'boolean'],
  382. 'isTop' => ['nullable', 'boolean'],
  383. 'button' => ['array'],
  384. 'button.*' => ['required', 'array'],
  385. 'button.*.*.text' => ['required', 'string'],
  386. 'button.*.*.url' => ['required', 'url'],
  387. ];
  388. $type = request()->input('type');
  389. if (in_array($type, ['image', 'video'])) $validate[$type] = ['required', 'url'];
  390. $params = request()->validate($validate);
  391. $params['image'] = request()->input('image', '');
  392. $params['video'] = request()->input('video', '');
  393. $isSend = request()->input('isSend', false);
  394. $isTop = request()->input('isTop', false);
  395. unset($params['isTop'], $params['isSend']);
  396. ConfigModel::where('field', 'channel_message')->update(['val' => json_encode($params)]);
  397. DB::commit();
  398. } catch (ValidationException $e) {
  399. DB::rollBack();
  400. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  401. } catch (Exception $e) {
  402. DB::rollBack();
  403. return $this->error(intval($e->getCode()), $e->getMessage());
  404. }
  405. if ($isSend) {
  406. try {
  407. $config = ConfigModel::where('field', 'channel_message')->first()->val;
  408. $config = json_decode($config, true);
  409. $telegram = new Api(config('services.telegram.token'));
  410. $msg = [];
  411. $msg['chat_id'] = "@{$config['chatId']}";
  412. $msg['protect_content'] = false;
  413. if (!empty($config['button'])) {
  414. $msg['reply_markup'] = json_encode(['inline_keyboard' => $config['button']]);
  415. }
  416. switch ($type) {
  417. case 'image':
  418. $msg['photo'] = InputFile::create($config['image']);
  419. $msg['caption'] = $config['text'];
  420. $response = $telegram->sendPhoto($msg);
  421. break;
  422. case 'video':
  423. $msg['video'] = InputFile::create($config['video']);
  424. $msg['caption'] = $config['text'];
  425. $response = $telegram->sendVideo($msg);
  426. break;
  427. case 'text':
  428. $msg['text'] = $config['text'];
  429. $response = $telegram->sendMessage($msg);
  430. break;
  431. default:
  432. throw new Exception("保存成功,发送失败", HttpStatus::CUSTOM_ERROR);
  433. }
  434. // 置顶消息
  435. if ($isTop) {
  436. $messageId = $response->get('message_id');
  437. $telegram->pinChatMessage(['chat_id' => "@{$config['chatId']}", 'message_id' => $messageId]);
  438. }
  439. } catch (TelegramSDKException $e) {
  440. return $this->error(HttpStatus::CUSTOM_ERROR, '保存成功,发送失败', $e->getMessage());
  441. } catch (Exception $e) {
  442. return $this->error($e->getCode(), '保存成功,发送失败');
  443. }
  444. }
  445. return $this->success();
  446. }
  447. /**
  448. * @api {post} /admin/config/set 修改配置
  449. * @apiGroup 配置
  450. * @apiUse result
  451. * @apiUse header
  452. * @apiVersion 1.0.0
  453. *
  454. * @apiParam {int[]} base_score 房间底分数组
  455. * @apiParam {string} brokerage 抽佣比例
  456. * @apiParam {string} service_charge 提现手续费
  457. * @apiParam {string} service_account 客服账号
  458. * @apiParam {string} receiving_address 充值收款地址
  459. * @apiParam {string} receiving_type 收款方式 1-自动 2-手动
  460. *
  461. */
  462. public function set()
  463. {
  464. DB::beginTransaction();
  465. try {
  466. request()->validate([
  467. 'base_score' => ['required', 'array', 'min:1', 'max:30'],
  468. 'base_score.*' => ['integer', 'min:1'],
  469. 'brokerage' => ['required', 'numeric', 'min:0.01', 'max:1', 'regex:/^\d*(\.\d{1,2})?$/'],
  470. 'service_charge' => ['required', 'integer', 'min:1'],
  471. 'service_account' => ['required', 'string', 'min:1'],
  472. 'receiving_address' => ['required', 'string', 'min:34'],
  473. 'receiving_type' => ['required', 'integer', 'in:1,2']
  474. ]);
  475. $baseScore = request()->input('base_score');
  476. sort($baseScore);
  477. $baseScore = array_unique($baseScore);
  478. ConfigModel::where('field', 'base_score')
  479. ->update(['val' => json_encode($baseScore)]);
  480. $val = request()->input('brokerage');
  481. ConfigModel::where('field', 'brokerage')
  482. ->update(['val' => $val]);
  483. $val = request()->input('service_charge');
  484. ConfigModel::where('field', 'service_charge')
  485. ->update(['val' => $val]);
  486. $val = request()->input('service_account');
  487. ConfigModel::where('field', 'service_account')
  488. ->update(['val' => $val]);
  489. $val = request()->input('receiving_address');
  490. ConfigModel::where('field', 'receiving_address')
  491. ->update(['val' => $val]);
  492. $val = request()->input('receiving_type');
  493. ConfigModel::where('field', 'receiving_type')
  494. ->update(['val' => $val]);
  495. DB::commit();
  496. } catch (ValidationException $e) {
  497. DB::rollBack();
  498. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  499. } catch (Exception $e) {
  500. DB::rollBack();
  501. return $this->error(intval($e->getCode()), $e->getMessage());
  502. }
  503. return $this->success();
  504. }
  505. }