WebRouteController.php 28 KB

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