LoginController.php 50 KB

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