LoginController.php 70 KB

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