LoginController.php 61 KB

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