Login.php 12 KB

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