LoginController.php 51 KB

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