PayRechargeController.php 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. <?php
  2. namespace App\Http\Controllers\Game;
  3. use App\Facade\TableName;
  4. use App\Game\GlobalUserInfo;
  5. use App\Game\Services\OuroGameService;
  6. use App\Http\Controllers\Controller;
  7. use App\Http\helper\NumConfig;
  8. use App\Models\Order;
  9. use App\Services\OrderServices;
  10. use App\Utility\SetNXLock;
  11. use App\Util;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Support\Facades\App;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Redis;
  16. class PayRechargeController extends Controller
  17. {
  18. /**
  19. * 设置用户语言环境
  20. */
  21. private function setUserLocale($request)
  22. {
  23. $user = $request->user();
  24. if ($user) {
  25. $locale = GlobalUserInfo::getLocaleByUserID($user->UserID, 'en');
  26. App::setLocale($locale);
  27. }
  28. }
  29. // 充值记录
  30. public function orderList(Request $request)
  31. {
  32. $user_id = (int)$request->globalUser->UserID;//$request->get('user_id', 1);
  33. $page = $request->get('page', 1);
  34. $pageSize = $request->get('pageSize', 7);
  35. $redisKey = 'PayRecharge_orderList_'.$user_id;
  36. if (!SetNXLock::getExclusiveLock($redisKey)) {
  37. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  38. }
  39. $where[] = ['user_id', $user_id];
  40. $where[] = ['pay_status', 1];
  41. $cacheTime = 60 * rand(1, 2);
  42. // $list = cache()->remember($user_id . '_order_list', $cacheTime, function () use ($where, $pageSize) {
  43. //
  44. // return Order::where($where)
  45. // ->orderBy('finished_at', 'desc')
  46. // ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
  47. // ->paginate(15,['*'],'page',1);
  48. // });
  49. $list = Order::query()->where($where)
  50. ->orderBy('finished_at', 'desc')
  51. ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status,type')
  52. ->paginate($pageSize);
  53. // ->paginate(15,['*'],'page',1);
  54. foreach ($list as &$val) {
  55. $val->amount = number_format($val->amount, 2, '.', '');
  56. }
  57. SetNXLock::release($redisKey);
  58. return apiReturnSuc($list);
  59. }
  60. // 首充
  61. public function firstPay(Request $request)
  62. {
  63. $user = $request->user();
  64. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  65. ->where('UserID', $user->UserID)
  66. ->value('Recharge') ?: 0;
  67. if($user_recharge)return apiReturnSuc();
  68. $firstPayGift = DB::table('agent.dbo.recharge_gift')
  69. ->where('gift_id', 301)->first();
  70. if(!$firstPayGift) return apiReturnFail();
  71. $names = DB::table('agent.dbo.admin_configs')
  72. ->where([
  73. 'type' => 'pay_method',
  74. 'status' => 1,
  75. ])
  76. ->selectRaw('id, name, status, new_pay_type as type')
  77. ->orderByDesc('sort')->get()->toArray();
  78. $list = DB::table('agent.dbo.recharge_gear')
  79. ->select('id','money','favorable_price','give')
  80. ->orderBy('money', 'asc')->where('status', 1)->get();
  81. $gear = Util::filterGearByDevice(\GuzzleHttp\json_encode($names));
  82. foreach ($list as &$val) {
  83. $val->favorable_price = $val->favorable_price + $val->give;
  84. $val->gear = $gear;
  85. $val->recommend = 0;
  86. if($val->money == $firstPayGift->recommend){
  87. $val->recommend = 1;
  88. }
  89. }
  90. return apiReturnSuc(compact('list', 'firstPayGift'));
  91. }
  92. // 首充礼包(带倒计时逻辑)
  93. public function firstPayGift(Request $request)
  94. {
  95. $user = $request->user();
  96. $this->setUserLocale($request);
  97. // 获取礼包配置
  98. $giftConfig = DB::table('agent.dbo.recharge_gift')
  99. ->where('gift_id', 301)
  100. ->first();
  101. if (!$giftConfig) {
  102. return apiReturnFail(['web.gift.config_not_exists', __('web.gift.config_not_exists')]);
  103. }
  104. // 检查用户是否购买了首充礼包
  105. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  106. ->where('user_id', $user->UserID)
  107. ->first();
  108. // ========== 未购买礼包:返回充值列表 + 礼包配置 + 倒计时 ==========
  109. if (!$giftRecord) {
  110. // 获取充值档位列表
  111. $list = DB::table('agent.dbo.recharge_gear')
  112. ->select('money', 'favorable_price', 'give', 'gear')
  113. ->orderBy('money', 'asc')
  114. ->where('status', 1)
  115. ->where('in_shop', 1)
  116. ->get();
  117. foreach ($list as &$val) {
  118. $val->favorable_price = $val->favorable_price + $val->give;
  119. $val->recommend = 0;
  120. if ($val->money == $giftConfig->recommend) {
  121. $val->recommend = 1;
  122. }
  123. if (!empty($val->gear)) {
  124. $val->gear = Util::filterGearByDevice($val->gear);
  125. }
  126. }
  127. // ========== 处理倒计时逻辑(仅未购买时) ==========
  128. $redisKey = "first_pay_gift_timer_{$user->UserID}";
  129. $currentTime = time();
  130. $timeLeft = 0;
  131. $timerData = Redis::get($redisKey);
  132. if ($timerData) {
  133. $timerData = json_decode($timerData, true);
  134. $firstRequestTime = $timerData['first_request_time'];
  135. $phase = $timerData['phase'];
  136. // 阶段1:valid_h倒计时
  137. if ($phase === 'first') {
  138. $expireTime = $firstRequestTime + ($giftConfig->valid_h * 3600);
  139. if ($currentTime >= $expireTime) {
  140. $expireDate = date('Y-m-d', $expireTime);
  141. $currentDate = date('Y-m-d', $currentTime);
  142. if ($expireDate !== $currentDate) {
  143. // 进入阶段2
  144. $nextDayStart = time();
  145. $newExpireTime = $nextDayStart + ($giftConfig->valid_h_2 * 3600);
  146. $newTimerData = [
  147. 'first_request_time' => $firstRequestTime,
  148. 'phase' => 'daily',
  149. 'current_cycle_start' => $nextDayStart,
  150. 'last_expire_time' => $newExpireTime
  151. ];
  152. Redis::set($redisKey, json_encode($newTimerData));
  153. $timeLeft = max(0, $newExpireTime - $currentTime);
  154. }
  155. } else {
  156. $timeLeft = $expireTime - $currentTime;
  157. }
  158. }
  159. // 阶段2:每日循环
  160. elseif ($phase === 'daily') {
  161. $currentCycleStart = $timerData['current_cycle_start'];
  162. $expireTime = $currentCycleStart + ($giftConfig->valid_h_2 * 3600);
  163. if ($currentTime >= $expireTime) {
  164. $expireDate = date('Y-m-d', $expireTime);
  165. $currentDate = date('Y-m-d', $currentTime);
  166. if ($expireDate !== $currentDate) {
  167. $todayStart = time();
  168. $newExpireTime = $todayStart + ($giftConfig->valid_h_2 * 3600);
  169. $newTimerData = [
  170. 'first_request_time' => $firstRequestTime,
  171. 'phase' => 'daily',
  172. 'current_cycle_start' => $todayStart,
  173. 'last_expire_time' => $newExpireTime
  174. ];
  175. Redis::set($redisKey, json_encode($newTimerData));
  176. $timeLeft = max(0, $newExpireTime - $currentTime);
  177. }
  178. } else {
  179. $timeLeft = $expireTime - $currentTime;
  180. }
  181. }
  182. } else {
  183. // 首次请求,初始化倒计时
  184. $expireTime = $currentTime + ($giftConfig->valid_h * 3600);
  185. $timerData = [
  186. 'first_request_time' => $currentTime,
  187. 'phase' => 'first',
  188. 'last_expire_time' => $expireTime
  189. ];
  190. Redis::set($redisKey, json_encode($timerData));
  191. $timeLeft = $giftConfig->valid_h * 3600;
  192. }
  193. return apiReturnSuc([
  194. 'has_purchased' => false, // 未购买标记
  195. 'list' => $list, // 充值档位列表
  196. 'gift_info' => [
  197. 'gift_id' => $giftConfig->gift_id,
  198. 'gift_name' => $giftConfig->gift_name,
  199. 'total_bonus' => $giftConfig->total_bonus,
  200. 'bonus_instantly' => $giftConfig->bonus_instantly,
  201. 'day_rewards' => $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards) : null,
  202. 'betting_bonus' => $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus) : null,
  203. 'betting_task' => $giftConfig->betting_task ? json_decode($giftConfig->betting_task) : null,
  204. ],
  205. 'time_left' => $timeLeft, // ✅ 倒计时(未购买时展示)
  206. 'expire_at' => time() + $timeLeft // ✅ 过期时间戳
  207. ]);
  208. }
  209. // ========== 已购买礼包:返回任务进度(无倒计时) ==========
  210. // 获取用户当前累计下注次数(从RecordUserGameCount表)
  211. $currentTotalBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  212. ->where('UserID', $user->UserID)
  213. ->sum('Cnt') ?? 0;
  214. // 获取用户当前累计下注金额(从统计表,用于下注任务)
  215. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  216. ->where('UserID', $user->UserID)
  217. ->first();
  218. $currentTotalBetAmount = $userStats->TotalBet ?? 0;
  219. // 更新下注进度到礼包记录(betting_current_bet存储下注次数,用于下注奖励)
  220. DB::table('agent.dbo.first_pay_gift_records')
  221. ->where('user_id', $user->UserID)
  222. ->update([
  223. 'betting_current_bet' => $currentTotalBetCount,
  224. 'updated_at' => date('Y-m-d H:i:s')
  225. ]);
  226. // 重新获取最新记录
  227. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  228. ->where('user_id', $user->UserID)
  229. ->first();
  230. // 解析任务数据
  231. $dayRewardsData = $giftRecord->day_rewards_data ? json_decode($giftRecord->day_rewards_data, true) : null;
  232. $bettingBonusData = $giftRecord->betting_bonus_data ? json_decode($giftRecord->betting_bonus_data, true) : null;
  233. $bettingTaskData = $giftRecord->betting_task_data ? json_decode($giftRecord->betting_task_data, true) : null;
  234. // 计算当前是购买后的第几天(所有任务都需要用到)
  235. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  236. $today = date('Y-m-d');
  237. $daysPassed = floor((strtotime($today) - strtotime($purchaseDate)) / 86400);
  238. // 构建返回数据
  239. $giftInfo = [
  240. 'gift_id' => $giftRecord->gift_id,
  241. 'gift_name' => $giftRecord->gift_name,
  242. 'total_bonus' => (float)$giftRecord->total_bonus,
  243. 'bonus_instantly' => (float)$giftRecord->bonus_instantly,
  244. 'pay_amount' => (float)$giftRecord->pay_amount,
  245. ];
  246. // 每日奖励进度
  247. if ($dayRewardsData) {
  248. $startDay = $dayRewardsData['start_day'] ?? 1;
  249. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  250. $claimedDays = $giftRecord->day_rewards_claimed;
  251. // $startDay = $startDay-1;
  252. // 判断每日奖励状态
  253. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  254. $dayRewardStatus = 0; // 默认不可领取
  255. // 检查是否过期(购买后7天)
  256. if ($daysPassed >= 7) {
  257. $dayRewardStatus = 3; // 过期
  258. } elseif ($daysPassed >= $startDay-1) {
  259. // 计算今天是第几个奖励日(从起始天数开始)
  260. $rewardIndex = $daysPassed - ($startDay-1);
  261. if ($rewardIndex < $bonusDay) {
  262. // 在奖励期内
  263. if ($claimedDays > $rewardIndex) {
  264. $dayRewardStatus = 2; // 已领取
  265. } else {
  266. // 即便前几天漏领,后续奖励仍可继续领取(漏掉的视为作废)
  267. $dayRewardStatus = 1; // 可领取
  268. }
  269. } else {
  270. // 超过奖励天数
  271. $dayRewardStatus = 2; // 已领取完
  272. }
  273. }
  274. $giftInfo['day_rewards'] = [
  275. 'total_bonus' => (float)$giftRecord->day_rewards_total,
  276. 'bonus_day' => $bonusDay,
  277. 'start_day' => $startDay,
  278. 'bonus' => $dayRewardsData['bonus'] ?? [],
  279. 'claimed_days' => $claimedDays,
  280. 'progress' => $claimedDays . '/' . $bonusDay,
  281. 'status' => $dayRewardStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  282. 'status_text' => [
  283. __('web.gift.status_cannot_claim'),
  284. __('web.gift.status_can_claim'),
  285. __('web.gift.status_claimed'),
  286. __('web.gift.status_expired')
  287. ][$dayRewardStatus] ?? __('web.gift.status_unknown')
  288. ];
  289. }
  290. // 下注奖励进度(使用下注次数)
  291. if ($bettingBonusData) {
  292. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  293. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  294. $currentBetCount = $giftRecord->betting_current_bet; // 当前累计下注次数
  295. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  296. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  297. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领取金额
  298. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  299. $perReward = (float)$perBetBonus;
  300. // 根据当前下注次数计算已达成的次数
  301. $completedTimes = floor($currentBetCount / $perBet);
  302. // 已领取的次数
  303. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  304. // 当前可领取次数(但不能超过剩余总额)
  305. $canClaimTimes = $completedTimes - $claimedTimes;
  306. $maxCanClaimTimes = floor($remainingBonus / $perReward); // 剩余总额最多可领次数
  307. $canClaimTimes = min($canClaimTimes, $maxCanClaimTimes);
  308. // 当前可领取金额
  309. $canClaimAmount = min($canClaimTimes * $perReward, $remainingBonus);
  310. // 计算下次领取需要的下注次数
  311. $nextClaimBet = 0;
  312. if ($remainingBonus > 0 && $canClaimTimes == 0) {
  313. // 还有剩余奖励但当前不能领取,计算还需下注多少次
  314. $nextClaimBet = ($claimedTimes + 1) * $perBet - $currentBetCount;
  315. }
  316. // 判断下注奖励状态
  317. // 0=不可领取(可领取金额为0), 1=可领取, 2=已领取(所有奖励都领完), 3=过期
  318. $bettingBonusStatus = 0; // 默认不可领取
  319. // 检查是否过期(购买后7天)
  320. if ($daysPassed >= 7) {
  321. $bettingBonusStatus = 3; // 过期
  322. } elseif ($remainingBonus <= 0) {
  323. $bettingBonusStatus = 2; // 已领取完
  324. } elseif ($canClaimAmount > 0) {
  325. $bettingBonusStatus = 1; // 可领取
  326. } else {
  327. $bettingBonusStatus = 0; // 不可领取(下注次数不足)
  328. }
  329. $giftInfo['betting_bonus'] = [
  330. 'total_bonus' => (float)$totalBonusLimit, // 总奖励上限
  331. 'per_bet' => $perBet, // 每次下注次数要求
  332. 'per_bet_bonus' => $perReward, // 每次奖励金额(实际金额)
  333. // 'per_reward' => $perReward, // 每次奖励金额(保持兼容)
  334. 'current_bet' => (float)$currentBetCount, // 当前累计下注次数
  335. 'claimed_amount' => (float)$claimedAmount, // 已领取金额
  336. 'remaining_bonus' => (float)$remainingBonus, // 剩余可领金额
  337. 'can_claim_amount' => (float)$canClaimAmount, // 当前可领取金额
  338. 'can_claim_times' => max(0, $canClaimTimes), // 当前可领取次数
  339. 'next_claim_bet' => max(0, $nextClaimBet), // 下次领取还需下注次数
  340. 'progress' => round($currentBetCount, 0) . '/' . round($claimedTimes * $perBet + $perBet, 0), // 当前进度/下次领取目标(次数)
  341. 'status' => $bettingBonusStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  342. 'status_text' => [
  343. __('web.gift.status_cannot_claim'),
  344. __('web.gift.status_can_claim'),
  345. __('web.gift.status_claimed'),
  346. __('web.gift.status_expired')
  347. ][$bettingBonusStatus] ?? __('web.gift.status_unknown')
  348. ];
  349. }
  350. // 下注任务进度(使用下注金额)
  351. if ($bettingTaskData) {
  352. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  353. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  354. $currentProgress = $currentTotalBetAmount / NumConfig::NUM_VALUE; // 使用下注金额,不是次数
  355. $taskCompleted = $currentProgress >= $requiredBet;
  356. $isClaimed = $giftRecord->betting_task_claimed == 1;
  357. // 判断下注任务状态
  358. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  359. $bettingTaskStatus = 0; // 默认不可领取
  360. // 检查是否过期(购买后7天)
  361. if ($daysPassed >= 7) {
  362. $bettingTaskStatus = 3; // 过期
  363. } elseif ($isClaimed) {
  364. $bettingTaskStatus = 2; // 已领取
  365. } elseif ($taskCompleted) {
  366. $bettingTaskStatus = 1; // 可领取(任务完成且未领取)
  367. } else {
  368. $bettingTaskStatus = 0; // 不可领取(任务未完成)
  369. }
  370. $giftInfo['betting_task'] = [
  371. 'total_bonus' => (float)$giftRecord->betting_task_total,
  372. 'bet_pay_times' => $betPayTimes,
  373. 'required_bet' => $requiredBet, // 需要下注的金额
  374. 'current_bet' => (float)$currentProgress, // 当前累计下注
  375. 'progress' => round($currentProgress, 2) . '/' . $requiredBet,
  376. 'status' => $bettingTaskStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  377. 'status_text' => [
  378. __('web.gift.status_cannot_claim'),
  379. __('web.gift.status_can_claim'),
  380. __('web.gift.status_claimed'),
  381. __('web.gift.status_expired')
  382. ][$bettingTaskStatus] ?? __('web.gift.status_unknown')
  383. ];
  384. }
  385. $giftInfo['expired'] = strtotime($giftRecord->created_at)+86400*7;
  386. return apiReturnSuc([
  387. 'has_purchased' => true, // 已购买标记
  388. 'gift_info' => $giftInfo
  389. // ✅ 已购买用户不返回倒计时
  390. ]);
  391. }
  392. /**
  393. * 领取首充礼包奖励
  394. */
  395. public function claimFirstPayGiftReward(Request $request)
  396. {
  397. $user = $request->user();
  398. $userId = $user->UserID;
  399. $rewardType = $request->input('reward_type'); // 'day_reward', 'betting_bonus', 'betting_task'
  400. $this->setUserLocale($request);
  401. // 获取礼包记录
  402. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  403. ->where('user_id', $userId)
  404. ->first();
  405. if (!$giftRecord) {
  406. return apiReturnFail(['web.gift.not_purchased', __('web.gift.not_purchased')]);
  407. }
  408. $rewardAmount = 0;
  409. try {
  410. // 每日奖励领取
  411. if ($rewardType === 'day_reward') {
  412. $dayRewardsData = json_decode($giftRecord->day_rewards_data, true);
  413. if (!$dayRewardsData) {
  414. return apiReturnFail(['web.gift.no_day_rewards_config', __('web.gift.no_day_rewards_config')]);
  415. }
  416. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  417. $startDay = $dayRewardsData['start_day'] ?? 1;
  418. $bonusArray = $dayRewardsData['bonus'] ?? [];
  419. $claimedDays = $giftRecord->day_rewards_claimed;
  420. // 检查是否还有可领取的天数
  421. if ($claimedDays >= $bonusDay) {
  422. return apiReturnFail(['web.gift.day_rewards_all_claimed', __('web.gift.day_rewards_all_claimed')]);
  423. }
  424. // 计算当前是购买后的第几天
  425. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  426. $currentDate = date('Y-m-d');
  427. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  428. // 检查是否到了可以领取的天数(从第start_day天开始)
  429. if ($daysPassed < $startDay-1) {
  430. return apiReturnFail(['web.gift.day_rewards_not_time', str_replace(':day', $startDay, __('web.gift.day_rewards_not_time'))]);
  431. }
  432. // 计算今天应该领取第几天的奖励
  433. // 例如:start_day=2,今天是第3天,应该领取第1个奖励(索引0)
  434. $todayRewardIndex = $daysPassed - ($startDay-1);
  435. // 检查是否超过奖励天数
  436. if ($todayRewardIndex >= $bonusDay) {
  437. return apiReturnFail(['web.gift.day_rewards_expired', __('web.gift.day_rewards_expired')]);
  438. }
  439. // 检查今天是否已领取
  440. $lastClaimDate = $giftRecord->day_last_claim_date;
  441. if ($lastClaimDate && $lastClaimDate === $currentDate) {
  442. return apiReturnFail(['web.gift.day_rewards_claimed_today', __('web.gift.day_rewards_claimed_today')]);
  443. }
  444. // 检查是否跳过了某些天(过期不补领)
  445. // 如果今天应该领第5天的奖励,但用户只领了3天,那就直接领第5天的
  446. if ($todayRewardIndex > $claimedDays) {
  447. // 跳过了一些天,更新已领取天数为今天的索引
  448. $claimedDays = $todayRewardIndex;
  449. }
  450. // 计算今天可领取的奖励(使用todayRewardIndex作为索引)
  451. $todayBonusPercent = $bonusArray[$todayRewardIndex] ?? 0;
  452. $rewardAmount = round($giftRecord->pay_amount * $todayBonusPercent / 100, 2);
  453. // 更新记录
  454. DB::table('agent.dbo.first_pay_gift_records')
  455. ->where('user_id', $userId)
  456. ->update([
  457. 'day_rewards_claimed' => $todayRewardIndex + 1, // 已领取到第几天(索引+1)
  458. 'day_last_claim_date' => $currentDate,
  459. 'updated_at' => date('Y-m-d H:i:s')
  460. ]);
  461. }
  462. // 下注奖励领取(使用下注次数)
  463. elseif ($rewardType === 'betting_bonus') {
  464. $bettingBonusData = json_decode($giftRecord->betting_bonus_data, true);
  465. if (!$bettingBonusData) {
  466. return apiReturnFail(['web.gift.no_betting_bonus_config', __('web.gift.no_betting_bonus_config')]);
  467. }
  468. // 检查是否过期(购买后7天)
  469. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  470. $currentDate = date('Y-m-d');
  471. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  472. if ($daysPassed >= 7) {
  473. return apiReturnFail(['web.gift.betting_bonus_expired', __('web.gift.betting_bonus_expired')]);
  474. }
  475. // 获取最新的下注次数
  476. $currentBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  477. ->where('UserID', $userId)
  478. ->sum('Cnt') ?? 0;
  479. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  480. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  481. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  482. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  483. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领金额
  484. // 检查是否还有剩余奖励
  485. if ($remainingBonus <= 0) {
  486. return apiReturnFail(['web.gift.betting_bonus_all_claimed', __('web.gift.betting_bonus_all_claimed')]);
  487. }
  488. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  489. $perReward = (float)$perBetBonus;
  490. // 根据当前下注次数计算已达成的次数
  491. $completedTimes = floor($currentBetCount / $perBet);
  492. // 已领取的次数
  493. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  494. // 可领取次数(下注达成的次数 - 已领取次数)
  495. $canClaimTimes = $completedTimes - $claimedTimes;
  496. // 检查是否可以领取
  497. if ($canClaimTimes <= 0) {
  498. $neededBets = (($claimedTimes + 1) * $perBet - $currentBetCount);
  499. return apiReturnFail(['web.gift.betting_bonus_insufficient', str_replace(':times', $neededBets, __('web.gift.betting_bonus_insufficient'))]);
  500. }
  501. // ✅ 一次性领取所有已达成的奖励(但不能超过剩余总额)
  502. $totalCanClaimAmount = $canClaimTimes * $perReward; // 理论可领取总额
  503. $rewardAmount = min($totalCanClaimAmount, $remainingBonus); // 实际领取金额(不超过剩余总额)
  504. $actualClaimTimes = floor($rewardAmount / $perReward); // 实际领取次数
  505. // 更新记录(同时更新下注次数)
  506. DB::table('agent.dbo.first_pay_gift_records')
  507. ->where('user_id', $userId)
  508. ->update([
  509. 'betting_bonus_claimed' => $giftRecord->betting_bonus_claimed + $rewardAmount,
  510. 'betting_current_bet' => $currentBetCount, // 更新最新下注次数
  511. 'updated_at' => date('Y-m-d H:i:s')
  512. ]);
  513. \Log::info('下注奖励领取', [
  514. 'user_id' => $userId,
  515. 'can_claim_times' => $canClaimTimes,
  516. 'actual_claim_times' => $actualClaimTimes,
  517. 'reward_amount' => $rewardAmount
  518. ]);
  519. }
  520. // 下注任务领取(使用下注金额)
  521. elseif ($rewardType === 'betting_task') {
  522. if ($giftRecord->betting_task_claimed == 1) {
  523. return apiReturnFail(['web.gift.betting_task_claimed', __('web.gift.betting_task_claimed')]);
  524. }
  525. $bettingTaskData = json_decode($giftRecord->betting_task_data, true);
  526. if (!$bettingTaskData) {
  527. return apiReturnFail(['web.gift.no_betting_task_config', __('web.gift.no_betting_task_config')]);
  528. }
  529. // 检查是否过期(购买后7天)
  530. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  531. $currentDate = date('Y-m-d');
  532. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  533. if ($daysPassed >= 7) {
  534. return apiReturnFail(['web.gift.betting_task_expired', __('web.gift.betting_task_expired')]);
  535. }
  536. // 获取最新的下注金额
  537. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  538. ->where('UserID', $userId)
  539. ->first();
  540. $currentBetAmount = ($userStats->TotalBet ?? 0) / NumConfig::NUM_VALUE;
  541. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  542. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  543. if ($currentBetAmount < $requiredBet) {
  544. return apiReturnFail(['web.gift.betting_task_insufficient', str_replace(':amount', $requiredBet, __('web.gift.betting_task_insufficient'))]);
  545. }
  546. $rewardAmount = $giftRecord->betting_task_total;
  547. // 更新记录
  548. DB::table('agent.dbo.first_pay_gift_records')
  549. ->where('user_id', $userId)
  550. ->update([
  551. 'betting_task_claimed' => 1,
  552. 'updated_at' => date('Y-m-d H:i:s')
  553. ]);
  554. }
  555. else {
  556. return apiReturnFail(['web.gift.invalid_reward_type', __('web.gift.invalid_reward_type')]);
  557. }
  558. // 添加奖励到用户账户
  559. if ($rewardAmount > 0) {
  560. OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=首充礼包奖励
  561. \Log::info('首充礼包奖励领取', [
  562. 'user_id' => $userId,
  563. 'reward_type' => $rewardType,
  564. 'amount' => $rewardAmount
  565. ]);
  566. }
  567. return apiReturnSuc([
  568. 'amount' => $rewardAmount,
  569. 'message' => str_replace(':amount', $rewardAmount, __('web.gift.claim_success'))
  570. ]);
  571. } catch (\Exception $e) {
  572. \Log::error('首充礼包奖励领取失败', [
  573. 'user_id' => $userId,
  574. 'error' => $e->getMessage()
  575. ]);
  576. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  577. }
  578. }
  579. /**
  580. * 获取首充礼包数据(包含充值档位列表)
  581. * @param $firstPayGift 礼包配置
  582. * @param $timeLeft 剩余秒数(已经是用户实际剩余时间)
  583. */
  584. private function getFirstPayGiftData($firstPayGift, $timeLeft)
  585. {
  586. // 获取支付方式
  587. // $names = DB::table('agent.dbo.admin_configs')
  588. // ->where([
  589. // 'type' => 'pay_method',
  590. // 'status' => 1,
  591. // ])
  592. // ->selectRaw('id, name, status, new_pay_type as type')
  593. // ->orderByDesc('sort')
  594. // ->get()
  595. // ->toArray();
  596. // 获取充值档位
  597. $list = DB::table('agent.dbo.recharge_gear')
  598. ->select('money', 'favorable_price', 'give','gear')
  599. ->orderBy('money', 'asc')
  600. ->where('status', 1)
  601. ->where('in_shop', 1)
  602. ->get();
  603. // $gear = \GuzzleHttp\json_encode($names);
  604. foreach ($list as &$val) {
  605. $val->favorable_price = $val->favorable_price + $val->give;
  606. // $val->gear = $gear;
  607. $val->recommend = 0;
  608. if ($val->money == $firstPayGift->recommend) {
  609. $val->recommend = 1;
  610. }
  611. if (!empty($val->gear)) {
  612. $val->gear = Util::filterGearByDevice($val->gear);
  613. }
  614. }
  615. return apiReturnSuc([
  616. 'list' => $list,
  617. 'gift_info' => [
  618. 'gift_id' => $firstPayGift->gift_id,
  619. 'gift_name' => $firstPayGift->gift_name,
  620. 'total_bonus' => $firstPayGift->total_bonus,
  621. 'bonus_instantly' => $firstPayGift->bonus_instantly,
  622. 'day_rewards' => $firstPayGift->day_rewards?json_decode($firstPayGift->day_rewards):'',
  623. 'betting_bonus' => $firstPayGift->betting_bonus?json_decode($firstPayGift->betting_bonus):'',
  624. 'betting_task' => $firstPayGift->betting_task?json_decode($firstPayGift->betting_task):'',
  625. ],
  626. 'time_left' => $timeLeft, // 剩余秒数
  627. 'expire_at' => time() + $timeLeft // 过期时间戳
  628. ]);
  629. }
  630. public function firstPayMulti(Request $request)
  631. {
  632. $user = LoginController::checkLogin($request);
  633. if($user){
  634. if(env('CONFIG_24680_NFTD_99',0)==0)if($user->Channel==99)return apiReturnFail();
  635. $fpkey='Firstpay_'.$user->UserID;
  636. if(Redis::exists($fpkey)){
  637. $data=Redis::get($fpkey);
  638. $data=json_decode($data,true);
  639. $data['timeleft']=86400-(time()-$data['buytime']);
  640. return apiReturnSuc(['leftitem'=>$data]);
  641. }
  642. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  643. ->where('UserID', $user->UserID)
  644. ->value('Recharge') ?: 0;
  645. if($user_recharge)return apiReturnFail();
  646. }
  647. $items=DB::table('agent.dbo.recharge_gear')
  648. ->where('status',1)
  649. ->where('second_give','>',0)
  650. ->where('first_pay','>=', 1)
  651. ->select('gift_id','money','give','favorable_price','second_give')->get()->each(function($item){
  652. $item->id=28;
  653. })->toArray();
  654. $default=count($items)-1;
  655. return apiReturnSuc(compact('items','default'));
  656. }
  657. // 破产礼包
  658. public function bankruptcyGift(Request $request)
  659. {
  660. $user = $request->user();
  661. $this->setUserLocale($request);
  662. // 判断用户是否充值
  663. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  664. ->where('UserID', $user->UserID)
  665. ->value('Recharge') ?: 0;
  666. if ($user_recharge <= 0) {
  667. return apiReturnFail(['web.gift.user_not_recharged', __('web.gift.user_not_recharged')]);
  668. }
  669. // 获取所有破产礼包配置 (gift_id=302)
  670. $bankruptcyGifts = DB::table('agent.dbo.recharge_gift')
  671. ->where('gift_id', 302)
  672. ->get();
  673. if ($bankruptcyGifts->isEmpty()) {
  674. return apiReturnFail(['web.gift.bankruptcy_gift_not_exists', __('web.gift.bankruptcy_gift_not_exists')]);
  675. }
  676. $result = [];
  677. // 遍历每条礼包配置,根据 recommend 关联 recharge_gear
  678. foreach ($bankruptcyGifts as $gift) {
  679. $gear = DB::table('agent.dbo.recharge_gear')
  680. ->select('money', 'favorable_price', 'gear')
  681. ->where('money', $gift->recommend)
  682. ->where('status', 1)
  683. ->first();
  684. if ($gear) {
  685. $gear->gift_id = $gift->gift_id;
  686. $gear->total_bonus = $gift->total_bonus;
  687. $gear->bonus = $gift->total_bonus - 100;
  688. if (!empty($gear->gear)) {
  689. $gear->gear = Util::filterGearByDevice($gear->gear);
  690. }
  691. $result[] = $gear;
  692. }
  693. }
  694. // 按 money 排序
  695. usort($result, function($a, $b) {
  696. return $a->money <=> $b->money;
  697. });
  698. return apiReturnSuc($result);
  699. }
  700. // 每日首充礼包
  701. public function dailyFirstRechargeGift(Request $request)
  702. {
  703. $user = $request->user();
  704. $this->setUserLocale($request);
  705. // 检查用户今日是否已充值(完成任意档位充值后入口消失)
  706. $todayStart = date('Y-m-d') . ' 00:00:00';
  707. $todayEnd = date('Y-m-d') . ' 23:59:59';
  708. $todayRecharge = DB::table('agent.dbo.order')
  709. ->where('user_id', $user->UserID)
  710. ->where('pay_status', 1)
  711. ->where('GiftsID', 303)
  712. ->where('pay_at', '>=', $todayStart)
  713. ->where('pay_at', '<=', $todayEnd)
  714. ->first();
  715. // 如果今日已充值,返回入口消失标记
  716. if ($todayRecharge) {
  717. return apiReturnSuc([
  718. 'has_recharged_today' => true,
  719. 'message' => __('web.gift.recharged_today')
  720. ]);
  721. }
  722. // 获取每日首充礼包配置 (gift_id=303)
  723. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  724. ->where('gift_id', 303)
  725. ->get();
  726. if ($dailyGifts->isEmpty()) {
  727. return apiReturnFail(['web.gift.daily_first_recharge_not_exists', __('web.gift.daily_first_recharge_not_exists')]);
  728. }
  729. $result = [];
  730. // 遍历每条礼包配置,根据 recommend 关联 recharge_gear
  731. foreach ($dailyGifts as $gift) {
  732. $gear = DB::table('agent.dbo.recharge_gear')
  733. ->select('money', 'favorable_price', 'gear', 'give')
  734. ->where('money', $gift->recommend)
  735. ->where('status', 1)
  736. ->first();
  737. if ($gear) {
  738. $gear->gift_id = $gift->gift_id;
  739. $gear->total_bonus = $gift->total_bonus;
  740. $gear->bonus = $gift->total_bonus - 100;
  741. $gear->recommend = $gift->first_pay?1:0;
  742. if (!empty($gear->gear)) {
  743. $gear->gear = Util::filterGearByDevice($gear->gear);
  744. }
  745. $result[] = $gear;
  746. }
  747. }
  748. // 按 money 排序
  749. usort($result, function($a, $b) {
  750. return $a->money <=> $b->money;
  751. });
  752. return apiReturnSuc([
  753. 'has_recharged_today' => false,
  754. 'list' => $result
  755. ]);
  756. }
  757. // 每日礼包(三档充值)
  758. public function dailyGift(Request $request)
  759. {
  760. $user = $request->user();
  761. $this->setUserLocale($request);
  762. // 获取每日礼包配置 (gift_id=304),应该有3档
  763. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  764. ->where('gift_id', 304)
  765. ->orderBy('recommend', 'asc')
  766. ->get();
  767. if ($dailyGifts->isEmpty()) {
  768. return apiReturnFail(['web.gift.daily_gift_not_exists', __('web.gift.daily_gift_not_exists')]);
  769. }
  770. if ($dailyGifts->count() > 3) {
  771. // 如果配置超过3档,只取前3档
  772. $dailyGifts = $dailyGifts->take(3);
  773. }
  774. // 检查用户今日每档的充值状态
  775. $todayStart = date('Y-m-d') . ' 00:00:00';
  776. $todayEnd = date('Y-m-d') . ' 23:59:59';
  777. $todayRecharges = DB::table('agent.dbo.order')
  778. ->where('user_id', $user->UserID)
  779. ->where('GiftsID', 304)
  780. ->where('pay_status', 1)
  781. ->where('pay_at', '>=', $todayStart)
  782. ->where('pay_at', '<=', $todayEnd)
  783. ->pluck('amount')
  784. ->toArray();
  785. $result = [];
  786. $completedCount = 0;
  787. // 遍历每档配置
  788. foreach ($dailyGifts as $index => $gift) {
  789. $gear = DB::table('agent.dbo.recharge_gear')
  790. ->select('money', 'favorable_price', 'gear', 'give')
  791. ->where('money', $gift->recommend)
  792. ->where('status', 1)
  793. ->first();
  794. if ($gear) {
  795. // 检查该档位今日是否已充值(使用浮点数比较,允许小数点精度差异)
  796. $isCompleted = false;
  797. foreach ($todayRecharges as $rechargeAmount) {
  798. if (abs($rechargeAmount/100 - $gift->recommend) < 0.01) {
  799. $isCompleted = true;
  800. break;
  801. }
  802. }
  803. if ($isCompleted) {
  804. $completedCount++;
  805. }
  806. $gear->gift_id = $gift->gift_id;
  807. $gear->total_bonus = $gift->total_bonus;
  808. $gear->bonus = $gift->total_bonus - 100;
  809. $gear->is_completed = $isCompleted; // 是否已完成
  810. $gear->gear_index = $index + 1; // 档位序号(1,2,3)
  811. $gear->recommend = $gift->first_pay?1:0;
  812. if (!empty($gear->gear)) {
  813. $gear->gear = Util::filterGearByDevice($gear->gear);
  814. }
  815. $result[] = $gear;
  816. }
  817. }
  818. // 获取额外奖励金额(从任意一档的 task_bonus 字段获取,task_bonus 是数字字段)
  819. $taskBonus = null;
  820. $firstGift = $dailyGifts->first();
  821. if ($firstGift && $firstGift->task_bonus !== null) {
  822. $taskBonus = round((float)$firstGift->task_bonus, 2);
  823. }
  824. // 检查是否可以领取额外奖励(三档都完成)
  825. $canClaimBonus = ($completedCount >= 3 && $taskBonus > 0);
  826. // 检查是否已领取过额外奖励
  827. $hasClaimedBonus = false;
  828. if ($canClaimBonus) {
  829. $redisKey = "daily_gift_bonus_claimed_{$user->UserID}_" . date('Y-m-d');
  830. $hasClaimedBonus = Redis::exists($redisKey);
  831. }
  832. return apiReturnSuc([
  833. 'list' => $result,
  834. 'completed_count' => $completedCount,
  835. 'total_count' => count($result),
  836. 'can_claim_bonus' => $canClaimBonus && !$hasClaimedBonus,
  837. 'has_claimed_bonus' => $hasClaimedBonus,
  838. 'task_bonus' => $taskBonus
  839. ]);
  840. }
  841. // 领取每日礼包三档完成后的额外奖励
  842. public function claimDailyGiftBonus(Request $request)
  843. {
  844. $user = $request->user();
  845. $userId = $user->UserID;
  846. $this->setUserLocale($request);
  847. // 检查三档是否都已完成
  848. $todayStart = date('Y-m-d') . ' 00:00:00';
  849. $todayEnd = date('Y-m-d') . ' 23:59:59';
  850. // 获取每日礼包配置
  851. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  852. ->where('gift_id', 304)
  853. ->orderBy('recommend', 'asc')
  854. ->get()
  855. ->take(3);
  856. if ($dailyGifts->isEmpty()) {
  857. return apiReturnFail(['web.gift.daily_gift_not_exists', __('web.gift.daily_gift_not_exists')]);
  858. }
  859. // 检查每档今日是否都已充值
  860. $todayRecharges = DB::table('agent.dbo.order')
  861. ->where('user_id', $userId)
  862. ->where('GiftsID', 304)
  863. ->where('pay_status', 1)
  864. ->where('pay_at', '>=', $todayStart)
  865. ->where('pay_at', '<=', $todayEnd)
  866. ->pluck('amount')
  867. ->toArray();
  868. $completedCount = 0;
  869. foreach ($dailyGifts as $gift) {
  870. // 检查该档位是否已充值(使用浮点数比较)
  871. $isCompleted = false;
  872. foreach ($todayRecharges as $rechargeAmount) {
  873. if (abs($rechargeAmount/100 - $gift->recommend) < 0.01) {
  874. $isCompleted = true;
  875. break;
  876. }
  877. }
  878. if ($isCompleted) {
  879. $completedCount++;
  880. }
  881. }
  882. if ($completedCount < 3) {
  883. return apiReturnFail(['web.gift.three_tiers_not_completed', __('web.gift.three_tiers_not_completed')]);
  884. }
  885. // 检查是否已领取过
  886. $redisKey = "daily_gift_bonus_claimed_{$userId}_" . date('Y-m-d');
  887. if (Redis::exists($redisKey)) {
  888. return apiReturnFail(['web.gift.bonus_already_claimed_today', __('web.gift.bonus_already_claimed_today')]);
  889. }
  890. // 获取奖励金额(从任意一档的 task_bonus 获取,task_bonus 是数字字段)
  891. $firstGift = $dailyGifts->first();
  892. $rewardAmount = 0;
  893. if ($firstGift && $firstGift->task_bonus !== null) {
  894. $rewardAmount = round((float)$firstGift->task_bonus, 2);
  895. }
  896. if ($rewardAmount <= 0) {
  897. return apiReturnFail(['web.gift.bonus_config_not_exists', __('web.gift.bonus_config_not_exists')]);
  898. }
  899. try {
  900. // 发放奖励
  901. OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
  902. // 标记已领取
  903. Redis::setex($redisKey, 86400, 1); // 24小时过期
  904. \Log::info('每日礼包额外奖励领取成功', [
  905. 'user_id' => $userId,
  906. 'reward_amount' => $rewardAmount
  907. ]);
  908. return apiReturnSuc([
  909. 'amount' => $rewardAmount,
  910. 'message' => str_replace(':amount', $rewardAmount, __('web.gift.claim_success'))
  911. ]);
  912. } catch (\Exception $e) {
  913. \Log::error('每日礼包额外奖励领取失败', [
  914. 'user_id' => $userId,
  915. 'error' => $e->getMessage()
  916. ]);
  917. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  918. }
  919. }
  920. public function getSecondGive(Request $request)
  921. {
  922. $user = $request->user();
  923. $fpkey='Firstpay_'.$user->UserID;
  924. if(Redis::exists($fpkey)){
  925. $data=Redis::get($fpkey);
  926. $data=json_decode($data,true);
  927. $data['timeleft']=86400-(time()-$data['buytime']);
  928. if($data['timeleft']<=0) {
  929. Redis::del($fpkey);
  930. //加钱
  931. if($data['second_give']){
  932. $czReason=$data['czReason'];
  933. $cjReason=$data['cjReason'];
  934. [$OrgScore,$NowScore]=OuroGameService::AddScore($user->UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);
  935. //更新二次领钱记录
  936. DB::table(TableName::agent() . 'guide_payment')->where('UserID',$user->UserID)->update([
  937. 'GetSecondTime' => now(),
  938. 'SecondScoreNum'=>$data['second_give']*NumConfig::NUM_VALUE
  939. ]);
  940. return apiReturnSuc(compact('OrgScore','NowScore'));
  941. }
  942. return apiReturnSuc();
  943. }
  944. }
  945. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  946. }
  947. /**
  948. * 连续未充值 VIP 礼包(gift_id=305)—— 检查条件和返回档位
  949. */
  950. public function vipInactiveGift(Request $request)
  951. {
  952. $user = $request->user();
  953. $this->setUserLocale($request);
  954. $userId = $user->UserID;
  955. // 1. VIP 判断:是否有过充值(YN_VIPAccount.Recharge > 0)
  956. $userRecharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  957. ->where('UserID', $userId)
  958. ->value('Recharge') ?: 0;
  959. if ($userRecharge <= 0) {
  960. // 不满足条件:不是 VIP 用户
  961. return apiReturnSuc([
  962. 'status' => 0,
  963. 'message' => __('web.gift.vip_inactive_not_vip')
  964. ]);
  965. }
  966. // 2. 检查最近一次充值时间,计算连续未充值天数
  967. $lastOrder = DB::table('agent.dbo.order')
  968. ->where('user_id', $userId)
  969. ->where('pay_status', 1)
  970. ->where('GiftsID','<>', 305)
  971. ->orderBy('pay_at', 'desc')
  972. ->first();
  973. if (!$lastOrder) {
  974. return apiReturnSuc([
  975. 'status' => 0,
  976. 'message' => __('web.gift.vip_inactive_not_vip')
  977. ]);
  978. }
  979. $lastDate = date('Y-m-d', strtotime($lastOrder->pay_at));
  980. $today = date('Y-m-d');
  981. $diffDays = (strtotime($today) - strtotime($lastDate)) / 86400;
  982. // 连续未充值天数:如果最后一次充值是昨天,则未充值天数为0;如果是前天,则为1;以此类推
  983. // 需要 >= 3 天,即最后一次充值至少是3天前
  984. $inactiveDays = max(0, (int)$diffDays - 1);
  985. if ($inactiveDays < 3) {
  986. // 不满足条件:连续未充值天数不足
  987. return apiReturnSuc([
  988. 'status' => 0,
  989. 'message' => __('web.gift.vip_inactive_days_insufficient'),
  990. 'inactive_days' => $inactiveDays
  991. ]);
  992. }
  993. // 3. 计算总充值与平均单笔(从 RecordUserTotalStatistics)
  994. $stat = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  995. ->where('UserID', $userId)
  996. ->select('Recharge', 'RechargeTimes')
  997. ->first();
  998. $totalRecharge = (float)($stat->Recharge ?? 0) / NumConfig::NUM_VALUE; // 转换为元
  999. $rechargeTimes = (int)($stat->RechargeTimes ?? 0);
  1000. if ($totalRecharge <= 0 || $rechargeTimes <= 0) {
  1001. return apiReturnSuc([
  1002. 'status' => 0,
  1003. 'message' => __('web.gift.vip_inactive_not_vip')
  1004. ]);
  1005. }
  1006. $avgRecharge = $totalRecharge / $rechargeTimes;
  1007. // 4. 按规则选择礼包金额
  1008. $amount = null;
  1009. if ($totalRecharge < 50) {
  1010. $amount = $avgRecharge < 15 ? 9.99 : 19.99;
  1011. } else {
  1012. if ($avgRecharge < 15) {
  1013. $amount = 19.99;
  1014. } elseif ($avgRecharge >= 15 && $avgRecharge < 20) {
  1015. $amount = 29.99;
  1016. } else {
  1017. $amount = 39.99;
  1018. }
  1019. }
  1020. // 5. 检查是否已经买过 305 礼包
  1021. $hasBought = DB::table('agent.dbo.order')
  1022. ->where('user_id', $userId)
  1023. ->where('GiftsID', 305)
  1024. ->where('pay_status', 1)
  1025. ->exists();
  1026. // 6. 查询 7 日礼包记录状态
  1027. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1028. ->where('user_id', $userId)
  1029. ->where('gift_id', 305)
  1030. ->orderBy('id', 'desc')
  1031. ->first();
  1032. /*
  1033. * status 定义:
  1034. * 0 不满足条件
  1035. * 1 满足条件未充值
  1036. * 2 满足条件已充值,奖励未全部领取
  1037. * 3 满足条件已充值,奖励全部领取
  1038. * 4 满足条件已充值,7天礼包已过期
  1039. */
  1040. $status = 1;
  1041. $timeLeft = 0; // 倒计时剩余秒数
  1042. if ($hasBought) {
  1043. if (!$record) {
  1044. $status = 2;
  1045. } else {
  1046. // 检查 7 天礼包是否已过期
  1047. if (strtotime($record->expired_at) < time()) {
  1048. $status = 4; // 7天礼包已过期
  1049. } else {
  1050. // 检查 7 天是否全部领完:claimed_days_mask 的低 7 位全部为 1
  1051. $allClaimedMask = (1 << 7) - 1; // 0b1111111
  1052. $status = (($record->claimed_days_mask & $allClaimedMask) == $allClaimedMask) ? 3 : 2;
  1053. }
  1054. }
  1055. } else {
  1056. // 满足条件但未充值:检查24小时倒计时(每天重置)
  1057. $today = date('Y-m-d');
  1058. $timerKey = "vip_inactive_gift_timer_{$userId}_{$today}";
  1059. $timerData = Redis::get($timerKey);
  1060. if ($timerData) {
  1061. $timerData = json_decode($timerData, true);
  1062. $expireTime = $timerData['expire_time'] ?? 0;
  1063. $timeLeft = max(0, $expireTime - time());
  1064. if ($timeLeft <= 0) {
  1065. // 今天的倒计时已结束,不再显示礼包
  1066. $status = 0;
  1067. }
  1068. } else {
  1069. // 今天首次检测到满足条件,初始化24小时倒计时
  1070. // 从当前时间开始,24小时后过期
  1071. $expireTime = time() + 86400; // 24小时后
  1072. $ttl = 86400 + 3600; // Redis过期时间设为25小时,确保跨天也能获取
  1073. Redis::setex($timerKey, $ttl, json_encode([
  1074. 'expire_time' => $expireTime,
  1075. 'created_at' => time(),
  1076. 'date' => $today
  1077. ]));
  1078. $timeLeft = 86400;
  1079. }
  1080. }
  1081. $payload = [
  1082. 'status' => $status,
  1083. 'inactive_days' => $inactiveDays,
  1084. // 'total_recharge' => $totalRecharge,
  1085. // 'avg_recharge' => round($avgRecharge, 2),
  1086. 'time_left' => $timeLeft,
  1087. 'expire_at' => $timeLeft > 0 ? (time() + $timeLeft) : null,
  1088. 'message' => $status == 1 ? __('web.gift.vip_inactive_can_recharge') :
  1089. ($status == 2 ? __('web.gift.vip_inactive_claimed_partial') :
  1090. ($status == 3 ? __('web.gift.vip_inactive_claimed_all') :
  1091. __('web.gift.vip_inactive_seven_days_expired')))
  1092. ];
  1093. // status=1 时返回充值档位信息(参考 bankruptcyGift),gift_id 固定 305,加总奖励百分比
  1094. if ($status == 1 && $amount !== null) {
  1095. $sevenPercent = 140 + max(0, $inactiveDays - 3) * 10;
  1096. $sevenPercent = min($sevenPercent, 200);
  1097. $totalRewardPercent = 120 + $sevenPercent; // 120% 立即 + 7日礼包%
  1098. $gear = DB::table('agent.dbo.recharge_gear')
  1099. ->select('money', 'favorable_price', 'gear', 'give')
  1100. ->where('money', $amount)
  1101. ->where('status', 1)
  1102. ->first();
  1103. $favorablePrice = round($amount * 120 / 100, 2); // 305 固定 120% 立即到账
  1104. $give = $favorablePrice - $amount;
  1105. if ($gear) {
  1106. $gear->gift_id = 305;
  1107. $gear->favorable_price = $favorablePrice;
  1108. $gear->give = $give;
  1109. $gear->total_bonus = $totalRewardPercent;
  1110. $gear->bonus = $totalRewardPercent;
  1111. $gear->total_reward_percent = $totalRewardPercent;
  1112. $gear->recommend = 1;
  1113. if (!empty($gear->gear)) {
  1114. $gear->gear = Util::filterGearByDevice($gear->gear);
  1115. }
  1116. $payload['list'] = [$gear];
  1117. } else {
  1118. $payload['list'] = [(object)[
  1119. 'money' => $amount,
  1120. 'favorable_price' => $favorablePrice,
  1121. 'give' => $give,
  1122. 'gear' => null,
  1123. 'gift_id' => 305,
  1124. 'total_bonus' => $totalRewardPercent,
  1125. 'bonus' => $totalRewardPercent,
  1126. 'total_reward_percent' => $totalRewardPercent,
  1127. 'recommend' => 1,
  1128. ]];
  1129. }
  1130. $payload['amount'] = $amount;
  1131. $payload['total_reward_percent'] = $totalRewardPercent;
  1132. $payload['extra_reward'] = round($amount*$totalRewardPercent/100);
  1133. $payload['total_reward'] = round($amount*$totalRewardPercent/100)+$amount;
  1134. } else {
  1135. $payload['amount'] = $amount;
  1136. }
  1137. return apiReturnSuc($payload);
  1138. }
  1139. /**
  1140. * 连续未充值 VIP 礼包(gift_id=305)—— 获取 7 日礼包信息
  1141. */
  1142. public function vipInactiveGiftSevenDays(Request $request)
  1143. {
  1144. $user = $request->user();
  1145. $this->setUserLocale($request);
  1146. $userId = $user->UserID;
  1147. // 获取 7 日礼包记录
  1148. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1149. ->where('user_id', $userId)
  1150. ->where('gift_id', 305)
  1151. ->orderBy('id', 'desc')
  1152. ->first();
  1153. if (!$record) {
  1154. return apiReturnFail(['web.gift.vip_inactive_no_record', __('web.gift.vip_inactive_no_record')]);
  1155. }
  1156. // 计算从充值完成后的第几天(从第1天开始,即充值的次日)
  1157. // 如果created_at是2024-01-01,今天是2024-01-02,daysPassed=1,表示可以领取第1天的奖励
  1158. $createdDate = date('Y-m-d', strtotime($record->created_at));
  1159. $today = date('Y-m-d');
  1160. $daysPassed = floor((strtotime($today) - strtotime($createdDate)) / 86400);
  1161. // daysPassed = 0 表示充值当天(还不能领取),1 表示充值的次日(可以领取第1天),以此类推
  1162. // 检查是否已过期(超过7天)
  1163. $expiredAt = strtotime($record->expired_at);
  1164. $isExpired = time() > $expiredAt;
  1165. $perDayAmount = (float)$record->per_day_amount;
  1166. $claimedMask = (int)$record->claimed_days_mask;
  1167. // 构建每一天的状态
  1168. $days = [];
  1169. for ($day = 1; $day <= 7; $day++) {
  1170. $dayIndex = $day - 1; // 位索引:day1对应bit0
  1171. $isClaimed = ($claimedMask & (1 << $dayIndex)) > 0;
  1172. // 计算这一天对应的日期(充值后第day天)
  1173. $targetDate = date('Ymd', strtotime($record->created_at . ' +' . $day . ' days'));
  1174. // 判断状态
  1175. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  1176. $dayStatus = 0;
  1177. $betAmount = 0; // 初始化
  1178. // 第4-7天需要查询流水信息(无论状态如何,都要展示进度)
  1179. if ($day >= 4) {
  1180. // var_dump($userId,$day,$targetDate);
  1181. $todayBet = DB::table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  1182. ->where('UserID', $userId)
  1183. ->where('DateID', $targetDate)
  1184. ->value('TotalBet') ?? 0;
  1185. $betAmount = $todayBet / NumConfig::NUM_VALUE; // 转换为元
  1186. }
  1187. if ($isClaimed) {
  1188. $dayStatus = 2; // 已领取
  1189. } elseif ($daysPassed > $day) {
  1190. // 已过这一天但未领取:过期
  1191. // 例如:今天是第4天(daysPassed=4),但第3天的奖励还没领取,则第3天过期
  1192. $dayStatus = 3; // 过期
  1193. } elseif ($daysPassed < $day) {
  1194. // 还没到这一天:第day天的奖励需要在充值后的第day天才能领取
  1195. // 例如:第1天奖励需要daysPassed >= 1(充值的次日)才能领取
  1196. $dayStatus = 0; // 不可领取
  1197. } elseif ($isExpired || $daysPassed >= 7) {
  1198. // 整体过期(超过7天)时,未领取的奖励都过期
  1199. $dayStatus = 3; // 过期
  1200. } else {
  1201. // 到了这一天,判断是否可以领取
  1202. if ($day <= 3) {
  1203. // 前3天:直接领取
  1204. $dayStatus = 1; // 可领取
  1205. } else {
  1206. // 第4-7天:需要当天游戏流水 >= 100(流水信息已在上面查询)
  1207. if ($betAmount >= 100) {
  1208. $dayStatus = 1; // 可领取
  1209. } else {
  1210. $dayStatus = 0; // 不可领取(流水不足)
  1211. }
  1212. }
  1213. }
  1214. // 计算进度条数据(仅第4-7天)
  1215. $betProgress = null;
  1216. if ($day >= 4) {
  1217. $requiredBet = 100;
  1218. $currentBetValue = round($betAmount, 2);
  1219. $progressPercent = $requiredBet > 0 ? min(100, round(($currentBetValue / $requiredBet) * 100, 2)) : 0;
  1220. $betProgress = [
  1221. 'current' => $currentBetValue, // 当前流水
  1222. 'required' => $requiredBet, // 需要流水
  1223. 'progress_percent' => $progressPercent, // 进度百分比(0-100)
  1224. 'is_completed' => $currentBetValue >= $requiredBet // 是否完成
  1225. ];
  1226. }
  1227. $days[] = [
  1228. 'day' => $day,
  1229. 'amount' => $perDayAmount,
  1230. 'status' => $dayStatus,
  1231. 'status_text' => [
  1232. __('web.gift.status_cannot_claim'),
  1233. __('web.gift.status_can_claim'),
  1234. __('web.gift.status_claimed'),
  1235. __('web.gift.status_expired')
  1236. ][$dayStatus] ?? __('web.gift.status_unknown'),
  1237. 'target_date' => $targetDate,
  1238. 'bet_progress' => $betProgress // 第4-7天的流水进度信息
  1239. ];
  1240. }
  1241. // 检查是否有倒计时(未充值时的24小时倒计时)
  1242. $timerKey = "vip_inactive_gift_timer_{$userId}";
  1243. $timerData = Redis::get($timerKey);
  1244. $timeLeft = 0;
  1245. if ($timerData) {
  1246. $timerData = json_decode($timerData, true);
  1247. $expireTime = $timerData['expire_time'] ?? 0;
  1248. $timeLeft = max(0, $expireTime - time());
  1249. }
  1250. return apiReturnSuc([
  1251. 'record' => [
  1252. 'pay_amount' => (float)$record->pay_amount,
  1253. 'total_percent' => (float)$record->total_percent,
  1254. 'seven_days_percent' => (float)$record->seven_days_percent,
  1255. 'per_day_amount' => $perDayAmount,
  1256. 'inactive_days' => (int)$record->inactive_days,
  1257. 'created_at' => $record->created_at,
  1258. 'expired_at' => $record->expired_at
  1259. ],
  1260. 'days' => $days,
  1261. 'current_day' => min($daysPassed + 1, 7), // 当前是第几天
  1262. 'is_expired' => $isExpired,
  1263. 'time_left' => $timeLeft, // 未充值时的倒计时(秒)
  1264. 'expire_at' => $expiredAt
  1265. ]);
  1266. }
  1267. /**
  1268. * 连续未充值 VIP 礼包(gift_id=305)—— 领取某日奖励
  1269. */
  1270. public function claimVipInactiveGiftDayReward(Request $request)
  1271. {
  1272. $user = $request->user();
  1273. $this->setUserLocale($request);
  1274. $userId = $user->UserID;
  1275. $day = (int)$request->input('day', 0);
  1276. if ($day < 1 || $day > 7) {
  1277. return apiReturnFail(['web.gift.invalid_reward_type', __('web.gift.invalid_reward_type')]);
  1278. }
  1279. // 获取 7 日礼包记录
  1280. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1281. ->where('user_id', $userId)
  1282. ->where('gift_id', 305)
  1283. ->orderBy('id', 'desc')
  1284. ->first();
  1285. if (!$record) {
  1286. return apiReturnFail(['web.gift.vip_inactive_no_record', __('web.gift.vip_inactive_no_record')]);
  1287. }
  1288. // 检查是否已过期
  1289. if (strtotime($record->expired_at) < time()) {
  1290. return apiReturnFail(['web.gift.vip_inactive_expired', __('web.gift.vip_inactive_expired')]);
  1291. }
  1292. // 检查是否已领取
  1293. $claimedMask = (int)$record->claimed_days_mask;
  1294. $dayIndex = $day - 1;
  1295. if ($claimedMask & (1 << $dayIndex)) {
  1296. return apiReturnFail(['web.gift.vip_inactive_day_claimed', str_replace(':day', $day, __('web.gift.vip_inactive_day_claimed'))]);
  1297. }
  1298. // 计算从充值完成后的第几天
  1299. $createdDate = date('Y-m-d', strtotime($record->created_at));
  1300. $today = date('Y-m-d');
  1301. $daysPassed = floor((strtotime($today) - strtotime($createdDate)) / 86400);
  1302. // 检查是否到了这一天:第day天的奖励只能在充值后的第day天领取(daysPassed == day)
  1303. if ($daysPassed < $day) {
  1304. return apiReturnFail(['web.gift.vip_inactive_day_not_time', str_replace(':day', $day, __('web.gift.vip_inactive_day_not_time'))]);
  1305. }
  1306. // 检查是否已过期:如果已经过了这一天(daysPassed > day),则不能领取
  1307. if ($daysPassed > $day) {
  1308. return apiReturnFail(['web.gift.vip_inactive_day_expired', str_replace(':day', $day, __('web.gift.vip_inactive_day_expired'))]);
  1309. }
  1310. // 第4-7天需要检查当天游戏流水 >= 100
  1311. if ($day >= 4) {
  1312. $targetDate = date('Ymd', strtotime($record->created_at . ' +' . $day . ' days'));
  1313. $todayBet = DB::table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  1314. ->where('UserID', $userId)
  1315. ->where('DataID', $targetDate)
  1316. ->value('TotalBet') ?? 0;
  1317. $betAmount = $todayBet / NumConfig::NUM_VALUE; // 转换为元
  1318. if ($betAmount < 100) {
  1319. return apiReturnFail(['web.gift.vip_inactive_bet_insufficient', str_replace(':amount', 100, __('web.gift.vip_inactive_bet_insufficient'))]);
  1320. }
  1321. }
  1322. $amount = (float)$record->per_day_amount;
  1323. try {
  1324. // 发放奖励
  1325. OuroGameService::AddScore($userId, $amount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
  1326. // 更新位标记
  1327. $newMask = $claimedMask | (1 << $dayIndex);
  1328. DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')
  1329. ->where('id', $record->id)
  1330. ->update([
  1331. 'claimed_days_mask' => $newMask,
  1332. 'updated_at' => date('Y-m-d H:i:s')
  1333. ]);
  1334. \Log::info('连续未充值VIP礼包奖励领取成功', [
  1335. 'user_id' => $userId,
  1336. 'day' => $day,
  1337. 'amount' => $amount
  1338. ]);
  1339. return apiReturnSuc([
  1340. 'amount' => $amount,
  1341. 'day' => $day,
  1342. 'message' => str_replace(':amount', $amount, __('web.gift.claim_success'))
  1343. ]);
  1344. } catch (\Exception $e) {
  1345. \Log::error('连续未充值VIP礼包奖励领取失败', [
  1346. 'user_id' => $userId,
  1347. 'day' => $day,
  1348. 'error' => $e->getMessage()
  1349. ]);
  1350. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  1351. }
  1352. }
  1353. }