LoginController.php 69 KB

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