LoginController.php 62 KB

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