LoginController.php 71 KB

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