LoginController.php 62 KB

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