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