LoginController.php 59 KB

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