2
0

LoginController.php 64 KB

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