2
0

LoginController.php 61 KB

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