LoginController.php 69 KB

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