LoginController.php 50 KB

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