LoginController.php 51 KB

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