LoginController.php 51 KB

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