Wallet.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Recharge;
  6. use App\Services\BalanceLogService;
  7. use App\Services\ManualAuditService;
  8. use App\Services\WageringService;
  9. use App\Services\MenuService;
  10. use App\Services\RechargeService;
  11. use App\Services\TopUpService;
  12. use Exception;
  13. use Illuminate\Support\Facades\Cache;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Validation\ValidationException;
  16. use App\Models\Wallet as WalletModel;
  17. use App\Models\Withdraw;
  18. use App\Models\Config;
  19. use App\Models\PaymentOrder;
  20. use App\Models\Order;
  21. use App\Models\LhcOrder;
  22. use App\Models\Bank;
  23. use App\Models\Address;
  24. use App\Services\Payment\QianBaoService;
  25. class Wallet extends Controller
  26. {
  27. /**
  28. * 获取提现通道
  29. */
  30. public function withdrawChannel()
  31. {
  32. $list = QianBaoService::withdrawChannel();
  33. $data[] = ['label' => 'USDT', 'value' => 'USDT'];
  34. foreach ($list as $key => $item) {
  35. $data[] = ['label' => $item, 'value' => $key];
  36. }
  37. return $this->success($data);
  38. }
  39. //银行卡/支付宝列表
  40. public function bankList()
  41. {
  42. try {
  43. $params = request()->validate([
  44. 'channel' => 'nullable',
  45. 'member_id' => 'nullable',
  46. ]);
  47. $where = [];
  48. if (!empty($params['channel'])) {
  49. $where[] = ['channel', '=', $params['channel']];
  50. }
  51. if (!empty($params['member_id'])) {
  52. $where[] = ['member_id', '=', $params['member_id']];
  53. }
  54. $list = Bank::where($where)->get()->toArray();
  55. return $this->success([
  56. 'list' => $list,
  57. ]);
  58. } catch (\Exception $e) {
  59. return $this->error($e->getMessage());
  60. }
  61. }
  62. //地址列表
  63. public function address()
  64. {
  65. try {
  66. $params = request()->validate([
  67. 'member_id' => 'nullable',
  68. ]);
  69. $where = [];
  70. if (!empty($params['member_id'])) {
  71. $where[] = ['member_id', '=', $params['member_id']];
  72. }
  73. $list = Address::where($where)->get()->toArray();
  74. return $this->success([
  75. 'list' => $list,
  76. ]);
  77. } catch (\Exception $e) {
  78. return $this->error($e->getMessage());
  79. }
  80. }
  81. public function getChangeTypes()
  82. {
  83. return $this->success(BalanceLogService::$manualRecharge);
  84. }
  85. /**
  86. * @api {get} /admin/wallet/getPendingTasks 待处理任务
  87. * @apiDescription 后台每隔10秒,轮询请求这个接口获取待处理的任务数,如果有待处理的任务,则播放音乐
  88. * @apiGroup 充值管理
  89. * @apiUse result
  90. * @apiUse header
  91. * @apiVersion 1.0.0
  92. *
  93. * @apiSuccess (data) {Object} data
  94. * @apiSuccess (data) {int} data.recharge_task 待处理充值任务
  95. * @apiSuccess (data) {int} data.withdraw_task 待处理提现任务
  96. */
  97. function getPendingTasks()
  98. {
  99. $data = [
  100. 'recharge_task' => 0,
  101. 'withdraw_task' => 0,
  102. 'rmb_withdraw_task' => 0,
  103. ];
  104. if (MenuService::checkMenu(request()->user->id, 'withdraw/topUp')) {
  105. $data['recharge_task'] = \App\Support\MemberAudience::visibleMembers(Recharge::where('type', 2)->where('status', 0), 'member_id')->count();
  106. }
  107. if (MenuService::checkMenu(request()->user->id, 'listUSDT')) {
  108. $data['withdraw_task'] = \App\Support\MemberAudience::visibleMembers(Withdraw::where('status', 0), 'member_id')->count();
  109. }
  110. if (MenuService::checkMenu(request()->user->id, 'listRMB')) {
  111. $data['rmb_withdraw_task'] = \App\Support\MemberAudience::visibleMembers(PaymentOrder::where('type', 2)->where('status', 0), 'member_id')->count();
  112. }
  113. return $this->success($data);
  114. }
  115. //扣款
  116. public function debiting()
  117. {
  118. DB::beginTransaction();
  119. try {
  120. request()->validate([
  121. 'amount' => ['required', 'numeric', 'min:0.01'],
  122. 'member_id' => ['required', 'string', 'min:1'],
  123. 'remark' => ['required', 'string', 'min:1'],
  124. // 人工充值、“其他”按平台倍数扣除打码量;其余类型扣除 wager_amount;不传不调整打码量
  125. 'recharge_type' => ['nullable', 'string', 'in:' . implode(',', BalanceLogService::$manualRecharge)],
  126. 'wager_amount' => ['nullable', 'numeric', 'min:0'],
  127. ]);
  128. $memberId = request()->input('member_id');
  129. $amount = request()->input('amount');
  130. [$wagerDelta, $writeWager] = ManualAuditService::wagerDelta(true, (string)$amount, ManualAuditService::DEBIT_CHANGE_TYPE,
  131. request()->input('recharge_type'), request()->filled('wager_amount') ? (string)request()->input('wager_amount') : null);
  132. $amount = $amount * -1;
  133. $remark = request()->input('remark');
  134. $key = 'api_request_' . md5($memberId . json_encode([
  135. 'amount' => $amount,
  136. 'remark' => $remark,
  137. 'action' => "wallet/debiting"
  138. ]));
  139. if (Cache::has($key)) throw new Exception("请求太频繁,请稍后再试。", HttpStatus::CUSTOM_ERROR);
  140. Cache::put($key, true, 3);
  141. $wallet = WalletModel::where('member_id', $memberId)->lockForUpdate()->first();
  142. if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  143. $beforeBalance = (string)$wallet->available_balance;
  144. $availableBalance = bcadd($beforeBalance, $amount, 10);
  145. if ($availableBalance < 0) throw new Exception('可用余额不足', HttpStatus::CUSTOM_ERROR);
  146. $wallet->available_balance = $availableBalance;
  147. $wallet->save();
  148. $log = BalanceLogService::addLog($memberId, $amount, $beforeBalance, $availableBalance, "人工扣款", null, $remark);
  149. if ($writeWager) {
  150. WageringService::addRequirement($wallet, $wagerDelta, 'manual_debit', 'balance_log:' . $log->id, $remark, (int)request()->user->id);
  151. }
  152. DB::commit();
  153. } catch (ValidationException $e) {
  154. DB::rollBack();
  155. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  156. } catch (Exception $e) {
  157. DB::rollBack();
  158. return $this->error(intval($e->getCode()), $e->getMessage());
  159. }
  160. $availableBalance = floatval($availableBalance);
  161. // 去除多余0后,再用 sprintf 补足两位
  162. $availableBalance = sprintf('%.2f', $availableBalance);
  163. TopUpService::notifyTransferSuccess($memberId, "您的账户余额更新:" . ($amount > 0 ? '+' : '') . "{$amount} \n总余额为:{$availableBalance}");
  164. return $this->success();
  165. }
  166. //会员账号充值
  167. public function topUp()
  168. {
  169. DB::beginTransaction();
  170. try {
  171. $params = request()->validate([
  172. 'amount' => ['required', 'numeric', 'min:0.01'],
  173. 'member_id' => ['required', 'string', 'min:1'],
  174. 'remark' => ['required', 'string', 'min:1'],
  175. 'change_type' => ['required', 'string', 'in:' . implode(',', BalanceLogService::$manualRecharge)],
  176. 'wager_amount' => ['nullable', 'numeric', 'min:0'],
  177. 'wager_multiple' => ['nullable', 'regex:' . ManualAuditService::WAGER_MULTIPLE_PATTERN],
  178. ], ['wager_multiple.regex' => '打码量倍数必须为非负整数']);
  179. $memberId = request()->input('member_id');
  180. $amount = request()->input('amount');
  181. $remark = request()->input('remark');
  182. $changeType = request()->input('change_type');
  183. [$wagerDelta, $writeWager] = ManualAuditService::wagerDelta(false, (string)$amount, (string)$changeType, null,
  184. isset($params['wager_amount']) ? (string)$params['wager_amount'] : null,
  185. isset($params['wager_multiple']) ? (string)$params['wager_multiple'] : null);
  186. $key = 'api_request_' . md5($memberId . json_encode([
  187. 'amount' => $amount,
  188. 'remark' => $remark,
  189. 'action' => "wallet/topUp"
  190. ]));
  191. if (Cache::has($key)) throw new Exception("请求太频繁,请稍后再试。", HttpStatus::CUSTOM_ERROR);
  192. Cache::put($key, true, 3);
  193. $wallet = WalletModel::where('member_id', $memberId)->lockForUpdate()->first();
  194. if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  195. $beforeBalance = (string)$wallet->available_balance;
  196. $availableBalance = bcadd($beforeBalance, $amount, 10);
  197. // 先保存余额再写日志:充值钩子(首充奖励、即充即送、打码量)会重新锁定并更新钱包
  198. $wallet->available_balance = $availableBalance;
  199. $wallet->save();
  200. $log = BalanceLogService::addLog($memberId, $amount, $beforeBalance, $availableBalance, $changeType, null, $remark);
  201. if ($writeWager) {
  202. $wallet = WalletModel::where('member_id', $memberId)->lockForUpdate()->first();
  203. WageringService::addRequirement($wallet, $wagerDelta, 'manual_credit', 'balance_log:' . $log->id, $remark, (int)request()->user->id);
  204. }
  205. DB::commit();
  206. } catch (ValidationException $e) {
  207. DB::rollBack();
  208. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  209. } catch (Exception $e) {
  210. DB::rollBack();
  211. return $this->error(intval($e->getCode()), $e->getMessage());
  212. }
  213. $availableBalance = floatval($availableBalance);
  214. // 去除多余0后,再用 sprintf 补足两位
  215. $availableBalance = sprintf('%.2f', $availableBalance);
  216. TopUpService::notifyTransferSuccess($memberId, "您的账户余额更新:" . ($amount > 0 ? '+' : '') . "{$amount} \n总余额为:{$availableBalance}");
  217. return $this->success();
  218. }
  219. //订单充值
  220. public function orderTopUp()
  221. {
  222. DB::beginTransaction();
  223. try {
  224. request()->validate([
  225. 'amount' => ['required', 'numeric', 'min:0.01'],
  226. 'remark' => ['required', 'string', 'min:1'],
  227. 'order_type' => ['nullable'],
  228. 'order_id' => ['nullable'],
  229. ]);
  230. $order_type = request()->input('order_type');
  231. $order_id = request()->input('order_id');
  232. $amount = request()->input('amount');
  233. $remark = request()->input('remark');
  234. // 订单补偿单独记类型:不算充值(等级、首充、返现等),报表仍计入人工加款
  235. $changeType = "订单补偿";
  236. $key = 'api_request_' . md5($order_id . json_encode([
  237. 'amount' => $amount,
  238. 'remark' => $remark,
  239. 'action' => "wallet/orderTopUp"
  240. ]));
  241. if (Cache::has($key)) throw new Exception("请求太频繁,请稍后再试。", HttpStatus::CUSTOM_ERROR);
  242. Cache::put($key, true, 3);
  243. if ($order_type == 'sport') {
  244. $info = Order::where('id', $order_id)->first();
  245. } elseif ($order_type == 'lhc') {
  246. $info = LhcOrder::where('id', $order_id)->first();
  247. }
  248. if (!$info) {
  249. throw new \Exception('订单不存在');
  250. } else {
  251. $info->remark = $info->remark ? $info->remark. '|' . $remark : $remark;
  252. $info->save();
  253. }
  254. $memberId = $order_type == 'sport' ? $info->user_id : $info->member_id;
  255. $wallet = WalletModel::where('member_id', $memberId)->first();
  256. if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  257. $availableBalance = bcadd($wallet->available_balance, $amount, 10);
  258. BalanceLogService::addLog($memberId, $amount, $wallet->available_balance, $availableBalance, $changeType, null, $remark);
  259. $wallet->available_balance = $availableBalance;
  260. $wallet->save();
  261. DB::commit();
  262. } catch (ValidationException $e) {
  263. DB::rollBack();
  264. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  265. } catch (Exception $e) {
  266. DB::rollBack();
  267. return $this->error(intval($e->getCode()), $e->getMessage());
  268. }
  269. return $this->success();
  270. }
  271. //订单扣款
  272. public function orderDebiting()
  273. {
  274. DB::beginTransaction();
  275. try {
  276. request()->validate([
  277. 'amount' => ['required', 'numeric', 'min:0.01'],
  278. 'remark' => ['required', 'string', 'min:1'],
  279. 'order_type' => ['required'],
  280. 'order_id' => ['required'],
  281. ]);
  282. $order_type = request()->input('order_type');
  283. $order_id = request()->input('order_id');
  284. $amount = request()->input('amount');
  285. $amount = $amount * -1;
  286. $remark = request()->input('remark');
  287. $key = 'api_request_' . md5($order_id . json_encode([
  288. 'amount' => $amount,
  289. 'remark' => $remark,
  290. 'action' => "wallet/orderDebiting"
  291. ]));
  292. if (Cache::has($key)) throw new Exception("请求太频繁,请稍后再试。", HttpStatus::CUSTOM_ERROR);
  293. Cache::put($key, true, 3);
  294. if ($order_type == 'sport') {
  295. $info = Order::where('id', $order_id)->first();
  296. } elseif ($order_type == 'lhc') {
  297. $info = LhcOrder::where('id', $order_id)->first();
  298. }
  299. if (!$info) {
  300. throw new \Exception('订单不存在');
  301. } else {
  302. $info->remark = $info->remark ? $info->remark. '|' . $remark : $remark;
  303. $info->save();
  304. }
  305. $memberId = $order_type == 'sport' ? $info->user_id : $info->member_id;
  306. $wallet = WalletModel::where('member_id', $memberId)->first();
  307. if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  308. $availableBalance = bcadd($wallet->available_balance, $amount, 10);
  309. if ($availableBalance < 0) throw new Exception('可用余额不足', HttpStatus::CUSTOM_ERROR);
  310. BalanceLogService::addLog($memberId, $amount, $wallet->available_balance, $availableBalance, "人工扣款", null, $remark);
  311. $wallet->available_balance = $availableBalance;
  312. $wallet->save();
  313. DB::commit();
  314. } catch (ValidationException $e) {
  315. DB::rollBack();
  316. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  317. } catch (Exception $e) {
  318. DB::rollBack();
  319. return $this->error(intval($e->getCode()), $e->getMessage());
  320. }
  321. return $this->success();
  322. }
  323. /**
  324. * @api {post} /admin/wallet/verifyRecharge 审核
  325. * @apiGroup 充值管理
  326. * @apiUse result
  327. * @apiUse header
  328. * @apiVersion 1.0.0
  329. * @apiParam {int} id 充值表的ID
  330. * @apiParam {int} status 状态
  331. * - 1 通过
  332. * - 2 拒绝
  333. * @apiParam {string} [remark] 说明
  334. * - 当status =2 时,此参数必填
  335. */
  336. public
  337. function verifyRecharge()
  338. {
  339. DB::beginTransaction();
  340. try {
  341. request()->validate([
  342. 'id' => ['required', 'integer', 'min:1'],
  343. 'status' => ['required', 'integer', 'in:1,2'],
  344. 'remark' => ['required_if:status,2', 'string', 'min:1']
  345. ]);
  346. $id = request()->input('id');
  347. $status = request()->input('status');
  348. $remark = request()->input('remark', '');
  349. $recharge = Recharge::where('id', $id)
  350. ->where('type', 2)
  351. ->where('status', 0)->lockForUpdate()->first();
  352. if (!$recharge) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
  353. $amount = floatval($recharge->amount);
  354. if ($status == 2) {
  355. $recharge->status = 2;
  356. $recharge->save();
  357. $text = "充值结果通知\n";
  358. $text .= "充值数量:{$amount} USDT\n";
  359. $text .= "充值地址:{$recharge->to_address}\n";
  360. $text .= "状态:失败\n";
  361. $text .= "原因:{$remark}\n";
  362. TopUpService::notifyTransferSuccess($recharge->member_id, $text);
  363. } else {
  364. // 汇率
  365. $rate = Config::where('field', 'exchange_rate_rmb')->first()->val ?? 1;
  366. $recharge->status = 1;
  367. $recharge->exchange_rate = $rate;
  368. $recharge->save();
  369. $wallet = WalletModel::where('member_id', $recharge->member_id)
  370. ->lockForUpdate()->first();
  371. $rate_amount = bcmul($amount, $rate, 10); // 汇率转换后分数
  372. $available_balance = bcadd($wallet->available_balance, $rate_amount, 10);
  373. $beforeBalance = (string)$wallet->available_balance;
  374. $wallet->available_balance = $available_balance;
  375. $wallet->save();
  376. $principal = BalanceLogService::addLog($recharge->member_id, $rate_amount, $beforeBalance, $available_balance, "充值", $recharge->id, "用户充值后台审核到账", orderSource: 'recharges');
  377. \App\Services\RechargeBonusService::grant('recharge', $recharge, $principal);
  378. $text = "充值结果通知\n";
  379. $text .= "充值数量:{$amount} USDT\n";
  380. $text .= "充值地址:{$recharge->to_address}\n";
  381. $text .= "汇率:1 USDT = {$rate} RMB\n";
  382. $text .= "折合金额:" . number_format($rate_amount, 2) . " RMB\n";
  383. $text .= "状态:成功\n";
  384. TopUpService::notifyTransferSuccess($recharge->member_id, $text);
  385. }
  386. DB::commit();
  387. } catch (ValidationException $e) {
  388. DB::rollBack();
  389. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  390. } catch (Exception $e) {
  391. DB::rollBack();
  392. return $this->error(intval($e->getCode()), $e->getMessage());
  393. }
  394. return $this->success();
  395. }
  396. /**
  397. * @api {get} /admin/wallet 充值列表
  398. * @apiGroup 充值管理
  399. * @apiDescription 如果列表的type=2 并且 status = 0 <br/>那么代表这条数据是需要后台手动审核的
  400. * 需要有审核按钮,审核通过或者拒绝,其它情况则不需要审核按钮
  401. *
  402. * @apiUse result
  403. * @apiUse header
  404. * @apiVersion 1.0.0
  405. *
  406. * @apiParam {int} [page=1]
  407. * @apiParam {int} [limit=10]
  408. * @apiParam {string} [member_id] 房主 tg会员ID
  409. * @apiParam {int} [status] 状态
  410. * - 0 待确认
  411. * - 1 已确认
  412. * - 2 失败
  413. * - 3 已忽略
  414. * @apiSuccess (data) {Object} data
  415. * @apiSuccess (data) {int} data.total 数量
  416. * @apiSuccess (data) {Object[]} data.data 列表
  417. * @apiSuccess (data) {int} data.data.id
  418. * @apiSuccess (data) {int} data.data.member_id tg会员id
  419. * @apiSuccess (data) {string} data.data.net 链接类型
  420. * @apiSuccess (data) {string} data.data.coin 币种
  421. * @apiSuccess (data) {string} data.data.amount 充值数量
  422. * @apiSuccess (data) {string} data.data.to_address 充值地址(平台地址)
  423. * @apiSuccess (data) {string} data.data.from_address 转出地址(用户发起地址)
  424. * @apiSuccess (data) {string} data.data.txid 链上交易哈希
  425. * @apiSuccess (data) {string} data.data.block_time 区块时间
  426. * @apiSuccess (data) {string} data.data.block_height
  427. * @apiSuccess (data) {int} data.data.confirmations 确认数
  428. * @apiSuccess (data) {string} data.data.updated_at
  429. * @apiSuccess (data) {string} data.data.created_at
  430. * @apiSuccess (data) {int} data.data.status 状态
  431. * - 0 待确认
  432. * - 1 已确认
  433. * - 2 失败
  434. * - 3 已忽略
  435. * @apiSuccess (data) {int} data.data.type 充值类型
  436. * - 1 自动
  437. * - 2 手动
  438. * @apiSuccess (data) {string} data.data.image 充值转账凭证图片
  439. */
  440. public
  441. function index()
  442. {
  443. try {
  444. request()->validate([
  445. 'member_id' => ['nullable', 'string', 'min:1'],
  446. 'status' => ['nullable', 'string', 'min:0', 'max:3'],
  447. 'type' => ['nullable', 'integer', 'in:1,2'],
  448. 'account' => ['nullable', 'string', 'max:64'],
  449. 'first_name' => ['nullable'],
  450. ]);
  451. $search = request()->all();
  452. $result = RechargeService::paginate($search);
  453. foreach($result['data'] as &$item) {
  454. if ($item['from'] == 2) {
  455. $item['image'] = str_replace(config('app.url'), config('app.football_url').'/', $item['image']);
  456. }
  457. }
  458. } catch (ValidationException $e) {
  459. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  460. } catch (Exception $e) {
  461. return $this->error(intval($e->getCode()));
  462. }
  463. return $this->success($result);
  464. }
  465. }