WebRouteController.php 29 KB

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