PayRechargeController.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. <?php
  2. namespace App\Http\Controllers\Game;
  3. use App\Facade\TableName;
  4. use App\Game\Services\OuroGameService;
  5. use App\Http\Controllers\Controller;
  6. use App\Http\helper\NumConfig;
  7. use App\Models\Order;
  8. use App\Services\OrderServices;
  9. use App\Utility\SetNXLock;
  10. use App\Util;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Redis;
  14. class PayRechargeController extends Controller
  15. {
  16. // 充值记录
  17. public function orderList(Request $request)
  18. {
  19. $user_id = (int)$request->globalUser->UserID;//$request->get('user_id', 1);
  20. $page = $request->get('page', 1);
  21. $pageSize = $request->get('pageSize', 7);
  22. $redisKey = 'PayRecharge_orderList_'.$user_id;
  23. if (!SetNXLock::getExclusiveLock($redisKey)) {
  24. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  25. }
  26. $where[] = ['user_id', $user_id];
  27. $where[] = ['pay_status', 1];
  28. $cacheTime = 60 * rand(1, 2);
  29. // $list = cache()->remember($user_id . '_order_list', $cacheTime, function () use ($where, $pageSize) {
  30. //
  31. // return Order::where($where)
  32. // ->orderBy('finished_at', 'desc')
  33. // ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
  34. // ->paginate(15,['*'],'page',1);
  35. // });
  36. $list = Order::query()->where($where)
  37. ->orderBy('finished_at', 'desc')
  38. ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status,type')
  39. ->paginate($pageSize);
  40. // ->paginate(15,['*'],'page',1);
  41. foreach ($list as &$val) {
  42. $val->amount = number_format($val->amount, 2, '.', '');
  43. }
  44. SetNXLock::release($redisKey);
  45. return apiReturnSuc($list);
  46. }
  47. // 首充
  48. public function firstPay(Request $request)
  49. {
  50. $user = $request->user();
  51. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  52. ->where('UserID', $user->UserID)
  53. ->value('Recharge') ?: 0;
  54. if($user_recharge)return apiReturnSuc();
  55. $firstPayGift = DB::table('agent.dbo.recharge_gift')
  56. ->where('gift_id', 301)->first();
  57. if(!$firstPayGift) return apiReturnFail();
  58. $names = DB::table('agent.dbo.admin_configs')
  59. ->where([
  60. 'type' => 'pay_method',
  61. 'status' => 1,
  62. ])
  63. ->selectRaw('id, name, status, new_pay_type as type')
  64. ->orderByDesc('sort')->get()->toArray();
  65. $list = DB::table('agent.dbo.recharge_gear')
  66. ->select('id','money','favorable_price','give')
  67. ->orderBy('money', 'asc')->where('status', 1)->get();
  68. $gear = Util::filterGearByDevice(\GuzzleHttp\json_encode($names));
  69. foreach ($list as &$val) {
  70. $val->favorable_price = $val->favorable_price + $val->give;
  71. $val->gear = $gear;
  72. $val->recommend = 0;
  73. if($val->money == $firstPayGift->recommend){
  74. $val->recommend = 1;
  75. }
  76. }
  77. return apiReturnSuc(compact('list', 'firstPayGift'));
  78. }
  79. // 首充礼包(带倒计时逻辑)
  80. public function firstPayGift(Request $request)
  81. {
  82. $user = $request->user();
  83. // 获取礼包配置
  84. $giftConfig = DB::table('agent.dbo.recharge_gift')
  85. ->where('gift_id', 301)
  86. ->first();
  87. if (!$giftConfig) {
  88. return apiReturnFail('礼包配置不存在');
  89. }
  90. // 检查用户是否购买了首充礼包
  91. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  92. ->where('user_id', $user->UserID)
  93. ->first();
  94. // ========== 未购买礼包:返回充值列表 + 礼包配置 + 倒计时 ==========
  95. if (!$giftRecord) {
  96. // 获取充值档位列表
  97. $list = DB::table('agent.dbo.recharge_gear')
  98. ->select('money', 'favorable_price', 'give', 'gear')
  99. ->orderBy('money', 'asc')
  100. ->where('status', 1)
  101. ->where('in_shop', 1)
  102. ->get();
  103. foreach ($list as &$val) {
  104. $val->favorable_price = $val->favorable_price + $val->give;
  105. $val->recommend = 0;
  106. if ($val->money == $giftConfig->recommend) {
  107. $val->recommend = 1;
  108. }
  109. if (!empty($val->gear)) {
  110. $val->gear = Util::filterGearByDevice($val->gear);
  111. }
  112. }
  113. // ========== 处理倒计时逻辑(仅未购买时) ==========
  114. $redisKey = "first_pay_gift_timer_{$user->UserID}";
  115. $currentTime = time();
  116. $timeLeft = 0;
  117. $timerData = Redis::get($redisKey);
  118. if ($timerData) {
  119. $timerData = json_decode($timerData, true);
  120. $firstRequestTime = $timerData['first_request_time'];
  121. $phase = $timerData['phase'];
  122. // 阶段1:valid_h倒计时
  123. if ($phase === 'first') {
  124. $expireTime = $firstRequestTime + ($giftConfig->valid_h * 3600);
  125. if ($currentTime >= $expireTime) {
  126. $expireDate = date('Y-m-d', $expireTime);
  127. $currentDate = date('Y-m-d', $currentTime);
  128. if ($expireDate !== $currentDate) {
  129. // 进入阶段2
  130. $nextDayStart = time();
  131. $newExpireTime = $nextDayStart + ($giftConfig->valid_h_2 * 3600);
  132. $newTimerData = [
  133. 'first_request_time' => $firstRequestTime,
  134. 'phase' => 'daily',
  135. 'current_cycle_start' => $nextDayStart,
  136. 'last_expire_time' => $newExpireTime
  137. ];
  138. Redis::set($redisKey, json_encode($newTimerData));
  139. $timeLeft = max(0, $newExpireTime - $currentTime);
  140. }
  141. } else {
  142. $timeLeft = $expireTime - $currentTime;
  143. }
  144. }
  145. // 阶段2:每日循环
  146. elseif ($phase === 'daily') {
  147. $currentCycleStart = $timerData['current_cycle_start'];
  148. $expireTime = $currentCycleStart + ($giftConfig->valid_h_2 * 3600);
  149. if ($currentTime >= $expireTime) {
  150. $expireDate = date('Y-m-d', $expireTime);
  151. $currentDate = date('Y-m-d', $currentTime);
  152. if ($expireDate !== $currentDate) {
  153. $todayStart = time();
  154. $newExpireTime = $todayStart + ($giftConfig->valid_h_2 * 3600);
  155. $newTimerData = [
  156. 'first_request_time' => $firstRequestTime,
  157. 'phase' => 'daily',
  158. 'current_cycle_start' => $todayStart,
  159. 'last_expire_time' => $newExpireTime
  160. ];
  161. Redis::set($redisKey, json_encode($newTimerData));
  162. $timeLeft = max(0, $newExpireTime - $currentTime);
  163. }
  164. } else {
  165. $timeLeft = $expireTime - $currentTime;
  166. }
  167. }
  168. } else {
  169. // 首次请求,初始化倒计时
  170. $expireTime = $currentTime + ($giftConfig->valid_h * 3600);
  171. $timerData = [
  172. 'first_request_time' => $currentTime,
  173. 'phase' => 'first',
  174. 'last_expire_time' => $expireTime
  175. ];
  176. Redis::set($redisKey, json_encode($timerData));
  177. $timeLeft = $giftConfig->valid_h * 3600;
  178. }
  179. return apiReturnSuc([
  180. 'has_purchased' => false, // 未购买标记
  181. 'list' => $list, // 充值档位列表
  182. 'gift_info' => [
  183. 'gift_id' => $giftConfig->gift_id,
  184. 'gift_name' => $giftConfig->gift_name,
  185. 'total_bonus' => $giftConfig->total_bonus,
  186. 'bonus_instantly' => $giftConfig->bonus_instantly,
  187. 'day_rewards' => $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards) : null,
  188. 'betting_bonus' => $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus) : null,
  189. 'betting_task' => $giftConfig->betting_task ? json_decode($giftConfig->betting_task) : null,
  190. ],
  191. 'time_left' => $timeLeft, // ✅ 倒计时(未购买时展示)
  192. 'expire_at' => time() + $timeLeft // ✅ 过期时间戳
  193. ]);
  194. }
  195. // ========== 已购买礼包:返回任务进度(无倒计时) ==========
  196. // 获取用户当前累计下注次数(从RecordUserGameCount表)
  197. $currentTotalBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  198. ->where('UserID', $user->UserID)
  199. ->sum('Cnt') ?? 0;
  200. // 获取用户当前累计下注金额(从统计表,用于下注任务)
  201. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  202. ->where('UserID', $user->UserID)
  203. ->first();
  204. $currentTotalBetAmount = $userStats->TotalBet ?? 0;
  205. // 更新下注进度到礼包记录(betting_current_bet存储下注次数,用于下注奖励)
  206. DB::table('agent.dbo.first_pay_gift_records')
  207. ->where('user_id', $user->UserID)
  208. ->update([
  209. 'betting_current_bet' => $currentTotalBetCount,
  210. 'updated_at' => date('Y-m-d H:i:s')
  211. ]);
  212. // 重新获取最新记录
  213. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  214. ->where('user_id', $user->UserID)
  215. ->first();
  216. // 解析任务数据
  217. $dayRewardsData = $giftRecord->day_rewards_data ? json_decode($giftRecord->day_rewards_data, true) : null;
  218. $bettingBonusData = $giftRecord->betting_bonus_data ? json_decode($giftRecord->betting_bonus_data, true) : null;
  219. $bettingTaskData = $giftRecord->betting_task_data ? json_decode($giftRecord->betting_task_data, true) : null;
  220. // 计算当前是购买后的第几天(所有任务都需要用到)
  221. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  222. $today = date('Y-m-d');
  223. $daysPassed = floor((strtotime($today) - strtotime($purchaseDate)) / 86400);
  224. // 构建返回数据
  225. $giftInfo = [
  226. 'gift_id' => $giftRecord->gift_id,
  227. 'gift_name' => $giftRecord->gift_name,
  228. 'total_bonus' => (float)$giftRecord->total_bonus,
  229. 'bonus_instantly' => (float)$giftRecord->bonus_instantly,
  230. 'pay_amount' => (float)$giftRecord->pay_amount,
  231. ];
  232. // 每日奖励进度
  233. if ($dayRewardsData) {
  234. $startDay = $dayRewardsData['start_day'] ?? 1;
  235. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  236. $claimedDays = $giftRecord->day_rewards_claimed;
  237. // $startDay = $startDay-1;
  238. // 判断每日奖励状态
  239. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  240. $dayRewardStatus = 0; // 默认不可领取
  241. // 检查是否过期(购买后7天)
  242. if ($daysPassed >= 7) {
  243. $dayRewardStatus = 3; // 过期
  244. } elseif ($daysPassed >= $startDay-1) {
  245. // 计算今天是第几个奖励日(从起始天数开始)
  246. $rewardIndex = $daysPassed - ($startDay-1);
  247. if ($rewardIndex < $bonusDay) {
  248. // 在奖励期内
  249. if ($claimedDays > $rewardIndex) {
  250. $dayRewardStatus = 2; // 已领取
  251. } else {
  252. // 即便前几天漏领,后续奖励仍可继续领取(漏掉的视为作废)
  253. $dayRewardStatus = 1; // 可领取
  254. }
  255. } else {
  256. // 超过奖励天数
  257. $dayRewardStatus = 2; // 已领取完
  258. }
  259. }
  260. $giftInfo['day_rewards'] = [
  261. 'total_bonus' => (float)$giftRecord->day_rewards_total,
  262. 'bonus_day' => $bonusDay,
  263. 'start_day' => $startDay,
  264. 'bonus' => $dayRewardsData['bonus'] ?? [],
  265. 'claimed_days' => $claimedDays,
  266. 'progress' => $claimedDays . '/' . $bonusDay,
  267. 'status' => $dayRewardStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  268. 'status_text' => ['不可领取', '可领取', '已领取', '过期'][$dayRewardStatus] ?? '未知'
  269. ];
  270. }
  271. // 下注奖励进度(使用下注次数)
  272. if ($bettingBonusData) {
  273. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  274. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  275. $currentBetCount = $giftRecord->betting_current_bet; // 当前累计下注次数
  276. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  277. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  278. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领取金额
  279. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  280. $perReward = (float)$perBetBonus;
  281. // 根据当前下注次数计算已达成的次数
  282. $completedTimes = floor($currentBetCount / $perBet);
  283. // 已领取的次数
  284. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  285. // 当前可领取次数(但不能超过剩余总额)
  286. $canClaimTimes = $completedTimes - $claimedTimes;
  287. $maxCanClaimTimes = floor($remainingBonus / $perReward); // 剩余总额最多可领次数
  288. $canClaimTimes = min($canClaimTimes, $maxCanClaimTimes);
  289. // 当前可领取金额
  290. $canClaimAmount = min($canClaimTimes * $perReward, $remainingBonus);
  291. // 计算下次领取需要的下注次数
  292. $nextClaimBet = 0;
  293. if ($remainingBonus > 0 && $canClaimTimes == 0) {
  294. // 还有剩余奖励但当前不能领取,计算还需下注多少次
  295. $nextClaimBet = ($claimedTimes + 1) * $perBet - $currentBetCount;
  296. }
  297. // 判断下注奖励状态
  298. // 0=不可领取(可领取金额为0), 1=可领取, 2=已领取(所有奖励都领完), 3=过期
  299. $bettingBonusStatus = 0; // 默认不可领取
  300. // 检查是否过期(购买后7天)
  301. if ($daysPassed >= 7) {
  302. $bettingBonusStatus = 3; // 过期
  303. } elseif ($remainingBonus <= 0) {
  304. $bettingBonusStatus = 2; // 已领取完
  305. } elseif ($canClaimAmount > 0) {
  306. $bettingBonusStatus = 1; // 可领取
  307. } else {
  308. $bettingBonusStatus = 0; // 不可领取(下注次数不足)
  309. }
  310. $giftInfo['betting_bonus'] = [
  311. 'total_bonus' => (float)$totalBonusLimit, // 总奖励上限
  312. 'per_bet' => $perBet, // 每次下注次数要求
  313. 'per_bet_bonus' => $perReward, // 每次奖励金额(实际金额)
  314. // 'per_reward' => $perReward, // 每次奖励金额(保持兼容)
  315. 'current_bet' => (float)$currentBetCount, // 当前累计下注次数
  316. 'claimed_amount' => (float)$claimedAmount, // 已领取金额
  317. 'remaining_bonus' => (float)$remainingBonus, // 剩余可领金额
  318. 'can_claim_amount' => (float)$canClaimAmount, // 当前可领取金额
  319. 'can_claim_times' => max(0, $canClaimTimes), // 当前可领取次数
  320. 'next_claim_bet' => max(0, $nextClaimBet), // 下次领取还需下注次数
  321. 'progress' => round($currentBetCount, 0) . '/' . round($claimedTimes * $perBet + $perBet, 0), // 当前进度/下次领取目标(次数)
  322. 'status' => $bettingBonusStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  323. 'status_text' => ['不可领取', '可领取', '已领取', '过期'][$bettingBonusStatus] ?? '未知'
  324. ];
  325. }
  326. // 下注任务进度(使用下注金额)
  327. if ($bettingTaskData) {
  328. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  329. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  330. $currentProgress = $currentTotalBetAmount / NumConfig::NUM_VALUE; // 使用下注金额,不是次数
  331. $taskCompleted = $currentProgress >= $requiredBet;
  332. $isClaimed = $giftRecord->betting_task_claimed == 1;
  333. // 判断下注任务状态
  334. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  335. $bettingTaskStatus = 0; // 默认不可领取
  336. // 检查是否过期(购买后7天)
  337. if ($daysPassed >= 7) {
  338. $bettingTaskStatus = 3; // 过期
  339. } elseif ($isClaimed) {
  340. $bettingTaskStatus = 2; // 已领取
  341. } elseif ($taskCompleted) {
  342. $bettingTaskStatus = 1; // 可领取(任务完成且未领取)
  343. } else {
  344. $bettingTaskStatus = 0; // 不可领取(任务未完成)
  345. }
  346. $giftInfo['betting_task'] = [
  347. 'total_bonus' => (float)$giftRecord->betting_task_total,
  348. 'bet_pay_times' => $betPayTimes,
  349. 'required_bet' => $requiredBet, // 需要下注的金额
  350. 'current_bet' => (float)$currentProgress, // 当前累计下注
  351. 'progress' => round($currentProgress, 2) . '/' . $requiredBet,
  352. 'status' => $bettingTaskStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  353. 'status_text' => ['不可领取', '可领取', '已领取', '过期'][$bettingTaskStatus] ?? '未知'
  354. ];
  355. }
  356. $giftInfo['expired'] = strtotime($giftRecord->created_at)+86400*7;
  357. return apiReturnSuc([
  358. 'has_purchased' => true, // 已购买标记
  359. 'gift_info' => $giftInfo
  360. // ✅ 已购买用户不返回倒计时
  361. ]);
  362. }
  363. /**
  364. * 领取首充礼包奖励
  365. */
  366. public function claimFirstPayGiftReward(Request $request)
  367. {
  368. $user = $request->user();
  369. $userId = $user->UserID;
  370. $rewardType = $request->input('reward_type'); // 'day_reward', 'betting_bonus', 'betting_task'
  371. // 获取礼包记录
  372. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  373. ->where('user_id', $userId)
  374. ->first();
  375. if (!$giftRecord) {
  376. return apiReturnFail('未购买首充礼包');
  377. }
  378. $rewardAmount = 0;
  379. try {
  380. // 每日奖励领取
  381. if ($rewardType === 'day_reward') {
  382. $dayRewardsData = json_decode($giftRecord->day_rewards_data, true);
  383. if (!$dayRewardsData) {
  384. return apiReturnFail('没有每日奖励配置');
  385. }
  386. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  387. $startDay = $dayRewardsData['start_day'] ?? 1;
  388. $bonusArray = $dayRewardsData['bonus'] ?? [];
  389. $claimedDays = $giftRecord->day_rewards_claimed;
  390. // 检查是否还有可领取的天数
  391. if ($claimedDays >= $bonusDay) {
  392. return apiReturnFail('每日奖励已全部领取');
  393. }
  394. // 计算当前是购买后的第几天
  395. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  396. $currentDate = date('Y-m-d');
  397. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  398. // 检查是否到了可以领取的天数(从第start_day天开始)
  399. if ($daysPassed < $startDay-1) {
  400. return apiReturnFail('还未到可领取时间,需要从第' . $startDay . '天开始');
  401. }
  402. // 计算今天应该领取第几天的奖励
  403. // 例如:start_day=2,今天是第3天,应该领取第1个奖励(索引0)
  404. $todayRewardIndex = $daysPassed - ($startDay-1);
  405. // 检查是否超过奖励天数
  406. if ($todayRewardIndex >= $bonusDay) {
  407. return apiReturnFail('每日奖励已过期');
  408. }
  409. // 检查今天是否已领取
  410. $lastClaimDate = $giftRecord->day_last_claim_date;
  411. if ($lastClaimDate && $lastClaimDate === $currentDate) {
  412. return apiReturnFail('今天已经领取过了');
  413. }
  414. // 检查是否跳过了某些天(过期不补领)
  415. // 如果今天应该领第5天的奖励,但用户只领了3天,那就直接领第5天的
  416. if ($todayRewardIndex > $claimedDays) {
  417. // 跳过了一些天,更新已领取天数为今天的索引
  418. $claimedDays = $todayRewardIndex;
  419. }
  420. // 计算今天可领取的奖励(使用todayRewardIndex作为索引)
  421. $todayBonusPercent = $bonusArray[$todayRewardIndex] ?? 0;
  422. $rewardAmount = round($giftRecord->pay_amount * $todayBonusPercent / 100, 2);
  423. // 更新记录
  424. DB::table('agent.dbo.first_pay_gift_records')
  425. ->where('user_id', $userId)
  426. ->update([
  427. 'day_rewards_claimed' => $todayRewardIndex + 1, // 已领取到第几天(索引+1)
  428. 'day_last_claim_date' => $currentDate,
  429. 'updated_at' => date('Y-m-d H:i:s')
  430. ]);
  431. }
  432. // 下注奖励领取(使用下注次数)
  433. elseif ($rewardType === 'betting_bonus') {
  434. $bettingBonusData = json_decode($giftRecord->betting_bonus_data, true);
  435. if (!$bettingBonusData) {
  436. return apiReturnFail('没有下注奖励配置');
  437. }
  438. // 检查是否过期(购买后7天)
  439. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  440. $currentDate = date('Y-m-d');
  441. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  442. if ($daysPassed >= 7) {
  443. return apiReturnFail('下注奖励已过期');
  444. }
  445. // 获取最新的下注次数
  446. $currentBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  447. ->where('UserID', $userId)
  448. ->sum('Cnt') ?? 0;
  449. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  450. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  451. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  452. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  453. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领金额
  454. // 检查是否还有剩余奖励
  455. if ($remainingBonus <= 0) {
  456. return apiReturnFail('下注奖励已全部领取');
  457. }
  458. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  459. $perReward = (float)$perBetBonus;
  460. // 根据当前下注次数计算已达成的次数
  461. $completedTimes = floor($currentBetCount / $perBet);
  462. // 已领取的次数
  463. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  464. // 可领取次数(下注达成的次数 - 已领取次数)
  465. $canClaimTimes = $completedTimes - $claimedTimes;
  466. // 检查是否可以领取
  467. if ($canClaimTimes <= 0) {
  468. return apiReturnFail('下注次数不足,还需下注 ' . (($claimedTimes + 1) * $perBet - $currentBetCount) . ' 次才能领取');
  469. }
  470. // ✅ 一次性领取所有已达成的奖励(但不能超过剩余总额)
  471. $totalCanClaimAmount = $canClaimTimes * $perReward; // 理论可领取总额
  472. $rewardAmount = min($totalCanClaimAmount, $remainingBonus); // 实际领取金额(不超过剩余总额)
  473. $actualClaimTimes = floor($rewardAmount / $perReward); // 实际领取次数
  474. // 更新记录(同时更新下注次数)
  475. DB::table('agent.dbo.first_pay_gift_records')
  476. ->where('user_id', $userId)
  477. ->update([
  478. 'betting_bonus_claimed' => $giftRecord->betting_bonus_claimed + $rewardAmount,
  479. 'betting_current_bet' => $currentBetCount, // 更新最新下注次数
  480. 'updated_at' => date('Y-m-d H:i:s')
  481. ]);
  482. \Log::info('下注奖励领取', [
  483. 'user_id' => $userId,
  484. 'can_claim_times' => $canClaimTimes,
  485. 'actual_claim_times' => $actualClaimTimes,
  486. 'reward_amount' => $rewardAmount
  487. ]);
  488. }
  489. // 下注任务领取(使用下注金额)
  490. elseif ($rewardType === 'betting_task') {
  491. if ($giftRecord->betting_task_claimed == 1) {
  492. return apiReturnFail('下注任务奖励已领取');
  493. }
  494. $bettingTaskData = json_decode($giftRecord->betting_task_data, true);
  495. if (!$bettingTaskData) {
  496. return apiReturnFail('没有下注任务配置');
  497. }
  498. // 检查是否过期(购买后7天)
  499. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  500. $currentDate = date('Y-m-d');
  501. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  502. if ($daysPassed >= 7) {
  503. return apiReturnFail('下注任务奖励已过期');
  504. }
  505. // 获取最新的下注金额
  506. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  507. ->where('UserID', $userId)
  508. ->first();
  509. $currentBetAmount = ($userStats->TotalBet ?? 0) / NumConfig::NUM_VALUE;
  510. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  511. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  512. if ($currentBetAmount < $requiredBet) {
  513. return apiReturnFail('下注金额不足,需要下注 ' . $requiredBet);
  514. }
  515. $rewardAmount = $giftRecord->betting_task_total;
  516. // 更新记录
  517. DB::table('agent.dbo.first_pay_gift_records')
  518. ->where('user_id', $userId)
  519. ->update([
  520. 'betting_task_claimed' => 1,
  521. 'updated_at' => date('Y-m-d H:i:s')
  522. ]);
  523. }
  524. else {
  525. return apiReturnFail('无效的奖励类型');
  526. }
  527. // 添加奖励到用户账户
  528. if ($rewardAmount > 0) {
  529. OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=首充礼包奖励
  530. \Log::info('首充礼包奖励领取', [
  531. 'user_id' => $userId,
  532. 'reward_type' => $rewardType,
  533. 'amount' => $rewardAmount
  534. ]);
  535. }
  536. return apiReturnSuc([
  537. 'amount' => $rewardAmount,
  538. 'message' => '成功领取 ' . $rewardAmount . ' 奖励'
  539. ]);
  540. } catch (\Exception $e) {
  541. \Log::error('首充礼包奖励领取失败', [
  542. 'user_id' => $userId,
  543. 'error' => $e->getMessage()
  544. ]);
  545. return apiReturnFail('领取失败:' . $e->getMessage());
  546. }
  547. }
  548. /**
  549. * 获取首充礼包数据(包含充值档位列表)
  550. * @param $firstPayGift 礼包配置
  551. * @param $timeLeft 剩余秒数(已经是用户实际剩余时间)
  552. */
  553. private function getFirstPayGiftData($firstPayGift, $timeLeft)
  554. {
  555. // 获取支付方式
  556. // $names = DB::table('agent.dbo.admin_configs')
  557. // ->where([
  558. // 'type' => 'pay_method',
  559. // 'status' => 1,
  560. // ])
  561. // ->selectRaw('id, name, status, new_pay_type as type')
  562. // ->orderByDesc('sort')
  563. // ->get()
  564. // ->toArray();
  565. // 获取充值档位
  566. $list = DB::table('agent.dbo.recharge_gear')
  567. ->select('money', 'favorable_price', 'give','gear')
  568. ->orderBy('money', 'asc')
  569. ->where('status', 1)
  570. ->where('in_shop', 1)
  571. ->get();
  572. // $gear = \GuzzleHttp\json_encode($names);
  573. foreach ($list as &$val) {
  574. $val->favorable_price = $val->favorable_price + $val->give;
  575. // $val->gear = $gear;
  576. $val->recommend = 0;
  577. if ($val->money == $firstPayGift->recommend) {
  578. $val->recommend = 1;
  579. }
  580. if (!empty($val->gear)) {
  581. $val->gear = Util::filterGearByDevice($val->gear);
  582. }
  583. }
  584. return apiReturnSuc([
  585. 'list' => $list,
  586. 'gift_info' => [
  587. 'gift_id' => $firstPayGift->gift_id,
  588. 'gift_name' => $firstPayGift->gift_name,
  589. 'total_bonus' => $firstPayGift->total_bonus,
  590. 'bonus_instantly' => $firstPayGift->bonus_instantly,
  591. 'day_rewards' => $firstPayGift->day_rewards?json_decode($firstPayGift->day_rewards):'',
  592. 'betting_bonus' => $firstPayGift->betting_bonus?json_decode($firstPayGift->betting_bonus):'',
  593. 'betting_task' => $firstPayGift->betting_task?json_decode($firstPayGift->betting_task):'',
  594. ],
  595. 'time_left' => $timeLeft, // 剩余秒数
  596. 'expire_at' => time() + $timeLeft // 过期时间戳
  597. ]);
  598. }
  599. public function firstPayMulti(Request $request)
  600. {
  601. $user = LoginController::checkLogin($request);
  602. if($user){
  603. if(env('CONFIG_24680_NFTD_99',0)==0)if($user->Channel==99)return apiReturnFail();
  604. $fpkey='Firstpay_'.$user->UserID;
  605. if(Redis::exists($fpkey)){
  606. $data=Redis::get($fpkey);
  607. $data=json_decode($data,true);
  608. $data['timeleft']=86400-(time()-$data['buytime']);
  609. return apiReturnSuc(['leftitem'=>$data]);
  610. }
  611. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  612. ->where('UserID', $user->UserID)
  613. ->value('Recharge') ?: 0;
  614. if($user_recharge)return apiReturnFail();
  615. }
  616. $items=DB::table('agent.dbo.recharge_gear')
  617. ->where('status',1)
  618. ->where('second_give','>',0)
  619. ->where('first_pay','>=', 1)
  620. ->select('gift_id','money','give','favorable_price','second_give')->get()->each(function($item){
  621. $item->id=28;
  622. })->toArray();
  623. $default=count($items)-1;
  624. return apiReturnSuc(compact('items','default'));
  625. }
  626. // 破产礼包
  627. public function bankruptcyGift(Request $request)
  628. {
  629. $user = $request->user();
  630. // 判断用户是否充值
  631. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  632. ->where('UserID', $user->UserID)
  633. ->value('Recharge') ?: 0;
  634. if ($user_recharge <= 0) {
  635. return apiReturnFail('用户未充值');
  636. }
  637. // 获取所有破产礼包配置 (gift_id=302)
  638. $bankruptcyGifts = DB::table('agent.dbo.recharge_gift')
  639. ->where('gift_id', 302)
  640. ->get();
  641. if ($bankruptcyGifts->isEmpty()) {
  642. return apiReturnFail('破产礼包配置不存在');
  643. }
  644. $result = [];
  645. // 遍历每条礼包配置,根据 recommend 关联 recharge_gear
  646. foreach ($bankruptcyGifts as $gift) {
  647. $gear = DB::table('agent.dbo.recharge_gear')
  648. ->select('money', 'favorable_price', 'gear')
  649. ->where('money', $gift->recommend)
  650. ->where('status', 1)
  651. ->first();
  652. if ($gear) {
  653. $gear->gift_id = $gift->gift_id;
  654. $gear->total_bonus = $gift->total_bonus;
  655. $gear->bonus = $gift->total_bonus - 100;
  656. if (!empty($gear->gear)) {
  657. $gear->gear = Util::filterGearByDevice($gear->gear);
  658. }
  659. $result[] = $gear;
  660. }
  661. }
  662. // 按 money 排序
  663. usort($result, function($a, $b) {
  664. return $a->money <=> $b->money;
  665. });
  666. return apiReturnSuc($result);
  667. }
  668. public function getSecondGive(Request $request)
  669. {
  670. $user = $request->user();
  671. $fpkey='Firstpay_'.$user->UserID;
  672. if(Redis::exists($fpkey)){
  673. $data=Redis::get($fpkey);
  674. $data=json_decode($data,true);
  675. $data['timeleft']=86400-(time()-$data['buytime']);
  676. if($data['timeleft']<=0) {
  677. Redis::del($fpkey);
  678. //加钱
  679. if($data['second_give']){
  680. $czReason=$data['czReason'];
  681. $cjReason=$data['cjReason'];
  682. [$OrgScore,$NowScore]=OuroGameService::AddScore($user->UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);
  683. //更新二次领钱记录
  684. DB::table(TableName::agent() . 'guide_payment')->where('UserID',$user->UserID)->update([
  685. 'GetSecondTime' => now(),
  686. 'SecondScoreNum'=>$data['second_give']*NumConfig::NUM_VALUE
  687. ]);
  688. return apiReturnSuc(compact('OrgScore','NowScore'));
  689. }
  690. return apiReturnSuc();
  691. }
  692. }
  693. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  694. }
  695. }