WebRouteController.php 29 KB

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