Login.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2025 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\service\passport;
  13. use app\api\model\{Setting as SettingModel, UploadFile as UploadFileModel, User as UserModel};
  14. use app\api\service\{passport\Party as PartyService, user\Oauth as OauthService};
  15. use app\api\validate\passport\Login as ValidateLogin;
  16. use app\common\enum\Client as ClientEnum;
  17. use app\common\enum\Setting as SettingEnum;
  18. use app\common\service\BaseService;
  19. use cores\exception\BaseException;
  20. use think\facade\Cache;
  21. /**
  22. * 服务类:用户登录
  23. * Class Login
  24. * @package app\api\service\passport
  25. */
  26. class Login extends BaseService
  27. {
  28. /**
  29. * 用户信息 (登录成功后才记录)
  30. * @var UserModel|null $userInfo
  31. */
  32. private ?UserModel $userInfo;
  33. // 用于生成token的自定义盐
  34. const TOKEN_SALT = 'user_salt';
  35. /**
  36. * 执行用户登录
  37. * @param array $data
  38. * @return bool
  39. * @throws BaseException
  40. * @throws \think\Exception
  41. * @throws \think\db\exception\DataNotFoundException
  42. * @throws \think\db\exception\DbException
  43. * @throws \think\db\exception\ModelNotFoundException
  44. */
  45. public function login(array $data): bool
  46. {
  47. // 数据验证
  48. $this->validate($data);
  49. // 自动登录注册
  50. $this->register($data);
  51. // 保存第三方用户信息
  52. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  53. // 记录登录态
  54. return $this->setSession();
  55. }
  56. /**
  57. * 快捷登录:微信小程序用户
  58. * @param array $form
  59. * @return bool
  60. * @throws BaseException
  61. * @throws \think\db\exception\DataNotFoundException
  62. * @throws \think\db\exception\DbException
  63. * @throws \think\db\exception\ModelNotFoundException
  64. * @throws \think\Exception
  65. */
  66. public function loginMpWx(array $form): bool
  67. {
  68. // 获取微信小程序登录态(session)
  69. $wxSession = PartyService::getMpWxSession($form['partyData']['code']);
  70. // 判断openid是否存在
  71. $userId = OauthService::getUserIdByOauthId($wxSession['openid'], ClientEnum::MP_WEIXIN);
  72. // 获取用户信息
  73. $userInfo = !empty($userId) ? UserModel::detail($userId) : null;
  74. // 用户信息存在, 更新登录信息
  75. if (!empty($userInfo)) {
  76. // 更新用户登录信息
  77. $this->updateUser($userInfo, true, $form['partyData']);
  78. // 记录登录态
  79. return $this->setSession();
  80. }
  81. // 用户信息不存在 => 注册新用户 或者 跳转到绑定手机号页
  82. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  83. // 后台设置了需强制绑定手机号, 返回前端isBindMobile, 跳转到手机号验证页
  84. if ($setting['isForceBindMpweixin']) {
  85. throwError('当前用户未绑定手机号', null, ['isBindMobile' => true, 'isPrompt' => false]);
  86. }
  87. // 后台未开启强制绑定手机号, 直接保存新用户
  88. if (!$setting['isForceBindMpweixin']) {
  89. // 用户不存在: 创建一个新用户
  90. $this->createUser('', true, $form['partyData']);
  91. // 保存第三方用户信息
  92. $this->createUserOauth($this->getUserId(), true, $form['partyData']);
  93. }
  94. // 记录登录态
  95. return $this->setSession();
  96. }
  97. /**
  98. * 是否需要填写昵称头像 (微信小程序端)
  99. * @param string $code
  100. * @return bool
  101. * @throws BaseException
  102. * @throws \think\db\exception\DataNotFoundException
  103. * @throws \think\db\exception\DbException
  104. * @throws \think\db\exception\ModelNotFoundException
  105. * @throws \think\Exception
  106. */
  107. public function isPersonalMpweixin(string $code): bool
  108. {
  109. // 后台需开启填写微信头像和昵称
  110. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  111. if (!$setting['isPersonalMpweixin']) {
  112. return false;
  113. }
  114. // 获取微信小程序登录态 (session)
  115. $wxSession = PartyService::getMpWxSession($code);
  116. // 判断用户是否存在 (openid)
  117. return !OauthService::getUserIdByOauthId($wxSession['openid'], ClientEnum::MP_WEIXIN);
  118. }
  119. /**
  120. * 快捷登录:微信小程序授权手机号登录
  121. * @param array $form
  122. * @return bool
  123. * @throws BaseException
  124. * @throws \think\db\exception\DataNotFoundException
  125. * @throws \think\db\exception\DbException
  126. * @throws \think\db\exception\ModelNotFoundException
  127. * @throws \think\Exception
  128. */
  129. public function loginMpWxMobile(array $form): bool
  130. {
  131. // 获取微信小程序登录态(session)
  132. $wxSession = PartyService::getMpWxSession($form['code']);
  133. // 解密encryptedData -> 拿到手机号
  134. $plainData = OauthService::wxDecryptData($form['encryptedData'], $form['iv'], $wxSession['session_key']);
  135. // 整理登录注册数据
  136. $loginData = [
  137. 'mobile' => $plainData['purePhoneNumber'],
  138. 'isParty' => $form['isParty'],
  139. 'partyData' => $form['partyData'],
  140. ];
  141. // 自动登录注册
  142. $this->register($loginData);
  143. // 保存第三方用户信息
  144. $this->createUserOauth($this->getUserId(), $loginData['isParty'], $loginData['partyData']);
  145. // 记录登录态
  146. return $this->setSession();
  147. }
  148. /**
  149. * 保存oauth信息(第三方用户信息)
  150. * @param int $userId 用户ID
  151. * @param bool $isParty 是否为第三方用户
  152. * @param array $partyData 第三方用户数据
  153. * @return void
  154. * @throws BaseException
  155. * @throws \think\db\exception\DataNotFoundException
  156. * @throws \think\db\exception\DbException
  157. * @throws \think\db\exception\ModelNotFoundException
  158. */
  159. private function createUserOauth(int $userId, bool $isParty, array $partyData = []): void
  160. {
  161. if ($isParty) {
  162. $Oauth = new PartyService;
  163. $Oauth->createUserOauth($userId, $partyData);
  164. }
  165. }
  166. /**
  167. * 当前登录的用户信息
  168. * @return UserModel
  169. */
  170. public function getUserInfo(): UserModel
  171. {
  172. return $this->userInfo;
  173. }
  174. /**
  175. * 当前登录的用户ID
  176. * @return int
  177. */
  178. private function getUserId(): int
  179. {
  180. return (int)$this->getUserInfo()['user_id'];
  181. }
  182. /**
  183. * 自动登录注册
  184. * @param array $data
  185. * @throws BaseException
  186. * @throws \think\Exception
  187. * @throws \think\db\exception\DataNotFoundException
  188. * @throws \think\db\exception\DbException
  189. * @throws \think\db\exception\ModelNotFoundException
  190. */
  191. private function register(array $data): void
  192. {
  193. // 查询用户是否已存在
  194. // 用户存在: 更新用户登录信息
  195. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  196. if ($userInfo) {
  197. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  198. return;
  199. }
  200. // 用户不存在: 创建一个新用户
  201. $this->createUser($data['mobile'], $data['isParty'], $data['partyData']);
  202. }
  203. /**
  204. * 新增用户
  205. * @param string $mobile 手机号
  206. * @param bool $isParty 是否存在第三方用户信息
  207. * @param array $partyData 用户信息(第三方)
  208. * @return void
  209. * @throws \think\Exception
  210. * @throws \think\db\exception\DataNotFoundException
  211. * @throws \think\db\exception\DbException
  212. * @throws \think\db\exception\ModelNotFoundException
  213. */
  214. private function createUser(string $mobile, bool $isParty, array $partyData = []): void
  215. {
  216. // 用户信息
  217. $data = [
  218. 'mobile' => $mobile,
  219. 'nick_name' => !empty($mobile) ? \hide_mobile($mobile) : '',
  220. 'platform' => \getPlatform(),
  221. 'last_login_time' => \time(),
  222. 'store_id' => $this->storeId
  223. ];
  224. // 写入用户信息(第三方)
  225. if ($isParty === true && !empty($partyData)) {
  226. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  227. $data = \array_merge($data, $partyUserInfo);
  228. }
  229. // 新增用户记录
  230. $model = new UserModel;
  231. $model->save($data);
  232. // 将微信用户昵称添加编号便于后台管理, 例如:微信用户_10001
  233. if (\in_array($data['nick_name'], ['微信用户', '支付宝用户'])) {
  234. $model->save(['nick_name' => "{$data['nick_name']}_{$model['user_id']}"]);
  235. }
  236. // 记录头像文件上传者
  237. if (isset($data['avatar_id']) && $data['avatar_id'] > 0) {
  238. UploadFileModel::setUploaderId($data['avatar_id'], (int)$model['user_id']);
  239. }
  240. // 记录用户信息
  241. $this->userInfo = $model;
  242. }
  243. /**
  244. * 更新用户登录信息
  245. * @param UserModel $userInfo
  246. * @param bool $isParty 是否存在第三方用户信息
  247. * @param array $partyData 用户信息(第三方)
  248. */
  249. private function updateUser(UserModel $userInfo, bool $isParty, array $partyData = []): void
  250. {
  251. // 用户信息
  252. $data = [
  253. 'last_login_time' => \time(),
  254. 'store_id' => $this->storeId
  255. ];
  256. // 写入用户信息(第三方)
  257. // 如果不需要每次登录都更新微信用户头像昵称, 下面几行代码可以屏蔽掉
  258. // if ($isParty === true && !empty($partyData)) {
  259. // $partyUserInfo = PartyService::partyUserInfo($partyData);
  260. // $data = \array_merge($data, $partyUserInfo);
  261. // }
  262. // // 记录头像文件上传者
  263. // if (isset($data['avatar_id']) && $data['avatar_id'] > 0) {
  264. // UploadFileModel::setUploaderId($data['avatar_id'], $userInfo['user_id']);
  265. // }
  266. // 更新用户记录
  267. $userInfo->save($data);
  268. // 记录用户信息
  269. $this->userInfo = $userInfo;
  270. }
  271. /**
  272. * 记录登录态
  273. * @return bool
  274. * @throws BaseException
  275. */
  276. private function setSession(): bool
  277. {
  278. empty($this->userInfo) && \throwError('未找到用户信息');
  279. // 登录的token
  280. $token = $this->getToken($this->getUserId());
  281. // 记录缓存, 30天
  282. Cache::set($token, [
  283. 'user' => $this->userInfo,
  284. 'store_id' => $this->storeId,
  285. 'is_login' => true,
  286. ], 86400 * 30);
  287. return true;
  288. }
  289. /**
  290. * 数据验证
  291. * @param array $data
  292. * @return void
  293. * @throws BaseException
  294. */
  295. private function validate(array $data): void
  296. {
  297. // 数据验证
  298. $validate = new ValidateLogin;
  299. if (!$validate->check($data)) {
  300. throwError($validate->getError());
  301. }
  302. // 验证短信验证码是否匹配
  303. // try {
  304. // CaptchaApi::checkSms($data['smsCode'], $data['mobile']);
  305. //} catch (\Exception $e) {
  306. // throwError($e->getMessage() ?: '短信验证码不正确');
  307. // }
  308. }
  309. /**
  310. * 获取登录的token
  311. * @param int $userId
  312. * @return string
  313. */
  314. public function getToken(int $userId): string
  315. {
  316. static $token = '';
  317. if (empty($token)) {
  318. $token = $this->makeToken($userId);
  319. }
  320. return $token;
  321. }
  322. /**
  323. * 生成用户认证的token
  324. * @param int $userId
  325. * @return string
  326. */
  327. private function makeToken(int $userId): string
  328. {
  329. $storeId = $this->storeId;
  330. // 生成一个不会重复的随机字符串
  331. $guid = \get_guid_v4();
  332. // 当前时间戳 (精确到毫秒)
  333. $timeStamp = \microtime(true);
  334. // 自定义一个盐
  335. $salt = self::TOKEN_SALT;
  336. return md5("{$storeId}_{$timeStamp}_{$userId}_{$guid}_{$salt}");
  337. }
  338. }