WebRouteController.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. <?php
  2. namespace App\Http\Controllers\Game;
  3. use App\Facade\TableName;
  4. use App\Game\Block;
  5. use App\Game\Config\GameBasicConfig;
  6. use App\Services\GoogleRedirectH5BonusService;
  7. use Carbon\Carbon;
  8. use App\Game\GameCard;
  9. use App\Game\GlobalUserInfo;
  10. use App\Game\Route;
  11. use App\Game\RouteModel;
  12. use App\Game\Services\BetbyService;
  13. use App\Game\Services\BetbyTestService;
  14. use App\Game\Services\OuroGameService;
  15. use App\Game\Services\RouteService;
  16. use App\Game\Services\TelegramAppService;
  17. use App\Game\Style;
  18. use App\Game\WebChannelConfig;
  19. use App\Game\WebRegionConfig;
  20. use App\Http\Controllers\Api\ApiController;
  21. use App\Http\Controllers\Api\WeightConfigController;
  22. use App\Http\Controllers\Controller;
  23. use App\Http\helper\NumConfig;
  24. use App\IpLocation;
  25. use App\Models\AccountsInfo;
  26. use App\Models\AccountLoginDomain;
  27. use App\Models\RouteMailConfig;
  28. use App\Models\SystemStatusInfo;
  29. use App\Jobs\IpRiskDetection;
  30. use App\Services\ApkService;
  31. use App\Services\VipService;
  32. use App\Util;
  33. use Illuminate\Http\Request;
  34. use Illuminate\Support\Facades\DB;
  35. use Illuminate\Support\Facades\Redis;
  36. // use Yansongda\Pay\Log;
  37. class WebRouteController extends Controller
  38. {
  39. protected $routeService;
  40. public function __construct(RouteService $routeService)
  41. {
  42. $this->routeService = $routeService;
  43. }
  44. private function recordLoginDomain(Request $request, $userId, $channel = 0)
  45. {
  46. $origin = $request
  47. ? ($request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER') ?? '*')
  48. : ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*');
  49. try {
  50. AccountLoginDomain::record($userId, $origin, $channel);
  51. } catch (\Throwable $exception) {
  52. \Log::warning('record_login_origin_failed', [
  53. 'UserID' => $userId,
  54. 'origin' => $origin,
  55. 'channel' => $channel,
  56. 'message' => $exception->getMessage(),
  57. ]);
  58. }
  59. }
  60. public function Routes(Request $request)
  61. {
  62. GlobalUserInfo::UpdateLoginDate($request, true);
  63. $FPID = $request->input("bfp", "");
  64. $inApp = $request->input('ia', 0);
  65. // 仅加载顶层路由,并预加载所有嵌套子路由
  66. $routes = RouteModel::whereNull('parent_id')
  67. ->whereRaw(RouteService::getStateToWhereRaw($request))
  68. ->with('subs.subs.subs') // 根据实际层级深度调整
  69. ->orderBy('index')
  70. ->get();
  71. $styles = Style::all();
  72. $blocks = Block::all();
  73. $config = RouteService::getChannelConfig($request);
  74. $guestOpen = $config->isGuestOpen();
  75. $disablePromote = $config->isDisablePromote();
  76. //在fb内,节省时间,不快速注册
  77. //if($inApp)$guestOpen=false;
  78. $upgradeBonus = intval($config->BONUS_VERIFY_PHONE());
  79. if ($guestOpen && !$upgradeBonus) {
  80. //游客模式打开,随时可以登录
  81. $upgradeBonus = SystemStatusInfo::OnlyGetCacheValue('BindPhoneReward') ?? 500;
  82. }
  83. $user = GlobalUserInfo::$me;//LoginController::checkLogin($request);
  84. if ($user) {
  85. $this->recordLoginDomain($request, $user->UserID ?? 0, $user->Channel ?? 0);
  86. RouteMailConfig::sendPendingForUser($user->UserID ?? 0);
  87. $ua = $request->userAgent();
  88. if (stripos($ua, 'iPhone') !== false) {
  89. $mobileBand = 'iPhone';
  90. } else if (stripos($ua, 'iPad') !== false) {
  91. $mobileBand = 'iPad';
  92. } else if (stripos($ua, 'Android') !== false) {
  93. $mobileBand = 'Android';
  94. } else if (stripos($ua, 'Windows') !== false) {
  95. $mobileBand = 'PC';
  96. } else if (stripos($ua, 'Mac') !== false) {
  97. $mobileBand = 'Mac';
  98. }
  99. if (isset($mobileBand)) {
  100. AccountsInfo::saveMobileBand($user->UserID, $mobileBand);
  101. }
  102. }
  103. $hashadd = $request->input("hashadd", "");
  104. $isreg = 0;
  105. if (!empty($hashadd)) {
  106. try {
  107. $hashadd = json_decode($hashadd, true);
  108. if ($hashadd['type'] == 'tele') {
  109. $teleUser = TelegramAppService::decodeHash($hashadd['data']);
  110. if (intval($teleUser->UserID)) {
  111. if (!$user || $user->UserID != $teleUser->UserID) {
  112. $user = GlobalUserInfo::getGameUserInfo('UserID', $teleUser->UserID);
  113. }
  114. } else {
  115. //不存在用户
  116. if (!$user) {
  117. $guestUser = (new LoginController())->registerUser($request, true);
  118. if (!is_array($guestUser)) {
  119. $guestUser->NickName = $teleUser->first_name;
  120. $guestUser->save();
  121. $isreg = 1;
  122. $user = $guestUser;
  123. }
  124. }
  125. if ($user) {
  126. //绑定现有用户
  127. $teleUser->UserID = $user->UserID;
  128. $teleUser->GlobalUID = $user->GlobalUID;
  129. $teleUser->save();
  130. }
  131. }
  132. }
  133. } catch (\Exception $e) {
  134. }
  135. }
  136. if (!$user) {
  137. $loginController = new LoginController();
  138. //游客模式打开,随时可以登录
  139. $user = $loginController->getUserByFPID($FPID);
  140. // if (!$user) {
  141. // $user = $loginController->registerUser($request, true);
  142. // }
  143. }
  144. $FF=$request->input('ff', '');
  145. $isPWA=$request->input('pwa', 0);
  146. $urlvars=json_decode($request->input('urlvars',''));
  147. if(!$user&&!empty($FF)&&$isPWA){
  148. $user=GlobalUserInfo::GetRecentLogin($request);
  149. }
  150. //转换成web数据
  151. //转换成web数据
  152. if ($user){
  153. // 异步派发 IP 风险检测
  154. $userId = $user->UserID ?? 0;
  155. $ip = IpLocation::getRealIp();
  156. if ($ip && $userId) {
  157. IpRiskDetection::dispatch($userId, $ip);
  158. }
  159. $user = GlobalUserInfo::toWebData($user);
  160. $config=WebChannelConfig::getByChannel($user['Channel']);
  161. } else{
  162. Util::WriteLog('routes_params',[$request]);
  163. }
  164. $data=['code'=>0,'data'=>$routes,'blocks'=>$blocks,'styles'=>$styles,'user'=>$user];
  165. $origin = $request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER')?? '*';
  166. $data['origin']=$origin;
  167. $isDesktop=($request->input('_d','m')=='d');
  168. $firstBonus=1;
  169. if(env('CONFIG_24680_NFTD_99',0)==0)if($config->Channel==99)$firstBonus=0;
  170. $registerBonus = SystemStatusInfo::OnlyGetCacheValue('GrantScoreCountNew') ?? 1000;
  171. $chat = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
  172. ->where('StatusName', 'Telegram')
  173. ->first();
  174. $servicelist = (new ApiController())->getServiceList();
  175. // $chat = "https://m.me/930365713484502";
  176. // 默认推荐游戏
  177. $defaultGameId = 931;
  178. $recommendGame = '/game/' . $defaultGameId;
  179. $popPwaBonus=$user?(Redis::get('pwa_bonus:'.$user['UserID'])??0):0;
  180. $ChannelPackageName = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$config->Channel??100)
  181. ->first();
  182. // slotsPartner: 与 WebChannelConfig 通过 RegionID 关联且 RegionID 不为空的区域,且当前 $config 的 Channel 不在该区域的 BindChannels 中(即其他“伙伴”区域)
  183. // $currentChannel = $config->Channel;
  184. // $slotsPartner = WebRegionConfig::query()
  185. // ->where('RegionID', '!=', '')
  186. // ->whereIn('RegionID', function ($q) use ($currentChannel) {
  187. // $q->select('RegionID')
  188. // ->from((new WebChannelConfig())->getTable())
  189. // ->where('RegionID', '!=', '')
  190. // ->where('Channel', '!=', $currentChannel);
  191. // })
  192. // ->get()
  193. //// ->filter(function ($region) use ($currentChannel) {
  194. //// $bindChannels = $region->BindChannels;
  195. //// return !is_array($bindChannels) || !in_array((int)$currentChannel, $bindChannels);
  196. //// })
  197. // ->map(function ($region) {
  198. // return [
  199. // 'DomainUrl' => $region->DomainUrl ?? '',
  200. // 'LogoUrl' => $region->LogoUrl ?? '',
  201. // 'GameDesc' => $region->GameDesc ?? '',
  202. // ];
  203. // })
  204. // ->values()
  205. // ->all();
  206. $GroupID=0;
  207. $RegionID = $request ? $request->input('regionid', '') : ($_REQUEST['regionid'] ?? '');
  208. if (empty($RegionID) && !empty($origin)) {
  209. $RegionID = explode('.', $origin)[str_starts_with($origin, 'www') ? 1 : 0];
  210. }
  211. if(!empty($RegionID)){
  212. $GroupID=WebRegionConfig::query()->where('RegionID',$RegionID)->value('GroupID')??0;
  213. }
  214. // slotsPartner: 与 WebChannelConfig 通过 RegionID 关联且 RegionID 不为空的区域,且当前 $config 的 Channel 不在该区域的 BindChannels 中(即其他“伙伴”区域)
  215. // $currentChannel = $config->Channel;
  216. $slotsPartner = WebRegionConfig::query()
  217. ->where('GroupID', $GroupID)
  218. ->whereIn('RegionID', function ($q) {
  219. $q->select('RegionID')
  220. ->from((new WebChannelConfig())->getTable())
  221. ->where('RegionID', '!=', '');
  222. })
  223. ->get()
  224. ->map(function ($region) {
  225. return [
  226. 'DomainUrl' => $region->DomainUrl ?? '',
  227. 'LogoUrl' => $region->LogoUrl ?? '',
  228. 'GameDesc' => $region->GameDesc ?? '',
  229. 'SC' => $region->SuggestChannel ?? '',
  230. ];
  231. })
  232. ->values()
  233. ->all();
  234. // sharePop:用户注册日起满 3 个自然日后开始弹(例:1 日注册则 4 日及以后满足)
  235. $sharePop = 0;
  236. if ($user && isset($user['UserID'])) {
  237. $userModel = GlobalUserInfo::getGameUserInfo('UserID', $user['UserID']);
  238. if ($userModel && $userModel->RegisterDate) {
  239. $registerDate = Carbon::parse($userModel->RegisterDate)->startOfDay();
  240. $today = Carbon::today();
  241. $user = GlobalUserInfo::toWebData($userModel);
  242. if ($today->gte($registerDate->copy()->addDays(3)) && $user['vip'] > 0) {
  243. $sharePop = 1;
  244. } else if ($user['vip'] == 0 && time() > strtotime($userModel->RegisterDate) + 1800) {
  245. $sharePop = 1;
  246. }
  247. }
  248. }
  249. $spe_key=$request->input('s_k', 0);
  250. $googleRedirectH5Bonus = GoogleRedirectH5BonusService::routePayload(
  251. $user['UserID'] ?? 0,
  252. $spe_key,
  253. $config->BONUS_PWA()
  254. );
  255. $data['conf']=[
  256. 'hall'=>env("CONFIG_24680_HALL")??GameBasicConfig::$HallServer,
  257. 'DOLLAR'=>env("CONFIG_24680_DOLLAR")??GameBasicConfig::$DOLLAR,
  258. 'currency'=>env("CONFIG_24680_CURRENCY","USD"),
  259. 'promoteInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
  260. 'showInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
  261. 'guest'=>$guestOpen?1:0,
  262. 'AdjustToken' => $ChannelPackageName?$ChannelPackageName->AdjustToken:null,
  263. 'AdjustConfig' => $ChannelPackageName?$ChannelPackageName->AdjustConfig:null,
  264. 'upgradeBonus'=>$upgradeBonus,
  265. 'registerBonus' =>$registerBonus,
  266. 'recommendGame' => $recommendGame,
  267. 'LandscapeGames' => [962,963,964,965,966,967,972,973,974,975, 976, 977, 978, 979, 980, 982, 983,
  268. 962, 941, 942, 943, 945, 946, 947, 948, 949, 950, 951, 952, 953,
  269. 936, 938, 939,940,934],
  270. 'getStateToWhereRaw' =>RouteService::getStateToWhereRaw($request),
  271. // 'serviceLink' => $chat,
  272. 'serviceLink' => $chat?$chat->StatusString:'https://m.me/930365713484502',
  273. 'cs' => $servicelist,
  274. 'vipConfig' => VipService::getVipLevelConfig(),
  275. 'popWheel'=>0,
  276. 'firstBonus'=>$firstBonus,
  277. 'popFirst'=>$firstBonus,
  278. 'openRelief'=>$firstBonus,
  279. 'popBindPhone'=>1,
  280. 'popPwaBonus' => $popPwaBonus,
  281. 'jumplater' => $config->isFbJumpLater(),
  282. 'jumpapk' => $config->isApkJump(),
  283. 'download'=>['light'=>$config->LightApk,'full'=>$config->FullApk,'bonus'=>$config->BONUS_PWA()],
  284. 'registerOpen'=>$config->RegOpen??env('CONFIG_REG_OPEN','sms,mail'),//id,phone,sms,mail,guest
  285. 'loginOpen'=>$config->LoginOpen??'id,phone,sms,mail,guest',
  286. 'slotsPartner' => $slotsPartner,
  287. 'outLimit' => ['cashapp' => 2000,'paypal' => 2000],
  288. 'withdrawChannel' => ['cashapp','paypal'],
  289. 'freeChannel' => ['paypal'],
  290. 'sharePop' => $sharePop,
  291. 's_k' => $this->quickLoad($spe_key, $user['UserID']??0, $FPID, $FF, $request->input('cookie', ''))??'',
  292. 'weight1234' => WeightConfigController::getConfig(),
  293. 'googleRedirectH5Bonus' => $googleRedirectH5Bonus,
  294. ];
  295. $data['conf']['pf']=['type'=>$config->PlatformName,'id'=>$config->PlatformID];
  296. // if (!$user){
  297. Util::WriteLog('routes_rs',[$data['conf']]);
  298. // }
  299. // $data['request']=$request->all();
  300. return response()->json($data);
  301. }
  302. public function getRegisterGold(Request $request)
  303. {
  304. try {
  305. $user = $request->user();
  306. $UserID = $user->UserID;
  307. if ($user->Registed == 1) {
  308. return apiReturnFail('Fail');
  309. }
  310. // 添加金币(10金币)
  311. $addResult = OuroGameService::AddScore($UserID, 10 * NumConfig::NUM_VALUE, null, false);
  312. // 更新 webgame.GlobalUserInfo 的 Registed 字段
  313. DB::connection('mysql')->table('webgame.GlobalUserInfo')
  314. ->where('UserID', $UserID)
  315. ->update(['Registed' => 1]);
  316. // 更新 QPAccountsDB.dbo.AccountsInfo 的 Registed 字段
  317. DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')
  318. ->where('UserID', $UserID)
  319. ->update(['Registed' => 1]);
  320. return apiReturnSuc([
  321. 'user' => [
  322. 'InsureScore' => 10,
  323. 'Registed' => 1,
  324. 'message' => 'Success'
  325. ]
  326. ]);
  327. } catch (\Exception $e) {
  328. \Log::error('注册送金币失败:' . $e->getMessage(), [
  329. 'UserID' => $UserID ?? 0,
  330. 'trace' => $e->getTraceAsString()
  331. ]);
  332. return apiReturnFail('领取失败:' . $e->getMessage());
  333. }
  334. }
  335. public function log(Request $request)
  336. {
  337. Util::writeLog("gamelog", [
  338. 'user' => $request->user(),
  339. 'request' => $request->all()
  340. ]);
  341. return apiReturnSuc();
  342. }
  343. public function checkApkInstall(Request $request)
  344. {
  345. $user = $request->user();
  346. $FPID = $request->input("bfp", "");
  347. $ff = $request->input('ff', '');
  348. $url_sign = $request->input('us', RouteService::getChannel($request));
  349. $UserID = $user ? $user->UserID : "";
  350. $ip = $request->ip();
  351. $agent = $request->userAgent();
  352. $alen = strlen($agent);
  353. $key = "apktmp_{$url_sign}_$ip";
  354. Util::writeLog("apkload", [
  355. 'FPID' => $FPID,
  356. 'FF' => $ff,
  357. 'url_sign' => $url_sign,
  358. 'user' => $user,
  359. 'ip' => IpLocation::getRealIp(),
  360. 'agent' => $agent,
  361. 'req' => $request->all()
  362. ]);
  363. $agent = explode('AppleWebKit', $agent)[0];
  364. //截取到最后一个分号Mozilla/5.0 (Linux; Android 16; SM-S936U Build/BP2A.250605.031.A3; wv) 去掉了wv和后面
  365. $lastSemicolon = strrpos($agent, ';');
  366. if ($lastSemicolon !== false) {
  367. $agent = substr($agent, 0, $lastSemicolon);
  368. }
  369. $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $request->input('cookie', ''));
  370. if ($cookieExist && is_array($cookieExist)) {
  371. $data = [];
  372. $data['cookie'] = $cookieExist['Cookie'] ?? "";
  373. $data['params'] = $cookieExist['Params'] ?? "";
  374. $data['ls'] = $cookieExist['LocalStorage'] ?? "";
  375. $data['us'] = $cookieExist['UrlSign'] ?? "";
  376. $data['type'] = $cookieExist['Platform'] ?? "";
  377. $data['agent'] = $cookieExist['ClickUA'] ?? "";
  378. $data['origin'] = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  379. Util::writeLog("apkload", "existUser:::" . json_encode($data));
  380. return apiReturnSuc($data);
  381. }
  382. $datas = [];
  383. if (Redis::exists($key)) {
  384. $datas = json_decode(Redis::get($key), true);
  385. //规则1,只有一个数据,直接归1
  386. if (count($datas) == 1) {
  387. Redis::del($key);
  388. ApkService::saveCookie($UserID, $datas[0], $FPID, $ff);
  389. Util::writeLog("apkload", "onlyone:::" . json_encode($datas[0]));
  390. return apiReturnSuc($datas[0]);
  391. }
  392. Util::WriteLog("apkload", $datas);
  393. foreach ($datas as $k => $v) {
  394. if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
  395. array_splice($datas, $k, 1);
  396. Redis::set($key, json_encode($datas));
  397. Redis::expire($key, 7200);
  398. ApkService::saveCookie($UserID, $v, $FPID, $ff);
  399. Util::writeLog("apkload", "sameagent:::" . json_encode($v));
  400. return apiReturnSuc($v);
  401. }
  402. }
  403. }
  404. $recents = ApkService::getRecentsNew($url_sign);
  405. foreach ($recents as $v) {
  406. if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
  407. ApkService::saveCookie($UserID, $v, $FPID, $ff);
  408. Util::writeLog("apkload", "recent:::" . json_encode($v));
  409. return apiReturnSuc($v);
  410. }
  411. }
  412. return apiReturnFail("");
  413. }
  414. public function quickLoad($spe_key=null, $UserID=0, $FPID='', $FF='', $cookie='')
  415. {
  416. $data=null;
  417. $fbclid = ApkService::extractFbclid($cookie);
  418. if($spe_key){
  419. $key = "quick_{$spe_key}";
  420. if(Redis::exists($key)) {
  421. $data = json_decode(Redis::get($key), true);
  422. }
  423. }
  424. if(!$data){
  425. $table = TableName::QPAccountsDB() . "AccountCookie";
  426. $obj=null;
  427. if($spe_key) {
  428. $candidates = DB::table($table)->where('SPE_KEY', $spe_key)->orderBy('CreateTime', 'desc')->get();
  429. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  430. }
  431. if(!$obj && $UserID){
  432. $candidates = DB::table($table)->where('UserID', $UserID)->orderBy('CreateTime', 'desc')->get();
  433. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  434. }
  435. if(!$obj && (!empty($FPID) || !empty($FF))){
  436. $query = DB::table($table);
  437. if (!empty($FPID) && !empty($FF)) {
  438. $query->where(function ($q) use ($FPID, $FF) {
  439. $q->where('FPID', $FPID)->orWhere('FF', $FF);
  440. });
  441. } elseif (!empty($FPID)) {
  442. $query->where('FPID', $FPID);
  443. } else {
  444. $query->where('FF', $FF);
  445. }
  446. $candidates = $query->orderBy('CreateTime', 'desc')->get();
  447. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  448. }
  449. try {
  450. if(!$obj && !empty($fbclid)){
  451. $obj = DB::table($table)
  452. ->where('Cookie', 'like', '%' . $fbclid . '%')
  453. ->orderBy('CreateTime', 'desc')
  454. ->first();
  455. }
  456. }catch (\Exception $e) {
  457. Util::WriteLog('invalid_cookie',$fbclid);
  458. $obj = null;
  459. }
  460. if($obj){
  461. $data=['type'=>$obj->Platform,'cookie'=>$obj->Cookie,'s_k'=>$obj->SPE_KEY, 'url_sign'=>$obj->UrlSign, 'params'=>$obj->Params, 'ff'=>$obj->FF, 'localStorage'=>$obj->LocalStorage];
  462. }
  463. }
  464. return $data;
  465. }
  466. public function quickSave(Request $request)
  467. {
  468. $FPID = $request->input("bfp", "");
  469. $ff = $request->input('ff', '');
  470. $url_sign = RouteService::getChannel($request);
  471. $UserID =$request->user()?$request->user()->UserID:0;
  472. $ip = IpLocation::getRealIp();
  473. $agent = $request->userAgent();
  474. ///gg or fb
  475. $type = $request->get('type') ?? "fb";
  476. $cookie = $request->get('cookie') ?? '';
  477. $localStorage = $request->get('ls') ?? '';
  478. $params = $request->get('params') ?? '';
  479. $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  480. $time = time();
  481. $spe_key = $request->input('s_k',0);
  482. if(!$spe_key)$spe_key=$this->md5Base62($cookie . $localStorage . $params);
  483. $locale = $request->get('locale') ?? '';
  484. $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');
  485. $key = "quick_{$spe_key}";
  486. if (Redis::exists($key)) {
  487. $cached = json_decode(Redis::get($key), true);
  488. if (is_array($cached)) {
  489. $data = $this->mergeQuickData($cached, $data);
  490. }
  491. }
  492. ApkService::saveCookie($UserID, $data, $FPID, $ff,$spe_key);
  493. Redis::set($key, json_encode($data));
  494. Redis::expire($key, 7200);
  495. GoogleRedirectH5BonusService::recordPending($request, $UserID, $url_sign, $spe_key);
  496. Util::WriteLog("saveQuick", $data);
  497. return apiReturnSuc(['s_k'=>$spe_key]);
  498. }
  499. public function saveEnv(Request $request)
  500. {
  501. $user = $request->user();
  502. $FPID = $request->input("bfp", "");
  503. $ff = $request->input('ff', '');
  504. $url_sign = $request->input('us', RouteService::getChannel($request));
  505. $UserID = $user ? $user->UserID : "";
  506. $ip = IpLocation::getRealIp();
  507. $agent = $request->userAgent();
  508. $alen = strlen($agent);
  509. $key = "apktmp_{$url_sign}_$ip";
  510. ///gg or fb
  511. $type = $request->get('type') ?? "fb";
  512. $cookie = $request->get('cookie') ?? '';
  513. $localStorage = $request->get('ls') ?? '';
  514. $params = $request->get('params') ?? '';
  515. $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  516. $time = time();
  517. $locale = $request->get('locale') ?? '';
  518. $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');
  519. $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $cookie);
  520. if (!$cookieExist) {
  521. ApkService::saveCookie($UserID, $data, $FPID, $ff);
  522. $key = "apktmp_{$url_sign}_$ip";
  523. $datas = [];
  524. if (Redis::exists($key)) {
  525. $datas = json_decode(Redis::get($key), true);
  526. //防止重复压入
  527. foreach ($datas as $v) {
  528. if ($data['agent'] == $v['agent'] && $data['type'] == $v['type']) {
  529. return apiReturnSuc(1);
  530. }
  531. }
  532. }
  533. array_unshift($datas, $data);
  534. Redis::set($key, json_encode($datas));
  535. Redis::expire($key, 7200);
  536. //压入最近记录
  537. ApkService::addRecentsNew($data, $url_sign);
  538. //写入快手
  539. if ($type == 'kw') {
  540. ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_DOWNLOAD']);
  541. }
  542. Util::WriteLog("saveEnv", $data);
  543. }
  544. return apiReturnSuc(1);
  545. }
  546. private function mergeQuickData(array $cached, array $current)
  547. {
  548. $merged = $cached;
  549. foreach ($current as $k => $v) {
  550. if ($k === 'cookie' || $k === 'params') {
  551. continue;
  552. }
  553. if ($v !== '' && $v !== null) {
  554. $merged[$k] = $v;
  555. }
  556. }
  557. $merged['cookie'] = $this->mergeCookieString($cached['cookie'] ?? '', $current['cookie'] ?? '');
  558. $merged['params'] = $this->mergeParamsString($cached['params'] ?? '', $current['params'] ?? '');
  559. return $merged;
  560. }
  561. private function mergeParamsString($cached, $current)
  562. {
  563. if ($cached === '') return $current;
  564. if ($current === '') return $cached;
  565. $cachedJson = json_decode($cached, true);
  566. $currentJson = json_decode($current, true);
  567. if (is_array($cachedJson) && is_array($currentJson)) {
  568. return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
  569. }
  570. $cachedArr = [];
  571. $currentArr = [];
  572. parse_str($cached, $cachedArr);
  573. parse_str($current, $currentArr);
  574. if (!empty($cachedArr) || !empty($currentArr)) {
  575. return http_build_query(array_replace($cachedArr, $currentArr));
  576. }
  577. if ($cached === $current) return $current;
  578. return $cached . '&' . $current;
  579. }
  580. private function mergeCookieString($cached, $current)
  581. {
  582. if ($cached === '') return $current;
  583. if ($current === '') return $cached;
  584. $cachedJson = json_decode($cached, true);
  585. $currentJson = json_decode($current, true);
  586. if (is_array($cachedJson) && is_array($currentJson)) {
  587. return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
  588. }
  589. $cookies = $this->parseCookiePairs($cached);
  590. $newCookies = $this->parseCookiePairs($current);
  591. if (!empty($cookies) || !empty($newCookies)) {
  592. $cookies = array_replace($cookies, $newCookies);
  593. $cookieParts = [];
  594. foreach ($cookies as $k => $v) {
  595. $cookieParts[] = $k . '=' . $v;
  596. }
  597. return implode('; ', $cookieParts);
  598. }
  599. if ($cached === $current) return $current;
  600. return $cached . '; ' . $current;
  601. }
  602. private function parseCookiePairs($cookieStr)
  603. {
  604. $pairs = [];
  605. foreach (explode(';', $cookieStr) as $segment) {
  606. $segment = trim($segment);
  607. if ($segment === '') {
  608. continue;
  609. }
  610. $pos = strpos($segment, '=');
  611. if ($pos === false) {
  612. continue;
  613. }
  614. $name = trim(substr($segment, 0, $pos));
  615. $value = trim(substr($segment, $pos + 1));
  616. if ($name !== '') {
  617. $pairs[$name] = $value;
  618. }
  619. }
  620. return $pairs;
  621. }
  622. /**
  623. * 环境短 key:MD5 二进制取前 6 字节(48bit)再 base62,长度 <=9(10 字符以内)。
  624. * PHP 对齐示例:$b = substr(md5($value, true), 0, 6); 再对 $b 做相同 base62 循环。
  625. */
  626. private function md5Base62($value)
  627. {
  628. $b = substr(md5($value, true), 0, 6);
  629. $bytes = array_values(unpack('C*', $b));
  630. $alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  631. $result = '';
  632. while (!empty($bytes)) {
  633. $quotient = [];
  634. $remainder = 0;
  635. foreach ($bytes as $byte) {
  636. $acc = ($remainder << 8) + $byte;
  637. $q = intdiv($acc, 62);
  638. $remainder = $acc % 62;
  639. if (!empty($quotient) || $q !== 0) {
  640. $quotient[] = $q;
  641. }
  642. }
  643. $result = $alphabet[$remainder] . $result;
  644. $bytes = $quotient;
  645. }
  646. return $result === '' ? '0' : $result;
  647. }
  648. public function SaveRoutes(Request $request)
  649. {
  650. // Assuming $jsonData is your JSON data
  651. $jsonData = json_decode(file_get_contents('path_to_your_json_file.json'), true);
  652. foreach ($jsonData['data'] as $routeData) {
  653. $this->insertRoute($routeData);
  654. }
  655. }
  656. function insertRoute($routeData, $parentId = null)
  657. {
  658. $route = new RouteModel([
  659. 'parent_id' => $parentId,
  660. 'path' => $routeData['path'],
  661. 'type' => $routeData['type'],
  662. 'side' => $routeData['side'],
  663. 'block' => $routeData['block'],
  664. 'title' => $routeData['title'],
  665. 'icon' => $routeData['icon'],
  666. 'fill' => $routeData['fill'],
  667. 'component' => $routeData['component'],
  668. 'query' => $routeData['query'],
  669. 'login' => $routeData['login'],
  670. 'lpath' => $routeData['lpath']
  671. ]);
  672. $route->save();
  673. foreach ($routeData['subs'] as $sub) {
  674. $this->insertRoute($sub, $route->id);
  675. }
  676. }
  677. public function testScoreChange(Request $request)
  678. {
  679. $user = $request->user();
  680. $nowGolds = $request->input("nowGolds", 4000);
  681. $AddNum = $request->input("AddNum", 1000);
  682. // notifyWebHall($UserID,"",'pay_finish',["Golds"=>$NowScore,"PayNum"=>$GiftScore]);
  683. OuroGameService::notifyWebHall($user->UserID, "", 'call_client', ["Golds" => $nowGolds, "AddNum" => $AddNum, "type" => "start_change"]);
  684. // ($user_id,$GlobalUID,'call_client',["type"=>"refresh_mail"]);
  685. return apiReturnSuc("");
  686. }
  687. }