WebRouteController.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. $user = GlobalUserInfo::toWebData($userModel);
  221. if ($today->gte($registerDate->copy()->addDays(3)) && $user['vip'] > 0) {
  222. $sharePop = 1;
  223. } else if ($user['vip'] == 0 && time() > strtotime($userModel->RegisterDate) + 1800) {
  224. $sharePop = 1;
  225. }
  226. }
  227. }
  228. $spe_key=$request->input('s_k', 0);
  229. $data['conf']=[
  230. 'hall'=>env("CONFIG_24680_HALL")??GameBasicConfig::$HallServer,
  231. 'DOLLAR'=>env("CONFIG_24680_DOLLAR")??GameBasicConfig::$DOLLAR,
  232. 'currency'=>env("CONFIG_24680_CURRENCY","USD"),
  233. 'promoteInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
  234. 'showInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
  235. 'guest'=>$guestOpen?1:0,
  236. 'AdjustToken' => $ChannelPackageName?$ChannelPackageName->AdjustToken:null,
  237. 'AdjustConfig' => $ChannelPackageName?$ChannelPackageName->AdjustConfig:null,
  238. 'upgradeBonus'=>$upgradeBonus,
  239. 'registerBonus' =>$registerBonus,
  240. 'recommendGame' => $recommendGame,
  241. 'LandscapeGames' => [962,963,964,965,966,967,972,973,974,975, 976, 977, 978, 979, 980, 982, 983,
  242. 962, 941, 942, 943, 945, 946, 947, 948, 949, 950, 951, 952, 953,
  243. 936, 938, 939,940,934],
  244. 'getStateToWhereRaw' =>RouteService::getStateToWhereRaw($request),
  245. // 'serviceLink' => $chat,
  246. 'serviceLink' => $chat?$chat->StatusString:'https://m.me/930365713484502',
  247. 'cs' => $servicelist,
  248. 'vipConfig' => VipService::getVipLevelConfig(),
  249. 'popWheel'=>0,
  250. 'firstBonus'=>$firstBonus,
  251. 'popFirst'=>$firstBonus,
  252. 'openRelief'=>$firstBonus,
  253. 'popBindPhone'=>1,
  254. 'popPwaBonus' => $popPwaBonus,
  255. 'jumplater' => $config->isFbJumpLater(),
  256. 'download'=>['light'=>$config->LightApk,'full'=>$config->FullApk,'bonus'=>$config->BONUS_PWA()],
  257. 'registerOpen'=>$config->RegOpen??env('CONFIG_REG_OPEN','sms,mail'),//id,phone,sms,mail,guest
  258. 'loginOpen'=>$config->LoginOpen??'id,phone,sms,mail,guest',
  259. 'slotsPartner' => $slotsPartner,
  260. 'outLimit' => ['cashapp' => 2000,'paypal' => 2000],
  261. 'withdrawChannel' => ['cashapp','paypal'],
  262. 'freeChannel' => ['paypal'],
  263. 'sharePop' => $sharePop,
  264. 's_k' => $this->quickLoad($spe_key, $user['UserID']??0, $FPID, $FF, $request->input('cookie', ''))??'',
  265. 'weight1234' => WeightConfigController::getConfig(),
  266. ];
  267. $data['conf']['pf']=['type'=>$config->PlatformName,'id'=>$config->PlatformID];
  268. // if (!$user){
  269. Util::WriteLog('routes_rs',[$data['conf']]);
  270. // }
  271. // $data['request']=$request->all();
  272. return response()->json($data);
  273. }
  274. public function getRegisterGold(Request $request)
  275. {
  276. try {
  277. $user = $request->user();
  278. $UserID = $user->UserID;
  279. if ($user->Registed == 1) {
  280. return apiReturnFail('Fail');
  281. }
  282. // 添加金币(10金币)
  283. $addResult = OuroGameService::AddScore($UserID, 10 * NumConfig::NUM_VALUE, null, false);
  284. // 更新 webgame.GlobalUserInfo 的 Registed 字段
  285. DB::connection('mysql')->table('webgame.GlobalUserInfo')
  286. ->where('UserID', $UserID)
  287. ->update(['Registed' => 1]);
  288. // 更新 QPAccountsDB.dbo.AccountsInfo 的 Registed 字段
  289. DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')
  290. ->where('UserID', $UserID)
  291. ->update(['Registed' => 1]);
  292. return apiReturnSuc([
  293. 'user' => [
  294. 'InsureScore' => 10,
  295. 'Registed' => 1,
  296. 'message' => 'Success'
  297. ]
  298. ]);
  299. } catch (\Exception $e) {
  300. \Log::error('注册送金币失败:' . $e->getMessage(), [
  301. 'UserID' => $UserID ?? 0,
  302. 'trace' => $e->getTraceAsString()
  303. ]);
  304. return apiReturnFail('领取失败:' . $e->getMessage());
  305. }
  306. }
  307. public function log(Request $request)
  308. {
  309. Util::writeLog("gamelog", [
  310. 'user' => $request->user(),
  311. 'request' => $request->all()
  312. ]);
  313. return apiReturnSuc();
  314. }
  315. public function checkApkInstall(Request $request)
  316. {
  317. $user = $request->user();
  318. $FPID = $request->input("bfp", "");
  319. $ff = $request->input('ff', '');
  320. $url_sign = $request->input('us', RouteService::getChannel($request));
  321. $UserID = $user ? $user->UserID : "";
  322. $ip = $request->ip();
  323. $agent = $request->userAgent();
  324. $alen = strlen($agent);
  325. $key = "apktmp_{$url_sign}_$ip";
  326. Util::writeLog("apkload", [
  327. 'FPID' => $FPID,
  328. 'FF' => $ff,
  329. 'url_sign' => $url_sign,
  330. 'user' => $user,
  331. 'ip' => IpLocation::getRealIp(),
  332. 'agent' => $agent,
  333. 'req' => $request->all()
  334. ]);
  335. $agent = explode('AppleWebKit', $agent)[0];
  336. //截取到最后一个分号Mozilla/5.0 (Linux; Android 16; SM-S936U Build/BP2A.250605.031.A3; wv) 去掉了wv和后面
  337. $lastSemicolon = strrpos($agent, ';');
  338. if ($lastSemicolon !== false) {
  339. $agent = substr($agent, 0, $lastSemicolon);
  340. }
  341. $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $request->input('cookie', ''));
  342. if ($cookieExist && is_array($cookieExist)) {
  343. $data = [];
  344. $data['cookie'] = $cookieExist['Cookie'] ?? "";
  345. $data['params'] = $cookieExist['Params'] ?? "";
  346. $data['ls'] = $cookieExist['LocalStorage'] ?? "";
  347. $data['us'] = $cookieExist['UrlSign'] ?? "";
  348. $data['type'] = $cookieExist['Platform'] ?? "";
  349. $data['agent'] = $cookieExist['ClickUA'] ?? "";
  350. $data['origin'] = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  351. Util::writeLog("apkload", "existUser:::" . json_encode($data));
  352. return apiReturnSuc($data);
  353. }
  354. $datas = [];
  355. if (Redis::exists($key)) {
  356. $datas = json_decode(Redis::get($key), true);
  357. //规则1,只有一个数据,直接归1
  358. if (count($datas) == 1) {
  359. Redis::del($key);
  360. ApkService::saveCookie($UserID, $datas[0], $FPID, $ff);
  361. Util::writeLog("apkload", "onlyone:::" . json_encode($datas[0]));
  362. return apiReturnSuc($datas[0]);
  363. }
  364. Util::WriteLog("apkload", $datas);
  365. foreach ($datas as $k => $v) {
  366. if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
  367. array_splice($datas, $k, 1);
  368. Redis::set($key, json_encode($datas));
  369. Redis::expire($key, 7200);
  370. ApkService::saveCookie($UserID, $v, $FPID, $ff);
  371. Util::writeLog("apkload", "sameagent:::" . json_encode($v));
  372. return apiReturnSuc($v);
  373. }
  374. }
  375. }
  376. $recents = ApkService::getRecentsNew($url_sign);
  377. foreach ($recents as $v) {
  378. if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
  379. ApkService::saveCookie($UserID, $v, $FPID, $ff);
  380. Util::writeLog("apkload", "recent:::" . json_encode($v));
  381. return apiReturnSuc($v);
  382. }
  383. }
  384. return apiReturnFail("");
  385. }
  386. public function quickLoad($spe_key=null, $UserID=0, $FPID='', $FF='', $cookie='')
  387. {
  388. $data=null;
  389. $fbclid = ApkService::extractFbclid($cookie);
  390. if($spe_key){
  391. $key = "quick_{$spe_key}";
  392. if(Redis::exists($key)) {
  393. $data = json_decode(Redis::get($key), true);
  394. }
  395. }
  396. if(!$data){
  397. $table = TableName::QPAccountsDB() . "AccountCookie";
  398. $obj=null;
  399. if($spe_key) {
  400. $candidates = DB::table($table)->where('SPE_KEY', $spe_key)->orderBy('CreateTime', 'desc')->get();
  401. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  402. }
  403. if(!$obj && $UserID){
  404. $candidates = DB::table($table)->where('UserID', $UserID)->orderBy('CreateTime', 'desc')->get();
  405. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  406. }
  407. if(!$obj && (!empty($FPID) || !empty($FF))){
  408. $query = DB::table($table);
  409. if (!empty($FPID) && !empty($FF)) {
  410. $query->where(function ($q) use ($FPID, $FF) {
  411. $q->where('FPID', $FPID)->orWhere('FF', $FF);
  412. });
  413. } elseif (!empty($FPID)) {
  414. $query->where('FPID', $FPID);
  415. } else {
  416. $query->where('FF', $FF);
  417. }
  418. $candidates = $query->orderBy('CreateTime', 'desc')->get();
  419. $obj = ApkService::pickBestCandidate($candidates, $fbclid);
  420. }
  421. try {
  422. if(!$obj && !empty($fbclid)){
  423. $obj = DB::table($table)
  424. ->where('Cookie', 'like', '%' . $fbclid . '%')
  425. ->orderBy('CreateTime', 'desc')
  426. ->first();
  427. }
  428. }catch (\Exception $e) {
  429. Util::WriteLog('invalid_cookie',$fbclid);
  430. $obj = null;
  431. }
  432. if($obj){
  433. $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];
  434. }
  435. }
  436. return $data;
  437. }
  438. public function quickSave(Request $request)
  439. {
  440. $FPID = $request->input("bfp", "");
  441. $ff = $request->input('ff', '');
  442. $url_sign = RouteService::getChannel($request);
  443. $UserID =$request->user()?$request->user()->UserID:0;
  444. $ip = IpLocation::getRealIp();
  445. $agent = $request->userAgent();
  446. ///gg or fb
  447. $type = $request->get('type') ?? "fb";
  448. $cookie = $request->get('cookie') ?? '';
  449. $localStorage = $request->get('ls') ?? '';
  450. $params = $request->get('params') ?? '';
  451. $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  452. $time = time();
  453. $spe_key = $request->input('s_k',0);
  454. if(!$spe_key)$spe_key=$this->md5Base62($cookie . $localStorage . $params);
  455. $locale = $request->get('locale') ?? '';
  456. $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');
  457. $key = "quick_{$spe_key}";
  458. if (Redis::exists($key)) {
  459. $cached = json_decode(Redis::get($key), true);
  460. if (is_array($cached)) {
  461. $data = $this->mergeQuickData($cached, $data);
  462. }
  463. }
  464. ApkService::saveCookie($UserID, $data, $FPID, $ff,$spe_key);
  465. Redis::set($key, json_encode($data));
  466. Redis::expire($key, 7200);
  467. Util::WriteLog("saveQuick", $data);
  468. return apiReturnSuc(['s_k'=>$spe_key]);
  469. }
  470. public function saveEnv(Request $request)
  471. {
  472. $user = $request->user();
  473. $FPID = $request->input("bfp", "");
  474. $ff = $request->input('ff', '');
  475. $url_sign = $request->input('us', RouteService::getChannel($request));
  476. $UserID = $user ? $user->UserID : "";
  477. $ip = IpLocation::getRealIp();
  478. $agent = $request->userAgent();
  479. $alen = strlen($agent);
  480. $key = "apktmp_{$url_sign}_$ip";
  481. ///gg or fb
  482. $type = $request->get('type') ?? "fb";
  483. $cookie = $request->get('cookie') ?? '';
  484. $localStorage = $request->get('ls') ?? '';
  485. $params = $request->get('params') ?? '';
  486. $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
  487. $time = time();
  488. $locale = $request->get('locale') ?? '';
  489. $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');
  490. $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $cookie);
  491. if (!$cookieExist) {
  492. ApkService::saveCookie($UserID, $data, $FPID, $ff);
  493. $key = "apktmp_{$url_sign}_$ip";
  494. $datas = [];
  495. if (Redis::exists($key)) {
  496. $datas = json_decode(Redis::get($key), true);
  497. //防止重复压入
  498. foreach ($datas as $v) {
  499. if ($data['agent'] == $v['agent'] && $data['type'] == $v['type']) {
  500. return apiReturnSuc(1);
  501. }
  502. }
  503. }
  504. array_unshift($datas, $data);
  505. Redis::set($key, json_encode($datas));
  506. Redis::expire($key, 7200);
  507. //压入最近记录
  508. ApkService::addRecentsNew($data, $url_sign);
  509. //写入快手
  510. if ($type == 'kw') {
  511. ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_DOWNLOAD']);
  512. }
  513. Util::WriteLog("saveEnv", $data);
  514. }
  515. return apiReturnSuc(1);
  516. }
  517. private function mergeQuickData(array $cached, array $current)
  518. {
  519. $merged = $cached;
  520. foreach ($current as $k => $v) {
  521. if ($k === 'cookie' || $k === 'params') {
  522. continue;
  523. }
  524. if ($v !== '' && $v !== null) {
  525. $merged[$k] = $v;
  526. }
  527. }
  528. $merged['cookie'] = $this->mergeCookieString($cached['cookie'] ?? '', $current['cookie'] ?? '');
  529. $merged['params'] = $this->mergeParamsString($cached['params'] ?? '', $current['params'] ?? '');
  530. return $merged;
  531. }
  532. private function mergeParamsString($cached, $current)
  533. {
  534. if ($cached === '') return $current;
  535. if ($current === '') return $cached;
  536. $cachedJson = json_decode($cached, true);
  537. $currentJson = json_decode($current, true);
  538. if (is_array($cachedJson) && is_array($currentJson)) {
  539. return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
  540. }
  541. $cachedArr = [];
  542. $currentArr = [];
  543. parse_str($cached, $cachedArr);
  544. parse_str($current, $currentArr);
  545. if (!empty($cachedArr) || !empty($currentArr)) {
  546. return http_build_query(array_replace($cachedArr, $currentArr));
  547. }
  548. if ($cached === $current) return $current;
  549. return $cached . '&' . $current;
  550. }
  551. private function mergeCookieString($cached, $current)
  552. {
  553. if ($cached === '') return $current;
  554. if ($current === '') return $cached;
  555. $cachedJson = json_decode($cached, true);
  556. $currentJson = json_decode($current, true);
  557. if (is_array($cachedJson) && is_array($currentJson)) {
  558. return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
  559. }
  560. $cookies = $this->parseCookiePairs($cached);
  561. $newCookies = $this->parseCookiePairs($current);
  562. if (!empty($cookies) || !empty($newCookies)) {
  563. $cookies = array_replace($cookies, $newCookies);
  564. $cookieParts = [];
  565. foreach ($cookies as $k => $v) {
  566. $cookieParts[] = $k . '=' . $v;
  567. }
  568. return implode('; ', $cookieParts);
  569. }
  570. if ($cached === $current) return $current;
  571. return $cached . '; ' . $current;
  572. }
  573. private function parseCookiePairs($cookieStr)
  574. {
  575. $pairs = [];
  576. foreach (explode(';', $cookieStr) as $segment) {
  577. $segment = trim($segment);
  578. if ($segment === '') {
  579. continue;
  580. }
  581. $pos = strpos($segment, '=');
  582. if ($pos === false) {
  583. continue;
  584. }
  585. $name = trim(substr($segment, 0, $pos));
  586. $value = trim(substr($segment, $pos + 1));
  587. if ($name !== '') {
  588. $pairs[$name] = $value;
  589. }
  590. }
  591. return $pairs;
  592. }
  593. /**
  594. * 环境短 key:MD5 二进制取前 6 字节(48bit)再 base62,长度 <=9(10 字符以内)。
  595. * PHP 对齐示例:$b = substr(md5($value, true), 0, 6); 再对 $b 做相同 base62 循环。
  596. */
  597. private function md5Base62($value)
  598. {
  599. $b = substr(md5($value, true), 0, 6);
  600. $bytes = array_values(unpack('C*', $b));
  601. $alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  602. $result = '';
  603. while (!empty($bytes)) {
  604. $quotient = [];
  605. $remainder = 0;
  606. foreach ($bytes as $byte) {
  607. $acc = ($remainder << 8) + $byte;
  608. $q = intdiv($acc, 62);
  609. $remainder = $acc % 62;
  610. if (!empty($quotient) || $q !== 0) {
  611. $quotient[] = $q;
  612. }
  613. }
  614. $result = $alphabet[$remainder] . $result;
  615. $bytes = $quotient;
  616. }
  617. return $result === '' ? '0' : $result;
  618. }
  619. public function SaveRoutes(Request $request)
  620. {
  621. // Assuming $jsonData is your JSON data
  622. $jsonData = json_decode(file_get_contents('path_to_your_json_file.json'), true);
  623. foreach ($jsonData['data'] as $routeData) {
  624. $this->insertRoute($routeData);
  625. }
  626. }
  627. function insertRoute($routeData, $parentId = null)
  628. {
  629. $route = new RouteModel([
  630. 'parent_id' => $parentId,
  631. 'path' => $routeData['path'],
  632. 'type' => $routeData['type'],
  633. 'side' => $routeData['side'],
  634. 'block' => $routeData['block'],
  635. 'title' => $routeData['title'],
  636. 'icon' => $routeData['icon'],
  637. 'fill' => $routeData['fill'],
  638. 'component' => $routeData['component'],
  639. 'query' => $routeData['query'],
  640. 'login' => $routeData['login'],
  641. 'lpath' => $routeData['lpath']
  642. ]);
  643. $route->save();
  644. foreach ($routeData['subs'] as $sub) {
  645. $this->insertRoute($sub, $route->id);
  646. }
  647. }
  648. public function testScoreChange(Request $request)
  649. {
  650. $user = $request->user();
  651. $nowGolds = $request->input("nowGolds", 4000);
  652. $AddNum = $request->input("AddNum", 1000);
  653. // notifyWebHall($UserID,"",'pay_finish',["Golds"=>$NowScore,"PayNum"=>$GiftScore]);
  654. OuroGameService::notifyWebHall($user->UserID, "", 'call_client', ["Golds" => $nowGolds, "AddNum" => $AddNum, "type" => "start_change"]);
  655. // ($user_id,$GlobalUID,'call_client',["type"=>"refresh_mail"]);
  656. return apiReturnSuc("");
  657. }
  658. }