LoginController.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. <?php
  2. namespace App\Http\Controllers\Game;
  3. use App\Game\AgentLinks;
  4. use App\Game\GlobalUserInfo;
  5. use App\Game\QuickAccountPass;
  6. use App\Game\QuickAccountPassStore;
  7. use App\Game\RePayConfig;
  8. use App\Game\Services\AgentService;
  9. use App\Game\Services\OuroGameService;
  10. use App\Game\Services\RouteService;
  11. use App\Game\WebChannelConfig;
  12. use App\Http\Controllers\Controller;
  13. use App\Http\helper\NumConfig;
  14. use App\IpLocation;
  15. use App\Jobs\AfEvent;
  16. use App\Jobs\IpRiskDetection;
  17. use App\Models\Account\AccountPhone;
  18. use App\Models\AccountsInfo;
  19. use App\Models\GamePhoneVerityCode;
  20. use App\Models\PwaBonusLog;
  21. use App\Models\SystemStatusInfo;
  22. use App\Models\Treasure\GameScoreInfo;
  23. use App\Notification\TelegramBot;
  24. use App\Services\ApkService;
  25. use App\Services\StoredProcedure;
  26. use App\Services\VipService;
  27. use App\Util;
  28. use App\Utility\SetNXLock;
  29. use Carbon\Carbon;
  30. use Illuminate\Http\Request;
  31. use Illuminate\Support\Facades\Cookie;
  32. use Illuminate\Support\Facades\Crypt;
  33. use Illuminate\Support\Facades\DB;
  34. use Illuminate\Support\Facades\Hash;
  35. use Illuminate\Support\Facades\Log;
  36. use Illuminate\Support\Facades\Redis;
  37. use Illuminate\Support\Facades\Validator;
  38. use PDO;
  39. // use Yansongda\Pay\Log;
  40. class LoginController extends Controller
  41. {
  42. public function __construct()
  43. {
  44. }
  45. public function LoginByCode(Request $request,$onlyVerify=false)
  46. {
  47. $RegisterLocation = $request->country ?? env('COUNTRY_CODE','1');
  48. $Phone = $request->phone;
  49. $PhoneCode = $request->code;
  50. $PhoneCode= preg_replace('/\D/s', '', $PhoneCode);
  51. if (empty($Phone)) {
  52. return apiReturnFail(['web.verify.num_empty', 'PhoneNum Empty']);
  53. }
  54. if (mb_strlen($PhoneCode) > 6) {
  55. return apiReturnFail(['web.verify.code_too_long', 'Phone code is too long']);
  56. }
  57. $Phone = $RegisterLocation.trim($Phone);
  58. Log::info('验证电话开始' . $Phone);
  59. $redisKey = 'LoginByCode_' . $Phone;
  60. if (!SetNXLock::getExclusiveLock($redisKey)) {
  61. return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  62. }
  63. if (!is_numeric($PhoneCode)) {
  64. SetNXLock::release($redisKey);
  65. Log::info('web.verify.code_incorrect_or_expired LoginByCode is_numeric($PhoneCode)',[$Phone,$PhoneCode]);
  66. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  67. }
  68. $verifyCode = GamePhoneVerityCode::verifyCode($Phone, $PhoneCode);
  69. SetNXLock::release($redisKey);
  70. if ($verifyCode != trim($PhoneCode)) {
  71. Log::info('web.verify.code_incorrect_or_expired LoginByCode $verifyCode',[$Phone,$PhoneCode]);
  72. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  73. }
  74. if($onlyVerify)return true;
  75. GamePhoneVerityCode::clearPhoneCode($Phone);
  76. $request->merge(['c' => '']);
  77. $_REQUEST['c'] = '';
  78. RouteService::clearChannelConfig();
  79. $config = RouteService::getChannelConfig($request);
  80. $user = GlobalUserInfo::query()->where('RegionID', $config->isRegionUnique())->where("Phone", $Phone)->first();
  81. if ($user) {
  82. $user = GlobalUserInfo::toWebData($user);
  83. Util::WriteLog('phone_login',['success',$Phone,$config]);
  84. $this->dispatchIpRiskCheck($user['UserID'] ?? 0);
  85. return response()->json(apiReturnSuc($user, ['login.success', 'Login bem-sucedido, bem-vindo de volta!']));//->withCookie($this->setLoginCookie($user['sign']));
  86. } else {
  87. $user = GlobalUserInfo::query()->where("Phone", $Phone)->first();
  88. if($user){
  89. return response()->json(apiReturnSuc($user, ['login.success', 'Login bem-sucedido, bem-vindo de volta!']));//->withCookie($this->setLoginCookie($user['sign']));
  90. }
  91. Util::WriteLog('phone_login',[$Phone,$config]);
  92. return apiReturnFail(['web.login.notfound', 'Sua conta não foi encontrada, registre-se ou tente novamente!']);
  93. }
  94. }
  95. public function BindPhone(Request $request)
  96. {
  97. $user = GlobalUserInfo::$me;
  98. $RegisterLocation = $request->country ?? env('COUNTRY_CODE','1');
  99. $Phone = $request->phone;
  100. $PhoneCode = $request->code;
  101. if (empty($Phone)) {
  102. Log::info('web.verify.num_empty',[$Phone,$PhoneCode]);
  103. return apiReturnFail(['web.verify.num_empty', 'PhoneNum Empty']);
  104. }
  105. if (mb_strlen($PhoneCode) > 6) {
  106. Log::info('web.verify.code_too_long',[$Phone,$PhoneCode]);
  107. return apiReturnFail(['web.verify.code_too_long', 'Phone code is too long']);
  108. }
  109. $Phone = $RegisterLocation.trim($Phone);
  110. Log::info('绑定电话开始' . $Phone);
  111. $redisKey = 'BindPhone_' . $Phone;
  112. if (!SetNXLock::getExclusiveLock($redisKey)) {
  113. Log::info('web.withdraw.try_again_later',[$Phone,$PhoneCode]);
  114. return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  115. }
  116. if (!is_numeric($PhoneCode)) {
  117. SetNXLock::release($redisKey);
  118. Log::info('web.verify.code_incorrect_or_expired BindPhone nonum',[$Phone,$PhoneCode]);
  119. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  120. }
  121. $verifyCode = GamePhoneVerityCode::verifyCode($Phone, $PhoneCode);
  122. if ($verifyCode != trim($PhoneCode)) {
  123. SetNXLock::release($redisKey);
  124. Log::info("web.verify.code_incorrect_or_expired BindPhone $verifyCode",[$Phone,$PhoneCode]);
  125. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  126. }
  127. GamePhoneVerityCode::clearPhoneCode($Phone);
  128. $config = RouteService::getChannelConfig($request);
  129. // 查看手机号是否已经绑定
  130. // $first = DB::connection('write')->table('QPAccountsDB.dbo.AccountPhone')
  131. // ->where('PhoneNum', $Phone)
  132. //// ->where('Channel', $user->Channel)
  133. // ->orWhere('UserID', $user->UserID)
  134. $first = GlobalUserInfo::query()->where(function ($query) use ($Phone, $user, $config) {
  135. $query->where(function ($q) use ($Phone, $user) {
  136. $q->where('RegionID', $user->RegionID??"")->where('Phone', $Phone);
  137. })->orWhere(function ($q) use ($user) {
  138. $q->where('UserID', $user->UserID)->where('Phone', '<>', '');
  139. });
  140. })->first();
  141. if ($first) {
  142. SetNXLock::release($redisKey);
  143. Log::info('web.verify.already_bound',[$Phone,$PhoneCode]);
  144. // return apiReturnFail(['web.verify.already_bound', 'O número de telefone foi vinculado']); // 电话号码已绑定
  145. return apiReturnFail(['web.verify.already_bound', 'O número de telefone foi vinculado'],GlobalUserInfo::getGameUserInfoToWeb('UserID',$first->UserID)); // 电话号码已绑定
  146. }
  147. // if (!isset($request->password) || !isset($request->repassword) || $request->password != $request->repassword) {
  148. // Log::info("web.reg.password_notsame",[$Phone,$PhoneCode]);
  149. // return apiReturnFail(['web.reg.password_notsame', 'As senhas digitadas duas vezes são inconsistentes, digite novamente!'], '', 2);
  150. // }
  151. $PhoneNum = $Phone;
  152. $Phone = $this->checkPhone($PhoneNum, $RegisterLocation, $request);
  153. //有错误返回
  154. if (is_array($Phone) || is_object($Phone)){
  155. Log::info(json_encode($Phone),[$Phone,$PhoneCode]);
  156. return $Phone;
  157. }
  158. $UserID = $user->UserID;
  159. $BindDate = Carbon::now()->toDateTimeString();
  160. $LogonPass = $request->password??$PhoneCode;
  161. $Channel = $user->Channel;
  162. $RegionID = $user->RegionID;
  163. // 绑定手机号
  164. try {
  165. AccountPhone::insert(compact('UserID', 'PhoneNum', 'BindDate', 'Channel', 'RegionID'));
  166. } catch (\Throwable $e) {
  167. if (stripos($e->getMessage(), 'duplicate key') !== false) {
  168. return apiReturnFail(['web.verify.already_bound', 'web.verify.already_bound']);
  169. }
  170. throw $e;
  171. }
  172. GlobalUserInfo::where('GlobalUID', $user->GlobalUID)->update([ 'Phone' => $Phone, 'RegisterLocation' => $RegisterLocation]);
  173. Log::info('绑定手机号'.'-'.$user->GlobalUID.'-' . $Phone . '-' . $LogonPass . '-' . $UserID);
  174. // --绑定手机赠送金币
  175. $SendGold = SystemStatusInfo::OnlyGetCacheValue('BindPhoneReward') ?? 500;
  176. DB::table('QPRecordDB.dbo.LogProp')->insert(['UserID' => $UserID, 'PropID' => 30000, 'PropNum' => $SendGold, 'Source' => 11, 'Param' => null]);
  177. OuroGameService::AddScore($UserID, $SendGold, OuroGameService::REASON_BindPhone,false);
  178. $RecordPlatformDataModel = new \App\Models\RecordPlatformData();
  179. $RecordPlatformDataModel->BindToday($Channel,$user->RegisterDate);
  180. AgentService::recordPerformance($UserID, 0,1);
  181. SetNXLock::release($redisKey);
  182. return apiReturnSuc(GlobalUserInfo::getGameUserInfoToWeb('UserID', $UserID));
  183. /**
  184. *
  185. * INSERT INTO [QPAccountsDB].[dbo].[AccountPhone] ([UserID],[PhoneNum],[BindDate],[LogonPass],[Channel])values(@UserId,@szPhoneNum,GETDATE(),@strLogonPass,@Channel)
  186. *
  187. * --绑定手机赠送金币
  188. * DECLARE @SendGold int
  189. * select @SendGold = [StatusValue] from QPAccountsDB.dbo.SystemStatusInfo where [StatusName] = 'BindPhoneReward'
  190. * if @SendGold is null
  191. * begin
  192. * set @SendGold = 500;
  193. * end
  194. *
  195. * INSERT INTO QPRecordDB.dbo.LogProp(UserID,PropID,PropNum,Source,[Param],RecordData)
  196. * VALUES(@UserId,30000,@SendGold,11,NULL,GETDATE())
  197. *
  198. * EXEC QPRecordDB.dbo.GSP_YN_GR_RecordGameScore
  199. * @dwUserID=@UserId,
  200. * @lChangeScore=@SendGold,
  201. * @nReason = 21,--绑定手机赠送
  202. * @nServerID=0,
  203. * @strUniqueCode='',
  204. * @lRevenue=0,
  205. * @Type=0
  206. *
  207. * update QPTreasureDB.dbo.GameScoreInfo set Score = Score+@SendGold where @UserId = UserID
  208. */
  209. }
  210. // public function PwaInstalled(Request $request)
  211. // {
  212. // $FPID=$request->input("bfp","");
  213. // $user=$request->user();
  214. //
  215. // GlobalUserInfo::where('FPID',$FPID)->orWhere('UserID',$user->UserID)->update(['PwaInstalled'=>1]);
  216. // }
  217. function generateUUID($userId, $location = '1', $region = null,$Channel=99)
  218. {
  219. if(!$region)$region=env('REGION_24680','sa-east');
  220. // 从随机字节创建基础 UUID
  221. $randomBytes = bin2hex(random_bytes(3)); // 6个字符
  222. $randomBytes=str_pad(dechex($Channel),4,'0',STR_PAD_LEFT).$randomBytes;//补上4个channel
  223. // 缩短区域和语言码以适应 UUID 格式
  224. $locCode = substr(md5($location), 0, 4); // 4个字符
  225. $regionCode = substr(md5($region), 0, 4); // 4个字符
  226. // 确保 UserID 以十六进制形式适应最后部分
  227. $userIdHex = substr("000000000" . $userId, -10, 10); // 变长,确保适应
  228. // 构造 UUID
  229. $uuid = sprintf('%s-%s-%s-%s', $randomBytes, $locCode, $regionCode, $userIdHex);
  230. return $uuid;
  231. }
  232. /// 'PayTotal',
  233. // 'PayTimes',
  234. // 'WithdrawTotal',
  235. // 'LessThan',
  236. // 'Condition',
  237. // 'Price',
  238. // 'Amount',
  239. // 'Gift',
  240. // 'TimeLimit',
  241. // 'Status',
  242. public function GetUserInfo(Request $request)
  243. {
  244. $user = $request->globalUser;
  245. $user = GlobalUserInfo::toWebData($user);
  246. self::CheckTimeBonus($user);
  247. // 计算VIP等级
  248. //$user['vip'] = VipService::calculateVipLevel($user['UserID'] ?? 0);
  249. return apiReturnSuc($user);
  250. }
  251. public static function CheckTimeBonus(&$user)
  252. {
  253. return;
  254. if(!$user)return;
  255. $outdatas=null;
  256. if($user['Channel']==99)return ;
  257. try {
  258. $key='repay_temp_'.$user['UserID'];
  259. if(Redis::exists($key)){
  260. $lastData=json_decode(Redis::get($key),true);
  261. if(!isset($lastData['settime'])){
  262. $lastData['settime']=time();
  263. Redis::set($key, json_encode($lastData));
  264. }
  265. $lastData['timeleft']=$lastData['TimeLimit']-(time()-$lastData['settime']);
  266. unset($lastData['PayTotal'],$lastData['PayTimes'],$lastData['WithdrawTotal'],$lastData['LessThan'],$lastData['id'],$lastData['Condition']);
  267. $user['bonus_pack'] = $lastData;
  268. }else {
  269. //处理新逻辑
  270. $datas = RePayConfig::CacheDatas();
  271. if($user['UserID']=='50000005'){
  272. $user['Score']=10;
  273. }
  274. if (isset($datas) && is_array($datas) && count($datas)) {
  275. $datas = array_filter($datas, function ($v) use ($user) {
  276. return $user['Score'] < $v['LessThan'];
  277. });
  278. }
  279. if (isset($datas) && is_array($datas) && count($datas)) {
  280. // $userstat = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  281. // ->where('UserID', $user['UserID'])->first();
  282. $dbh = DB::connection()->getPdo();
  283. $stmt = $dbh->prepare( "EXEC [QPTreasureDB].[dbo].[GSP_GR_QueryUserRechargeInfo] @dwUserID = ".$user['UserID']);
  284. $stmt->execute();
  285. $userstat = $stmt->fetch(\PDO::FETCH_ASSOC);
  286. if($user['UserID']=='50000005'){
  287. $userstat['Recharge']=60000;
  288. $userstat['Withdraw']=0;
  289. }
  290. if ($userstat) {
  291. $datas = array_filter($datas, function ($v) use ($userstat) {
  292. return $userstat['Withdraw'] <= $v['WithdrawTotal'] * NumConfig::NUM_VALUE
  293. && $userstat['Recharge'] >= $v['PayTotal']* NumConfig::NUM_VALUE
  294. && $userstat['RechargeTimes'] <= $v['PayTimes'];
  295. });
  296. } else {
  297. $datas = [];
  298. }
  299. $outdatas = $datas;
  300. if (isset($datas) && is_array($datas) && count($datas)) {
  301. $datas = array_values($datas);
  302. $lastData = $datas[0];
  303. foreach ($datas as $k => $v) {
  304. if ($v['PayTotal'] > $lastData['PayTotal']) {
  305. $lastData = $v;
  306. }
  307. }
  308. if (!empty($lastData)) {
  309. $lastData['gear'] = DB::table('agent.dbo.recharge_gear')
  310. ->where('money', $lastData['Amount'])
  311. ->whereBetween('gift_id', [300, 400])
  312. ->where('status', 2)
  313. ->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')
  314. ->first();
  315. if(empty($lastData['gear'])){
  316. $lastData['gear']=[
  317. 'money' => $lastData['Amount'],
  318. 'gear' => '[{"id":"2","status":1},{"id":"4","status":-1},{"id":"6","status":1},{"id":"11","status":1},{"id":"15","status":1},{"id":"19","status":1}]',
  319. 'status' => 2,
  320. 'created_at' => date('Y-m-d H:i:s.v'),
  321. 'favorable_price' => $lastData['Amount'],
  322. 'image' => '11',
  323. 'give' => $lastData['Gift'],
  324. 'first_pay' => 0,
  325. 'name' => '二次付费',
  326. 'gift_id' => DB::table('agent.dbo.recharge_gear')->where('gift_id','<',400)->max('gift_id')+1,
  327. 'channels' => '',
  328. 'second_give' => 0
  329. ];
  330. DB::table('agent.dbo.recharge_gear')->insert($lastData['gear']);
  331. $lastData['gear']=(object)$lastData['gear'];
  332. }
  333. $lastData['gear']->id = 28;
  334. $lastData['settime']=time();
  335. $lastData['timeleft']=$lastData['TimeLimit'];
  336. $lastData['gear'] = (array)$lastData['gear'];
  337. }
  338. unset($lastData['PayTotal'],$lastData['PayTimes'],$lastData['WithdrawTotal'],$lastData['LessThan'],$lastData['id'],$lastData['Condition']);
  339. Redis::setex($key, $lastData['TimeLimit'], json_encode($lastData));
  340. $user['bonus_pack'] = $lastData;
  341. }
  342. }
  343. }
  344. }catch (\Exception $e) {
  345. TelegramBot::getDefault()->sendMsgWithEnv($e->getMessage().json_encode($outdatas).$e->getTraceAsString());
  346. }
  347. }
  348. public function modiEmail(Request $request)
  349. {
  350. $user = $request->globalUser;
  351. // 自定义错误消息
  352. $messages = [
  353. 'Email.email' => 'O formato do email fornecido está incorreto. ',
  354. 'Email.unique' => 'Este endereço de e-mail foi registrado. ',
  355. ];
  356. // 验证规则
  357. $validator = Validator::make($request->all(), [
  358. 'Email' => 'required|email|unique:mysql.webgame.GlobalUserInfo,Email,' . $user->GlobalUID . ',GlobalUID',
  359. ], $messages);
  360. if ($validator->fails()) {
  361. // 返回具体的错误消息
  362. return apiReturnFail(['web.user.email_fail', $validator->errors()], '', 422);
  363. }
  364. $user->update($validator->validate());
  365. return response()->json(apiReturnSuc(GlobalUserInfo::toWebData($user), ['user.info.modi_success', 'Informação modificada']));
  366. }
  367. public function modiPhone(Request $request)
  368. {
  369. $user = $request->globalUser;
  370. // 自定义错误消息
  371. $messages = [
  372. 'Phone.string' => 'O número de telefone deve estar no formato string. ',
  373. 'Phone.max' => 'O número de telefone não pode exceder 20 caracteres. ',
  374. 'Phone.unique' => 'Este número de telefone já existe. ',
  375. ];
  376. // 验证规则
  377. $validator = Validator::make($request->all(), [
  378. 'Phone' => 'required|string|max:20|unique:mysql.webgame.GlobalUserInfo,Phone,' . $user->GlobalUID . ',GlobalUID',
  379. ], $messages);
  380. if ($validator->fails()) {
  381. // 返回具体的错误消息
  382. return apiReturnFail(['web.user.phone_fail', $validator->errors()], '', 422);
  383. }
  384. $user->update($validator->validate());
  385. return response()->json(apiReturnSuc(GlobalUserInfo::toWebData($user), ['user.info.modi_success', 'Informação modificada']));
  386. }
  387. public function modiUserInfo(Request $request)
  388. {
  389. $user = $request->globalUser;
  390. $validatedData = Validator::make($request->all(), [
  391. 'NickName' => 'nullable|string|max:32',
  392. 'FaceID' => 'nullable|integer|min:1',
  393. 'Gender' => 'nullable|integer|in:0,1,2',
  394. 'DefaultLanguage' => 'nullable|string|max:10',
  395. 'ThemeColor' => 'nullable|in:dark,light'
  396. ], [
  397. 'NickName.string' => 'O apelido deve ser uma string válida. ',
  398. 'NickName.max' => 'O apelido não pode exceder 32 caracteres. ',
  399. 'FaceID.integer' => 'O ID facial deve ser um número inteiro. ',
  400. 'FaceID.min' => 'O ID facial deve ser maior que 0. ',
  401. 'Gender.integer' => 'A seleção de gênero é inválida. ',
  402. 'Gender.in' => 'O gênero deve ser 0 (feminino), 1 (masculino) ou 2 (desconhecido). ',
  403. 'DefaultLanguage.string' => 'O idioma padrão deve ser uma string válida. ',
  404. 'DefaultLanguage.max' => 'O identificador de idioma padrão não pode exceder 10 caracteres. ',
  405. 'ThemeColor.in' => 'A cor do tema deve ser "escuro" ou "claro". '
  406. ]);
  407. if ($validatedData->fails()) {
  408. foreach ($validatedData->errors() as $key => $value) {
  409. return apiReturnFail(['web.modiUserInfo.fail_' . $key, $value[0]], '', 422);
  410. }
  411. }
  412. $validatedData = $validatedData->validate();
  413. foreach ($validatedData as $key => $value) {
  414. if (empty($validatedData[$key]) && $validatedData[$key] !== 0) unset($validatedData[$key]);
  415. }
  416. if (isset($validatedData['FaceID'])) $validatedData['FaceID'] = ($validatedData['FaceID'] - 1) % 16 + 1;
  417. if (isset($validatedData['NickName'])) $validatedData['NickName'] = Util::filterNickName($validatedData['NickName']);
  418. $user->update($validatedData);
  419. return response()->json(apiReturnSuc(GlobalUserInfo::toWebData($user,true), ['user.info.modi_success', 'Informação modificada']));
  420. }
  421. private function checkPhoneCode(Request $request)
  422. {
  423. $user=GlobalUserInfo::$me;
  424. $RegisterLocation = $request->country ?? env('COUNTRY_CODE','55');
  425. $userPhone="";
  426. if($user&&isset($user->Phone)&&substr($user->Phone,0,2)==$RegisterLocation){
  427. $userPhone = explode($RegisterLocation, $user->Phone)[1];
  428. }
  429. $Phone = $request->phone??$userPhone;
  430. // if($Phone!=$userPhone){
  431. // return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  432. // }
  433. $PhoneCode = $request->code;
  434. if (empty($Phone)) {
  435. return apiReturnFail(['web.verify.num_empty', 'PhoneNum Empty']);
  436. }
  437. if (mb_strlen($PhoneCode) > 6) {
  438. return apiReturnFail(['web.verify.code_too_long', 'Phone code is too long']);
  439. }
  440. $Phone = $RegisterLocation.trim($Phone);
  441. Log::info('验证电话开始' . $Phone);
  442. $redisKey = 'checkPhoneCode_' . $Phone;
  443. if (!SetNXLock::getExclusiveLock($redisKey)) {
  444. return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  445. }
  446. if (!is_numeric($PhoneCode)) {
  447. SetNXLock::release($redisKey);
  448. Log::info('web.verify.code_incorrect_or_expired checkPhoneCode nonum',[$Phone,$PhoneCode]);
  449. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  450. }
  451. $verifyCode = GamePhoneVerityCode::verifyCode($Phone, $PhoneCode);
  452. SetNXLock::release($redisKey);
  453. if ($verifyCode != trim($PhoneCode)) {
  454. Log::info('web.verify.code_incorrect_or_expired checkPhoneCode noveri',[$Phone,$PhoneCode]);
  455. return apiReturnFail(['web.verify.code_incorrect_or_expired', 'O código está incorreto ou o tempo passou']);
  456. }
  457. GamePhoneVerityCode::clearPhoneCode($Phone);
  458. return 1;
  459. }
  460. public function forgetPassword(Request $request)
  461. {
  462. $check=$this->checkPhoneCode($request);
  463. if($check!==1){
  464. return $check;
  465. }
  466. $RegisterLocation = $request->country ?? env('COUNTRY_CODE','55');
  467. $user = GlobalUserInfo::getGameUserInfo("Phone", $RegisterLocation . $request->phone);
  468. if(!$user||empty($user)){
  469. return $this->registerUser($request);
  470. return apiReturnFail(['web.login.notfound', 'Erro de entrada, tente novamente!'], '', 2);
  471. }
  472. $request->globalUser=$user;
  473. return $this->modiPassword($request,false);
  474. }
  475. public function forgetInsurePassword(Request $request)
  476. {
  477. $check=$this->checkPhoneCode($request);
  478. if($check!==1){
  479. return $check;
  480. }
  481. return $this->modiInsurePassword($request,false);
  482. }
  483. public function modiPassword(Request $request,$checkOldpass=true)
  484. {
  485. $user = $request->globalUser;
  486. if($checkOldpass) {
  487. $oldpassword = $request->input('oldpassword');
  488. if (!Hash::check($oldpassword, $user->LogonPass)) {
  489. return apiReturnFail(['web.user.password_fail', 'A senha original está errada, digite-a novamente.'], '', 2);
  490. }
  491. }
  492. $newpassword = $request->input('newpassword');
  493. $renewpassword = $request->input('renewpassword');
  494. if (empty($newpassword) || empty($renewpassword)) {
  495. return apiReturnFail(['web.user.password_fail', 'A senha original está errada, digite-a novamente.'], '', 3);
  496. }
  497. if ($newpassword == $renewpassword) {
  498. $user->LogonPass = Hash::make($newpassword);
  499. $user->update(['LogonPass' => $user->LogonPass]);
  500. return response()->json(apiReturnSuc(GlobalUserInfo::toWebData($user), ['user.password.modi_success', 'Redefinição de senha concluída!']));//->withCookie($this->setLoginCookie($user['sign']));
  501. } else {
  502. return apiReturnFail(['web.reg.password_notsame', 'As senhas digitadas duas vezes são inconsistentes, digite novamente!'], '', 2);
  503. }
  504. }
  505. public function modiInsurePassword(Request $request,$checkOldpass=true)
  506. {
  507. $user = $request->globalUser;
  508. if($checkOldpass) {
  509. $oldpassword = $request->input('oldpassword');
  510. if (!empty($user->InsurePass) && !Hash::check($oldpassword, $user->InsurePass)) {
  511. return apiReturnFail(['web.user.paypass_fail', 'A senha original está errada, digite-a novamente.'], '', 2);
  512. }
  513. }
  514. $newpassword = $request->input('newpassword');
  515. $renewpassword = $request->input('renewpassword');
  516. if (empty($newpassword) || empty($renewpassword)) {
  517. return apiReturnFail(['web.user.password_fail', 'A senha original está errada, digite-a novamente.'], '', 3);
  518. }
  519. if ($newpassword == $renewpassword) {
  520. $user->InsurePass = Hash::make($newpassword);
  521. $user->update(['InsurePass' => $user->InsurePass]);
  522. return response()->json(apiReturnSuc(GlobalUserInfo::toWebData($user), ['user.password.modi_success', 'Redefinição de senha concluída!']));//->withCookie($this->setLoginCookie($user['sign']));
  523. } else {
  524. return apiReturnFail(['web.reg.paypass_notsame', 'As senhas digitadas duas vezes são inconsistentes, digite novamente!'], '', 2);
  525. }
  526. }
  527. public function Logout(Request $request)
  528. {
  529. return response()->json(apiReturnSuc('', ['logout.success', 'Você saiu com sucesso.']))->withCookie(self::clearLoginCookie());
  530. }
  531. public static function getPwaBonus(Request $request)
  532. {
  533. $user=$request->user();
  534. $haveBonus=Redis::get('pwa_bonus:'.$user->UserID);
  535. $config = RouteService::getChannelConfig($request);
  536. if($haveBonus&&$config->BONUS_PWA()>0){
  537. [$OrgScore,$NowScore]=OuroGameService::AddFreeScore($user->UserID,$config->BONUS_PWA(),OuroGameService::REASON_PwaBonus,false);
  538. $data=GlobalUserInfo::toWebData($user);
  539. $data['Score']=$NowScore;
  540. Redis::del('pwa_bonus:'.$user->UserID);
  541. PwaBonusLog::addLog([
  542. 'userID' => $user->UserID,
  543. 'GameID' => $user->GameID,
  544. 'Channel' => $user->Channel,
  545. 'bonus_amount' => $config->BONUS_PWA(),
  546. 'org_score' => $OrgScore,
  547. 'now_score' => $NowScore,
  548. 'ip' => $request->ip(),
  549. 'log_date' => date('Y-m-d'),
  550. ]);
  551. if(date('Ymd',strtotime($user->RegisterDate)) == date('Ymd')){
  552. $RecordPlatformDataModel = new \App\Models\RecordPlatformData();
  553. $RecordPlatformDataModel->PwaToday($user->Channel);
  554. }
  555. return response()->json(apiReturnSuc($data, ['user.bonus.pwa_bonus_success', 'Bônus PWA recebido com sucesso!']));
  556. }else{
  557. return response()->json(apiReturnFail(['user.bonus.pwa_bonus_fail', 'Você já recebeu o bônus PWA.',$haveBonus,$config->BONUS_PWA()]));
  558. }
  559. }
  560. private function isSequentialOrRepetitive($phoneNumber)
  561. {
  562. // 移除国家代码和非数字字符
  563. $digits = $phoneNumber;//substr($phoneNumber, 2);
  564. // 检查连号
  565. if (preg_match('/(\d)\1{5,}/', $digits)) { // 改为检测6个或更多连续相同的数字
  566. return true;
  567. }
  568. // 检查顺子,增加检测递增和递减顺子
  569. $ascending = true;
  570. $descending = true;
  571. for ($i = 0; $i < strlen($digits) - 1; $i++) {
  572. if (ord($digits[$i + 1]) - ord($digits[$i]) != 1) {
  573. $ascending = false;
  574. }
  575. if (ord($digits[$i]) - ord($digits[$i + 1]) != 1) {
  576. $descending = false;
  577. }
  578. }
  579. if ($ascending || $descending) {
  580. return true;
  581. }
  582. return false;
  583. }
  584. /**
  585. * @param Request $request
  586. * @return GlobalUserInfo|false
  587. */
  588. public static function checkLogin(Request $request)
  589. {
  590. // $sign=$request->cookie('guuid')??$request->sign;
  591. $sign = $request->sign;
  592. if ($sign) {
  593. try {
  594. $arr = explode('|', Crypt::decryptString($sign));
  595. $globalUID = $arr[0];
  596. $timestamp = intval($arr[1]);
  597. if (time() > $timestamp) return false;
  598. $user = GlobalUserInfo::getGameUserInfo('GlobalUID', $globalUID);
  599. if ($user) {
  600. if ($arr[2] == substr(md5($user->LogonPass), 0, 6)) {
  601. $FPID = $request->input("bfp", "");
  602. if (!empty($FPID)) {
  603. if (empty($user->FPID)) $user->update(['FPID' => $FPID]);
  604. if ($user->LastFPID != $FPID) $user->update(['LastFPID' => $FPID]);
  605. }
  606. if (empty($user->ShortHashID)) {
  607. $ShortHashID = explode('-', $globalUID)[0];
  608. $user->update(['ShortHashID' => $ShortHashID]);
  609. }
  610. GlobalUserInfo::$me = $user;
  611. if (intval($request->input('pwa', 0)) == 1) {
  612. if (intval($user->PwaInstalled) == 0) {
  613. $user->update(['PwaInstalled' => 1]);
  614. //s2s
  615. AfEvent::dispatch([
  616. 'UserID' => $user->UserID,
  617. 'event_name' => 'Lead',
  618. 'custom_data' => [
  619. 'content_name' => 'Install Pwa1',
  620. 'status' => 1,
  621. ],
  622. ]);
  623. $config = RouteService::getChannelConfig($request);
  624. if($config->BONUS_PWA()>0){
  625. Redis::setex('pwa_bonus:'.$user->UserID,86400,1);
  626. }
  627. }
  628. }
  629. return $user;
  630. }
  631. }
  632. } catch (\Exception $e) {
  633. }
  634. }
  635. return false;
  636. }
  637. private function guestLogin($user,$isRegister=false)
  638. {
  639. $qp=QuickAccountPass::query()->where('UserID',$user->UserID)->first();
  640. if(!$qp){
  641. $qp=$this->getGustAccount($user->UserID);
  642. $user->Accounts=$qp['account'];
  643. $user->LogonPass=Hash::make($qp['password']);
  644. $user->save();
  645. }
  646. $user = GlobalUserInfo::toWebData($user,true);
  647. if($isRegister)$user['reg'] = 1;
  648. if($qp){
  649. if(!is_array($qp))$qp=$qp->toArray();
  650. $user['account']=$qp['account'];
  651. $user['password']=$qp['password'];
  652. }
  653. $this->dispatchIpRiskCheck($user['UserID'] ?? 0);
  654. return response()->json(apiReturnSuc($user, ['login.success', 'Login bem-sucedido, bem-vindo de volta!']));
  655. }
  656. /**
  657. * 异步派发 IP 风险检测任务
  658. * 在用户登录/注册成功后调用,不阻塞响应
  659. *
  660. * @param int $userId
  661. */
  662. private function dispatchIpRiskCheck($userId)
  663. {
  664. $ip = IpLocation::getRealIp();
  665. if ($ip && $userId) {
  666. IpRiskDetection::dispatch($userId, $ip);
  667. }
  668. }
  669. public function login(Request $request)
  670. {
  671. $type=$request->input('type','id');
  672. $FPID = $request->input("bfp", "");
  673. $user=null;
  674. $config = RouteService::getChannelConfig($request);
  675. if($type=='guest'){
  676. //游客模式打开,随时可以登录
  677. //$user=GlobalUserInfo::where('FPID',$FPID)->where('Phone','')->where('Email','')->first();
  678. $user=GlobalUserInfo::where('FPID',$FPID)->where('RegionID',$config->isRegionUnique())->first();
  679. if(!$user){
  680. return $this->registerUser($request);
  681. }else{
  682. return $this->guestLogin($user);
  683. }
  684. }
  685. if (!isset($request->account)) {
  686. return apiReturnFail(["web.login.account_empty", 'Por favor insira o nome de usuário!']);
  687. }
  688. if (!isset($request->password)) {
  689. return apiReturnFail(['web.login.password_empty', 'Por favor insira a senha!'], '', 302);
  690. }
  691. $RegisterLocation = $request->country ?? env('COUNTRY_CODE','55');
  692. if (strstr($request->account, '@')) {
  693. $user = GlobalUserInfo::query()->where('RegionID', $config->isRegionUnique())->where("Email", $request->account)->first();
  694. } else if (is_numeric($request->account)) {
  695. $user = GlobalUserInfo::query()->where('RegionID', $config->isRegionUnique())->where("Phone", $RegisterLocation . $request->account)->first();
  696. } else {
  697. $user = GlobalUserInfo::query()->where('RegionID', $config->isRegionUnique())->where("Accounts", $request->account)->first();
  698. }
  699. if ($user) {
  700. if (Hash::check($request->password, $user->LogonPass)) {
  701. $user = GlobalUserInfo::toWebData($user,true);
  702. $this->dispatchIpRiskCheck($user['UserID'] ?? 0);
  703. return response()->json(apiReturnSuc($user, ['login.success', 'Login bem-sucedido, bem-vindo de volta!']));//->withCookie($this->setLoginCookie($user['sign']));
  704. } else {
  705. return apiReturnFail(['web.login.notfound', 'Erro de entrada, tente novamente!'], '', 2);
  706. }
  707. } else {
  708. return apiReturnFail(['web.login.notfound', 'Sua conta não foi encontrada, registre-se ou tente novamente!']);
  709. }
  710. }
  711. private function checkPhone($Phone, $RegisterLocation = '1',Request $request=null)
  712. {
  713. $OrgPhone=$Phone;
  714. // dd($RegisterLocation,$Phone,str_starts_with($Phone,$RegisterLocation),$Phone=explode($RegisterLocation,$Phone));
  715. if(!empty($RegisterLocation)&&str_starts_with($Phone,$RegisterLocation)){
  716. $Phone=$OrgPhone;
  717. }
  718. if (!empty($Phone)) {
  719. // 验证规则
  720. // Remove spaces and dashes from the input
  721. $Phone = str_replace(['-', ' '], '', $Phone);
  722. // Check if the number has 11 digits and the third character is 9
  723. if ($RegisterLocation == env('COUNTRY_CODE','1')) {
  724. // if (!preg_match('/^\d{2}9\d{8}$/', $Phone)) {
  725. // return apiReturnFail(['web.user.phone_fail', 'Not correct phone number'], '', 422);
  726. // }
  727. }
  728. if ($this->isSequentialOrRepetitive($Phone)) {
  729. return apiReturnFail(['web.user.phone_fail', 'Not correct phone number'], '', 422);
  730. }
  731. // if(!str_starts_with($Phone,$RegisterLocation)) {
  732. // $Phone = $RegisterLocation . $Phone;
  733. // }
  734. }
  735. if (!empty($Phone)) {
  736. $config = RouteService::getChannelConfig($request);
  737. $region=$config->isRegionUnique();
  738. $regionID = $request?$request->user()?$request->user()->RegionID:$region:$region;
  739. $isExist = GlobalUserInfo::query()
  740. ->where('RegionID', $regionID)
  741. ->where(function ($query) use ($Phone, $OrgPhone) {
  742. $query->where("Phone", $Phone)->orWhere('Accounts', $OrgPhone);
  743. })
  744. ->first();
  745. //账户查重
  746. if ($isExist) {
  747. if ($request&&Hash::check($request->password, $isExist->LogonPass)) {
  748. return $isExist;
  749. }
  750. return apiReturnFail(['web.reg.fail_phone_exist', 'O número de telefone já existe, altere-o e tente se cadastrar novamente!']);
  751. }
  752. }
  753. return $Phone;
  754. }
  755. public function createGuestAccounts()
  756. {
  757. $accs=[];
  758. for($i=0;$i<100;$i++) {
  759. $acc = $this->makeGuestAccount();
  760. while(QuickAccountPassStore::where("account", $acc['account'])->exists()) {
  761. $acc = $this->makeGuestAccount();
  762. }
  763. QuickAccountPassStore::create($acc);
  764. $accs[]=$acc;
  765. }
  766. return ['accs'=>$accs];
  767. }
  768. public function getGustAccount($UserID)
  769. {
  770. $acc=QuickAccountPass::whereNull('UserID')->first();
  771. if(!$acc){
  772. $res=$this->createGuestAccounts();
  773. $accs=$res['accs'];
  774. if($accs){
  775. QuickAccountPass::insert($accs);
  776. }
  777. $acc=QuickAccountPass::query()->whereNull('UserID')->first();
  778. }
  779. if($acc){
  780. $acc->update(['UserID' => $UserID]);
  781. }
  782. return $acc->toArray();
  783. }
  784. public function makeGuestAccount()
  785. {
  786. // 词库
  787. $words = ["sun", "moon", "star", "sky", "wind", "fire", "water", "earth","apple","banana","cherry","date","elderberry","fig","grape","honeydew","kiwi","lemon","mango","nectarine","orange","peach","pear","plum","quince","raspberry","strawberry","tangerine","ugli","vanilla","watermelon","xylophone","yam","zucchini","airplane","balloon","camera","drum","eagle","flag","guitar","hat","iceberg","jacket","kite","lamp","mountain","notebook","octopus","penguin","quilt","robot","sunflower","train","umbrella","vase","whale","yacht","zebra","actor","bicycle","carrot","dolphin","elephant","fountain","grape","honey","internet","jungle","koala","lemonade","moose","ninja","octopus","puzzle","quasar","rocket","sunset","trampoline","unicorn","violin","whale","xylophone","yellow","zebra","adventure","bubble","cactus","daisy","envelope","feather","gorilla","horizon","jellyfish","kitchen","lighthouse","mushroom","notebook","orchestra","penguin","quilt","river","snowflake","telescope","universe","vortex","whisper","xenon","yoga","zebra","airport","beach","cucumber","dolphin","eggplant","fishing","grapevine","hiking","jelly","keyboard","lunar","monkey","northern","ocean","pebble","question","robot","scarf","thunder","underwear","vivid","windmill","xylophone","yogurt","zoo","amethyst","butterfly","cloud","dream","emerald","frost","garden","harmony","island","jigsaw","kaleidoscope","lily","melody","nectar","obsidian","parrot","quilt","rainbow","storm","twilight","vortex","whistle","xenon","yarn","zeppelin","antelope","bridge","cobweb","diamond","energy","feather","giraffe","horizon","icicle","jungle","kettle","lemonade","morning","nightfall","octagon","peacock","quasar","riddle","snowman","tulip","unicorn","violet","wonder","xenon","yellow","zodiac","albatross","bamboo","carpet","dandelion","echo","flamingo","galaxy","honeycomb","illusion","jellybean","knight","lighthouse","moonlight","ninja","orchestra","penguin","quill","robot","sunrise","tiger","umbrella","vampire","wisteria","xylophone","yawn","zebra","acrobat","beetle","coral","dusk","elm","frost","grace","horizon","igloo","jacket","kite","lamb","meadow","nail","owl","prism","quince","raven","sand","telescope","universe","vacuum","waterfall","xylophone","yacht","zenith","alphabet","breeze","crystal","dawn","eagle","festival","glow","horizon","ivory","jewel","knob","lemon","magnet","noon","oak","path","quest","rose","skyline","trail","umbrella","vortex","wave","xylophone","yellow","zephyr","abstract","beetle","cherry","dolphin","enigma","flame","giraffe","horizon","ink","jewel","kaleidoscope","lily","matrix","neptune","oasis","puzzle","quartz","rain","snowflake","tulip","ufo","vortex","whale","xylophone","yarn","zeppelin","apple","amazon","google","microsoft","facebook","twitter","netflix","sony","samsung","intel","nike","adidas","coca-cola","pepsi","oracle","ibm","hp","dell","nvidia","twitter","afghanistan","brazil","canada","denmark","egypt","france","germany","hungary","india","japan","kenya","luxembourg","morocco","nigeria","oman","portugal","qatar","russia","spain","turkey","ukraine","vietnam","albert","isaac","marie","charles","nelson","martin","george","abraham","leo","vincent","john","michael","james","robert","david","mary","jennifer","linda","patricia","susan"];
  788. $numbers = range(0, 999);
  789. // 生成账号和密码
  790. $word1 = $words[array_rand($words)];
  791. // $word2 = $words[array_rand($words)];
  792. $number = str_pad($numbers[array_rand($numbers)], 2, '0', STR_PAD_LEFT);
  793. $account= $word1 . $number ;
  794. $word = $words[array_rand($words)];
  795. $number = str_pad($numbers[array_rand($numbers)], 2, '0', STR_PAD_LEFT);
  796. $password= $word . $number;
  797. return compact('account', 'password');
  798. }
  799. public function getUserByFPID($FPID)
  800. {
  801. $user=GlobalUserInfo::getGameUserInfo('FPID', $FPID);
  802. return $user;
  803. }
  804. private $maxFpsidLimit=2;
  805. public function registerUser(Request $request, $regByGuest = false)
  806. {
  807. //type=id,phone,sms,mail,guest
  808. $type=$request->input('type',"id");
  809. if (!$regByGuest&&$type!='guest') {
  810. if (!isset($request->email) && !isset($request->phone)&&!isset($request->account)) {
  811. return apiReturnFail(["web.reg.account_empty", 'Por favor insira o nome de usuário!']);
  812. }
  813. if (!isset($request->password) || !isset($request->repassword) || $request->password != $request->repassword) {
  814. return apiReturnFail(['web.reg.password_notsame', 'As senhas digitadas duas vezes são inconsistentes, digite novamente!'], '', 2);
  815. }
  816. }
  817. $FPID = $request->input("bfp", "");
  818. if($type=='sms'){
  819. $verifyRes=$this->LoginByCode($request,true);
  820. //报错
  821. if(is_array($verifyRes))return $verifyRes;
  822. }else{
  823. //把数据卡限制住
  824. // if (GlobalUserInfo::where('FPID',$FPID)->count() > $this->maxFpsidLimit) {
  825. // $allAcc=GlobalUserInfo::where('FPID',$FPID)->get()->toArray();
  826. // $reqs=$request->all();
  827. // Util::WriteLog('maxreg',compact('allAcc','reqs'));
  828. // return apiReturnFail(['web.reg.fail_ipmax', 'Too many register requests!']);
  829. // }
  830. }
  831. if (empty($FPID)) {
  832. return apiReturnFail(['web.reg.fail_phone_exist', 'O número de telefone já existe, altere-o e tente se cadastrar novamente!']);
  833. }
  834. //获取默认配置
  835. $config = RouteService::getChannelConfig($request);
  836. //游客注册检查是否已经注册
  837. if($type=='guest'){
  838. $where = [];
  839. $where[] = ['FPID', $FPID];
  840. $where[] = ['Phone', ''];
  841. $where[] = ['Email', ''];
  842. $where[] = ['RegionID', $config->isRegionUnique()];
  843. $guestUser=GlobalUserInfo::where($where)->first();
  844. if($guestUser){
  845. //存在,直接返回去
  846. return $this->guestLogin($guestUser);
  847. }
  848. }
  849. $login_ip = IpLocation::getRealIp();
  850. $RegisterLocation = $request->country ?? env('COUNTRY_CODE',55);
  851. $ServerRegion = env('REGION_24680','sa-east');
  852. $Language = $request->lang ?? $request->getLocale();
  853. $Phone = $request->phone ?? "";
  854. $Phone = $this->checkPhone($Phone, $RegisterLocation,$request);
  855. //有错误返回
  856. if (is_array($Phone)) {
  857. return $Phone;
  858. }else if(is_object($Phone)&&isset($Phone->GlobalUID)){
  859. //原来就存在,直接返回
  860. $guser = GlobalUserInfo::toWebData($Phone,true);
  861. $guser['reg'] = 1;
  862. return response()->json(apiReturnSuc($guser, ['reg.success', 'Registro realizado com sucesso!']));
  863. }
  864. if (isset($request->email) && strstr($request->email, '@')) {
  865. $isExist = GlobalUserInfo::query()->where("Email", $request->email)->exists();
  866. //账户查重
  867. if ($isExist) {
  868. return apiReturnFail(['web.reg.fail_email_exist', 'O e-mail já existe, altere-o e tente se cadastrar novamente!']);
  869. }
  870. }
  871. $redisKey = 'register_' . $FPID;
  872. if (!SetNXLock::getExclusiveLock($redisKey)) {
  873. return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  874. }
  875. $Channel = 0;
  876. //保持邀请和被邀请的渠道序列统一
  877. $ActCode = $request->input('act');
  878. if(strstr($ActCode,'http')){
  879. $ActCode=explode('http',$ActCode)[0];
  880. }
  881. $ReferrType = 0;
  882. if ($ActCode) {
  883. //使用邀请的Code来保持邀请被邀请的用户注册渠道一致性
  884. $link = AgentLinks::getByCode($ActCode);
  885. if ($link) {
  886. $inviter = AccountsInfo::where('UserID', $link->UserID)->first();
  887. if($inviter&&is_object($inviter)) {
  888. $Channel = $inviter->Channel;
  889. $ReferrType = 2;
  890. }
  891. }
  892. }
  893. if(!$Channel){
  894. //非游客注册
  895. while($config->isGuestOpen()&&!$regByGuest){
  896. RouteService::clearChannelConfig();
  897. $config = RouteService::getChannelConfig($request);
  898. }
  899. $Channel = $config->Channel;
  900. if($Channel!=env('REGION_24680_DEFAULT_CHANNEL',100))$ReferrType = 1;
  901. }else{
  902. //先搜索本地配置
  903. $config = WebChannelConfig::getByChannel($Channel);
  904. }
  905. $Package = $config->PackageName;
  906. if ($config) {
  907. //每小时对齐两个表的包名
  908. if(!Redis::exists('ChannelPackageName'.$Channel)) {
  909. $pack = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $Channel)->select('PackageName')->first();
  910. if ($pack) {
  911. Redis::setex('ChannelPackageName' . $Channel, 3600, $Package);
  912. if ($Package != $pack->PackageName) {
  913. DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $Channel)->update(['PackageName' => $Package]);
  914. }
  915. }
  916. }
  917. }
  918. $account= $request->account??$request->email ?? $request->phone ?? $FPID;
  919. //注册到游戏服务器
  920. $user = $this->registerAccountInfo($request, $Package, $Channel,$account);
  921. //返回错误
  922. if (is_array($user) && !isset($user['UserID'])) {
  923. SetNXLock::release($redisKey);
  924. return $user;
  925. }
  926. if (!$user) {
  927. SetNXLock::release($redisKey);
  928. return apiReturnFail(['web.withdraw.try_again_later', 'Pausa de login']);
  929. }
  930. //代理注册,保留号段10000-100000
  931. if($request->input('isagent',0)=='24680'){
  932. $oldid=$user['UserID'];
  933. $newid=AccountsInfo::whereBetween('UserID',[10000,100000])->max('UserID')??10000;
  934. $newid++;
  935. $acc=AccountsInfo::find($oldid);
  936. $newacc=$acc->toArray();
  937. $acc->delete();
  938. $newacc['UserID']=$newid;
  939. $pdo = DB::connection('write')->getPdo();
  940. $pdo->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY, true);
  941. DB::connection('write')->unprepared("set identity_insert QPAccountsDB.dbo.AccountsInfo on;");
  942. DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->insert($newacc);
  943. DB::connection('write')->unprepared("set identity_insert QPAccountsDB.dbo.AccountsInfo off;");
  944. $pdo->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY, false);
  945. $old=['UserID'=>$oldid];$new=['UserID'=>$newid];
  946. DB::connection('write')->table('QPAccountsDB.dbo.UserAgent')->where($old)->update($new);
  947. DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where($old)->update($new);
  948. $user['UserID']=$newid;
  949. }
  950. $UserID = $user['UserID'];
  951. $GameID = $user['GameID'];
  952. $password=$request->password;
  953. $globalUserInfo = GlobalUserInfo::getGameUserInfo('UserID', $UserID);
  954. if ($globalUserInfo) {
  955. $GlobalUID = $globalUserInfo->GlobalUID;
  956. } else {
  957. if($type=='guest'){
  958. //改成从中心区获取idpass
  959. $idps=$this->getGustAccount($UserID);
  960. $account=$idps['account'];
  961. $password=$idps['password'];
  962. }
  963. $GlobalUID = $this->generateUUID($UserID, $RegisterLocation, $ServerRegion,$Channel??99);
  964. $ShortHashID = explode('-', $GlobalUID)[0];
  965. //先搞定userid
  966. $globalUserInfo = new GlobalUserInfo([
  967. 'UserID' => $UserID,
  968. 'GameID' => $GameID,
  969. 'FF' => $request->input('ff', ''),
  970. 'FPID' => $FPID,
  971. 'LastFPID' => $FPID,
  972. 'ShortHashID' => $ShortHashID,
  973. 'GlobalUID' => $GlobalUID,
  974. 'Accounts' => $account, // Assuming email is received from request
  975. 'Email' => $request->email ?? '', // Assuming email is received from request
  976. 'Phone' => $Phone, // Assuming email is received from request
  977. 'LogonPass' => Hash::make($password),
  978. 'LogonIP' => $login_ip,
  979. 'Gender' => 1,
  980. 'RegisterIP' => $login_ip,
  981. 'RegisterLocation' => $RegisterLocation,
  982. 'ServerRegion' => $ServerRegion,
  983. 'DefaultLanguage' => $Language,
  984. 'Channel' => $Channel??99,
  985. 'RegionID' => $config->isRegionUnique(),
  986. 'ReferrType' => $ReferrType,
  987. 'RegisterDate' => date('Y-m-d H:i:s'),
  988. 'InsurePass' => '',
  989. 'UserRight' => 0,
  990. 'Level' => 0,
  991. 'Exp' => 0,
  992. 'FaceID' => $user['FaceID'],
  993. 'NickName' => $user['NickName'],
  994. 'Registed' =>1,
  995. 'PwaInstalled' =>$request->input('pwa',0),
  996. // 'InsurePass' => Hash::make($request->insurePassword),
  997. // Add other fields as needed
  998. ]);
  999. try {
  1000. $globalUserInfo->save();
  1001. } catch (\Exception $exception) {
  1002. Log::error($exception->getMessage());
  1003. }
  1004. }
  1005. GlobalUserInfo::$me=$globalUserInfo;
  1006. if($Channel==env('REGION_24680_DEFAULT_CHANNEL',100)){
  1007. Util::WriteLog('c99',json_encode($_SERVER));
  1008. }
  1009. //注册钱数要归0
  1010. // $newRegGolds=$config->isRegZeroMoneyOpen()?0:$config->BONUS_REG();
  1011. // GameScoreInfo::query()->where('UserID', $UserID)->update(['Score'=>$newRegGolds]);
  1012. $agentUser = AgentService::SetUserAgent($GlobalUID, $UserID, $ActCode);
  1013. SetNXLock::release($redisKey);
  1014. if ($regByGuest) {
  1015. return GlobalUserInfo::getGameUserInfo("UserID", $UserID);
  1016. }
  1017. $cookieParam = $request->input('cookie', '');
  1018. $fbclid = ApkService::extractFbclid($cookieParam);
  1019. ApkService::bindCookie($globalUserInfo, $request->input('s_k', ''), $fbclid, $cookieParam);
  1020. $guser = GlobalUserInfo::toWebData($globalUserInfo,true);
  1021. // if($agentUser->Higher1ID){
  1022. // //获取邀请者信息
  1023. // $inviter=AccountsInfo::where('UserID',$agentUser->Higher1ID)->first();
  1024. // }
  1025. $guser['reg'] = 1;
  1026. if($type=='guest'){
  1027. $guser['account'] = $account;
  1028. $guser['password'] = $password;
  1029. }
  1030. $defaultGameId = 931;
  1031. $recommendGame = '/game/' . $defaultGameId;
  1032. // 如果用户信息存在,根据GameID的最后一位数字查询映射关系
  1033. if ($guser && isset($guser['GameID'])) {
  1034. $gameId = (string)$guser['GameID'];
  1035. $lastDigit = (int)substr($gameId, -1); // 获取最后一位数字
  1036. // 查询映射关系(带缓存)
  1037. $cacheKey = 'game_number_mapping:' . $lastDigit;
  1038. $mapping = null;
  1039. // 尝试从缓存获取
  1040. $cached = Redis::get($cacheKey);
  1041. if ($cached !== null) {
  1042. $decoded = json_decode($cached, true);
  1043. if (is_array($decoded) && !empty($decoded)) {
  1044. $mapping = (object)$decoded;
  1045. }
  1046. }
  1047. if(!$mapping){
  1048. $mapping = DB::table('agent.dbo.game_number_mapping')
  1049. ->where('number', $lastDigit)
  1050. ->first();
  1051. Redis::setex($cacheKey, $mapping ? 86400 : 300, json_encode($mapping ?: []));
  1052. }
  1053. if ($mapping && isset($mapping->game_id) && $mapping->game_id) {
  1054. $defaultGameId = $mapping->game_id;
  1055. $recommendGame = '/game/' . $mapping->game_id;
  1056. }
  1057. }
  1058. $guser['recommendGame'] = $recommendGame;
  1059. AccountsInfo::where('UserID', $UserID)->update(['UserMedal' => $defaultGameId ]);
  1060. Util::WriteLog('register_params',[$request,$guser]);
  1061. //s2s上报
  1062. AfEvent::dispatch([
  1063. 'UserID' => $UserID,
  1064. 'event_name' => 'CompleteRegistration',
  1065. 'custom_data' => [
  1066. 'content_name' => 'register_success',
  1067. 'status' => 1,
  1068. ],
  1069. ]);
  1070. if($request->input('pwa',0)){
  1071. AfEvent::dispatch([
  1072. 'UserID' => $UserID,
  1073. 'event_name' => 'Lead',
  1074. 'custom_data' => [
  1075. 'content_name' => 'Install Pwa2',
  1076. 'status' => 1,
  1077. ],
  1078. ]);
  1079. }
  1080. $this->dispatchIpRiskCheck($UserID);
  1081. return response()->json(apiReturnSuc($guser, ['reg.success', 'Registro realizado com sucesso!']));//->withCookie($this->setLoginCookie($guser['sign']));
  1082. }
  1083. public function registerUserNew(Request $request, $regByGuest = true)
  1084. {
  1085. //type=id,phone,sms,mail,guest
  1086. $type=$request->input('type',"id");
  1087. $FPID = $request->input("bfp", "");
  1088. if (empty($FPID)) {
  1089. return apiReturnFail(['web.reg.fail_phone_exist', 'O número de telefone já existe, altere-o e tente se cadastrar novamente!']);
  1090. }
  1091. $config = RouteService::getChannelConfig($request);
  1092. $where = [];
  1093. $where[] = ['FPID', $FPID];
  1094. // $where[] = ['Phone', ''];
  1095. // $where[] = ['Email', ''];
  1096. $where[] = ['RegionID', $config->isRegionUnique()];
  1097. $guestUser=GlobalUserInfo::where($where)->first();
  1098. if($guestUser){
  1099. //存在,直接返回去
  1100. return $this->guestLogin($guestUser);
  1101. }
  1102. $login_ip = IpLocation::getRealIp();
  1103. $RegisterLocation = $request->country ?? env('COUNTRY_CODE',1);
  1104. $ServerRegion = env('REGION_24680','sa-east');
  1105. $Language = $request->lang ?? $request->getLocale();
  1106. $Phone = $request->phone ?? "";
  1107. if (is_numeric($Phone) && !str_starts_with($Phone, $RegisterLocation)) {
  1108. //如果是纯数字且不以国家码开头,自动加上国家码
  1109. $Phone = $RegisterLocation . $Phone;
  1110. }
  1111. $Phone = $this->checkPhone($Phone, $RegisterLocation,$request);
  1112. //有错误返回
  1113. if (is_array($Phone)) {
  1114. return $Phone;
  1115. }else if(is_object($Phone)&&isset($Phone->GlobalUID)){
  1116. //原来就存在,直接返回
  1117. $guser = GlobalUserInfo::toWebData($Phone,true);
  1118. $guser['reg'] = 1;
  1119. return response()->json(apiReturnSuc($guser, ['reg.success', 'Registro realizado com sucesso!']));
  1120. }
  1121. $redisKey = 'register_' . $FPID;
  1122. if (!SetNXLock::getExclusiveLock($redisKey)) {
  1123. return apiReturnFail(['web.withdraw.try_again_later', 'Tente novamente mais tarde']);
  1124. }
  1125. $Channel = 0;
  1126. //保持邀请和被邀请的渠道序列统一
  1127. $ActCode = $request->input('act');
  1128. if(strstr($ActCode,'http')){
  1129. $ActCode=explode('http',$ActCode)[0];
  1130. }
  1131. $Package = 'com.uswin.game777';
  1132. $ReferrType = 0;
  1133. if ($ActCode) {
  1134. //使用邀请的Code来保持邀请被邀请的用户注册渠道一致性
  1135. if (strlen($ActCode) > 6) {
  1136. $ActCode = substr($ActCode, 0, 6);
  1137. }
  1138. $link = AgentLinks::getByCode($ActCode);
  1139. if ($link) {
  1140. $inviter = AccountsInfo::where('UserID', $link->UserID)->first();
  1141. if($inviter&&is_object($inviter)) {
  1142. $Channel = $inviter->Channel;
  1143. $ReferrType = 2;
  1144. }
  1145. }
  1146. }
  1147. if(!$Channel){
  1148. //获取默认配置
  1149. // $config = RouteService::getChannelConfig($request);
  1150. //非游客注册
  1151. // while($config->isGuestOpen()&&!$regByGuest){
  1152. // RouteService::clearChannelConfig();
  1153. // $config = RouteService::getChannelConfig($request);
  1154. // }
  1155. $Channel = $config->Channel;
  1156. if($Channel!=env('REGION_24680_DEFAULT_CHANNEL',100))$ReferrType = 1;
  1157. }else{
  1158. //先搜索本地配置
  1159. $config = WebChannelConfig::getByChannel($Channel);
  1160. }
  1161. $Package = $config->PackageName;
  1162. if ($config) {
  1163. //每小时对齐两个表的包名
  1164. if(!Redis::exists('ChannelPackageName'.$Channel)) {
  1165. $pack = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $Channel)->select('PackageName')->first();
  1166. if ($pack) {
  1167. Redis::setex('ChannelPackageName' . $Channel, 3600, $Package);
  1168. if ($Package != $pack->PackageName) {
  1169. DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $Channel)->update(['PackageName' => $Package]);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. $account= $request->account??$request->email ?? $request->phone ?? $FPID;
  1175. //注册到游戏服务器
  1176. $user = $this->registerAccountInfo($request, $Package, $Channel,$account);
  1177. //返回错误
  1178. if (is_array($user) && !isset($user['UserID'])) {
  1179. SetNXLock::release($redisKey);
  1180. return $user;
  1181. }
  1182. if (!$user) {
  1183. SetNXLock::release($redisKey);
  1184. return apiReturnFail(['web.withdraw.try_again_later', 'Pausa de login']);
  1185. }
  1186. //代理注册,保留号段10000-100000
  1187. $UserID = $user['UserID'];
  1188. $GameID = $user['GameID'];
  1189. $password=$request->password;
  1190. $globalUserInfo = GlobalUserInfo::getGameUserInfo('UserID', $UserID);
  1191. if ($globalUserInfo) {
  1192. $GlobalUID = $globalUserInfo->GlobalUID;
  1193. } else {
  1194. // if($type=='guest'){
  1195. // //改成从中心区获取idpass
  1196. // $idps=$this->getGustAccount($UserID);
  1197. // $account=$idps['account'];
  1198. // $password=$idps['password'];
  1199. // }
  1200. $GlobalUID = $this->generateUUID($UserID, $RegisterLocation, $ServerRegion,$Channel??99);
  1201. $ShortHashID = explode('-', $GlobalUID)[0];
  1202. //先搞定userid
  1203. $globalUserInfo = new GlobalUserInfo([
  1204. 'UserID' => $UserID,
  1205. 'GameID' => $GameID,
  1206. 'FF' => $request->input('ff', ''),
  1207. 'FPID' => $FPID,
  1208. 'LastFPID' => $FPID,
  1209. 'ShortHashID' => $ShortHashID,
  1210. 'GlobalUID' => $GlobalUID,
  1211. 'Accounts' => $account, // Assuming email is received from request
  1212. 'Email' => $request->email ?? '', // Assuming email is received from request
  1213. 'Phone' => $Phone ?? '', // Assuming phone is received from request
  1214. 'LogonPass' => Hash::make($password),
  1215. 'LogonIP' => $login_ip,
  1216. 'Gender' => 1,
  1217. 'RegisterIP' => $login_ip,
  1218. 'RegisterLocation' => $RegisterLocation,
  1219. 'ServerRegion' => $ServerRegion,
  1220. 'DefaultLanguage' => $Language,
  1221. 'Channel' => $Channel??100,
  1222. 'RegionID' => $config->isRegionUnique(),
  1223. 'ReferrType' => $ReferrType,
  1224. 'RegisterDate' => date('Y-m-d H:i:s'),
  1225. 'InsurePass' => '',
  1226. 'UserRight' => 0,
  1227. 'Level' => 0,
  1228. 'Exp' => 0,
  1229. 'FaceID' => $user['FaceID'],
  1230. 'NickName' => $user['NickName'],
  1231. 'Registed' =>1,
  1232. 'PwaInstalled' =>$request->input('pwa',0),
  1233. // 'InsurePass' => Hash::make($request->insurePassword),
  1234. // Add other fields as needed
  1235. ]);
  1236. try {
  1237. $globalUserInfo->save();
  1238. } catch (\Exception $exception) {
  1239. Log::error($exception->getMessage());
  1240. }
  1241. }
  1242. GlobalUserInfo::$me=$globalUserInfo;
  1243. if($Channel==env('REGION_24680_DEFAULT_CHANNEL',100)){
  1244. Util::WriteLog('c99',json_encode($_SERVER));
  1245. }
  1246. //注册钱数要归0
  1247. // $newRegGolds=$config->isRegZeroMoneyOpen()?0:$config->BONUS_REG();
  1248. // GameScoreInfo::query()->where('UserID', $UserID)->update(['Score'=>$newRegGolds]);
  1249. $agentUser = AgentService::SetUserAgent($GlobalUID, $UserID, $ActCode);
  1250. SetNXLock::release($redisKey);
  1251. // if ($regByGuest) {
  1252. // return GlobalUserInfo::getGameUserInfo("UserID", $UserID);
  1253. // }
  1254. $cookieParam = $request->input('cookie', '');
  1255. $fbclid = ApkService::extractFbclid($cookieParam);
  1256. ApkService::bindCookie($globalUserInfo, $request->input('s_k', ''), $fbclid, $cookieParam);
  1257. $guser = GlobalUserInfo::toWebData($globalUserInfo,true);
  1258. // if($agentUser->Higher1ID){
  1259. // //获取邀请者信息
  1260. // $inviter=AccountsInfo::where('UserID',$agentUser->Higher1ID)->first();
  1261. // }
  1262. $guser['reg'] = 1;
  1263. //
  1264. // if($type=='guest'){
  1265. // $guser['account'] = $account;
  1266. // $guser['password'] = $password;
  1267. // }
  1268. $defaultGameId = 931;
  1269. $recommendGame = '/game/' . $defaultGameId;
  1270. $guser['recommendGame'] = $recommendGame;
  1271. // 如果用户信息存在,根据GameID的最后一位数字查询映射关系
  1272. if ($guser && isset($guser['GameID'])) {
  1273. $gameId = (string)$guser['GameID'];
  1274. $lastDigit = (int)substr($gameId, -1); // 获取最后一位数字
  1275. // 查询映射关系(带缓存)
  1276. $cacheKey = 'game_number_mapping:' . $lastDigit;
  1277. $mapping = null;
  1278. $cacheHit = false;
  1279. // 尝试从缓存获取
  1280. $cached = Redis::get($cacheKey);
  1281. if ($cached !== null) {
  1282. $decoded = json_decode($cached, true);
  1283. // 如果解码成功且不是空数组,说明有数据
  1284. if (is_array($decoded) && !empty($decoded)) {
  1285. $mapping = (object)$decoded; // 转换为对象以保持兼容性
  1286. $cacheHit = true;
  1287. } elseif ($decoded === []) {
  1288. // 空数组表示数据库中没有记录,已缓存,直接跳过查询
  1289. $cacheHit = true;
  1290. $mapping = null;
  1291. }
  1292. }
  1293. // 缓存未命中,查询数据库
  1294. if (!$cacheHit) {
  1295. $mapping = DB::connection('write')
  1296. ->table('agent.dbo.game_number_mapping')
  1297. ->where('number', $lastDigit)
  1298. ->first();
  1299. // 存入缓存,24小时过期
  1300. if ($mapping) {
  1301. Redis::setex($cacheKey, 86400, json_encode($mapping));
  1302. } else {
  1303. // 即使不存在也缓存,避免频繁查询,缓存5分钟
  1304. Redis::setex($cacheKey, 300, json_encode([]));
  1305. }
  1306. }
  1307. if ($mapping && !empty($mapping) && isset($mapping->game_id) && $mapping->game_id) {
  1308. $defaultGameId = $mapping->game_id;
  1309. $recommendGame = '/game/' . $mapping->game_id;
  1310. }
  1311. $guser['recommendGame'] = $recommendGame;
  1312. }
  1313. $mobileBand = '';
  1314. $ua = $request->userAgent();
  1315. if (stripos($ua, 'iPhone') !== false) {
  1316. $mobileBand = 'iPhone';
  1317. } else if (stripos($ua, 'iPad') !== false) {
  1318. $mobileBand = 'iPad';
  1319. } else if (stripos($ua, 'Android') !== false) {
  1320. $mobileBand = 'Android';
  1321. } else if (stripos($ua, 'Windows') !== false) {
  1322. $mobileBand = 'PC';
  1323. } else if (stripos($ua, 'Mac') !== false) {
  1324. $mobileBand = 'Mac';
  1325. }
  1326. $accUpdate = ['UserMedal' => $defaultGameId];
  1327. if ($mobileBand){
  1328. $accUpdate['LastLogonMobile'] = $mobileBand;
  1329. }
  1330. AccountsInfo::where('UserID', $UserID)->update($accUpdate);
  1331. Util::WriteLog('register_params',[$request,$guser,['Package' => $Package]]);
  1332. //s2s上报
  1333. AfEvent::dispatch([
  1334. 'UserID' => $UserID,
  1335. 'event_name' => 'CompleteRegistration',
  1336. 'custom_data' => [
  1337. 'content_name' => 'register_success',
  1338. 'status' => 1,
  1339. ],
  1340. ]);
  1341. if($request->input('pwa',0)){
  1342. AfEvent::dispatch([
  1343. 'UserID' => $UserID,
  1344. 'event_name' => 'Lead',
  1345. 'custom_data' => [
  1346. 'content_name' => 'Install Pwa2',
  1347. 'status' => 1,
  1348. ],
  1349. ]);
  1350. }
  1351. $this->dispatchIpRiskCheck($UserID);
  1352. return response()->json(apiReturnSuc($guser, ['reg.success', 'Registro realizado com sucesso!']));//->withCookie($this->setLoginCookie($guser['sign']));
  1353. }
  1354. public function registerAccountInfo(Request $request, $PackageName = 'com.uswin.game777', $Channel = 0,$account=null)
  1355. {
  1356. if (empty($Channel) || !$Channel) $Channel = env('REGION_24680_DEFAULT_CHANNEL',100);
  1357. //防止串行
  1358. $app=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $Channel)->first();
  1359. if($app)$PackageName=$app->PackageName;
  1360. $FPID = $request->input("bfp", "");
  1361. $Accounts = $account??$FPID ?? $request->adid ?? $request->gaaid ?? md5(random_bytes(30));
  1362. $SpreadID = 0;
  1363. $Password = $request->password ?? md5(random_bytes(30));
  1364. $FaceI = mt_rand(1, 16);
  1365. $Gender = $request->gender ?? 0;
  1366. $InsurePass = "";
  1367. $Phone = $request->phone ?? "";
  1368. $ip = $request->header("X_REAL_IP") ?? $request->ip();
  1369. $MachineID = $Accounts;
  1370. $cbType = 1;
  1371. if (!empty($Phone)) {
  1372. $cbType = 2;
  1373. }
  1374. $res = StoredProcedure::ALLRegisterAccounts(
  1375. $Accounts,
  1376. '1',
  1377. $SpreadID,
  1378. $Password,
  1379. $InsurePass,
  1380. $FaceI,
  1381. $Gender,
  1382. 1,
  1383. $Phone,
  1384. $ip,
  1385. $MachineID,
  1386. $cbType,
  1387. $Channel,
  1388. $PackageName
  1389. );
  1390. Log::info('注册结果 ' . json_encode($res));
  1391. $ReturnValue = $res['ReturnValue'] ?? 0;
  1392. if (is_bool($res)) {
  1393. $ReturnValue = 3;
  1394. }
  1395. $message = '';
  1396. if ($ReturnValue > 0) {
  1397. switch ($ReturnValue) {
  1398. case 1: # 注册暂停
  1399. return apiReturnFail(['web.reg.fail_suspend', 'Registro suspenso']);
  1400. break;
  1401. case 2: # 登录暂停
  1402. return apiReturnFail(['web.reg.fail_stoplogin', 'Pausa de login']);
  1403. break;
  1404. case 3: # 登录暂停
  1405. return apiReturnFail(['web.withdraw.try_again_later', 'Pausa de login']);
  1406. break;
  1407. case 201: # accounts已经存在
  1408. case 301:
  1409. case 8: # 帐号已存在,请换另一帐号名字尝试再次注册!
  1410. $exist_user = AccountsInfo::where('Accounts', $Accounts . $Channel)->first();
  1411. if ($exist_user) {
  1412. $isexitGuser = GlobalUserInfo::getGameUserInfo('UserID', $exist_user->UserID);
  1413. if ($isexitGuser) {
  1414. return apiReturnFail(['web.reg.fail_account_exist', 'A conta já existe, altere outro nome de conta e tente se registrar novamente!'],compact('res','Accounts'));
  1415. } else {
  1416. $res = $exist_user;
  1417. }
  1418. } else {
  1419. return apiReturnFail(['web.withdraw.try_again_later', 'Pausa de login']);
  1420. }
  1421. break;
  1422. case 10: # IP最大注册数量
  1423. return apiReturnFail(['web.reg.fail_ipmax', 'Mesmo IP não pode registrar várias contas']);
  1424. break;
  1425. }
  1426. }
  1427. Util::WriteLog('login', $res);
  1428. // $user=AccountsInfo::query()->where("Accounts",$Accounts)->first();
  1429. // Util::WriteLog('login',$user);
  1430. return $res;
  1431. }
  1432. protected function setLoginCookie($encryptedGlobalUID)
  1433. {
  1434. // $encryptedGlobalUID = Crypt::encryptString($GlobalUID);
  1435. $cookie = Cookie::make('guuid', $encryptedGlobalUID, 60 * 24 * 365, "/", null, true, false, false, 'None');
  1436. return $cookie;
  1437. }
  1438. static public function clearLoginCookie()
  1439. {
  1440. $cookie = Cookie::make('guuid', "", -60, "/", null, true, false, false, 'None');
  1441. return $cookie;
  1442. }
  1443. }