LoginController.php 68 KB

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