LoginController.php 63 KB

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