ServiceLogic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\api\logic;
  15. use app\common\cache\WebScanLoginCache;
  16. use app\common\logic\BaseLogic;
  17. use app\api\service\{UserTokenService, WechatUserService};
  18. use app\common\enum\{LoginEnum, user\UserTerminalEnum, YesNoEnum};
  19. use app\common\service\{
  20. ConfigService,
  21. FileService,
  22. wechat\WeChatConfigService,
  23. wechat\WeChatMnpService,
  24. wechat\WeChatOaService,
  25. wechat\WeChatRequestService
  26. };
  27. use app\common\model\agricultural_machinery\UserService;
  28. use app\common\model\user\{User, UserAuth};
  29. use think\facade\{Db, Config};
  30. /**
  31. * 服务商逻辑
  32. * Class LoginLogic
  33. * @package app\api\logic
  34. */
  35. class ServiceLogic extends BaseLogic
  36. {
  37. /**
  38. * @notes 入驻
  39. * @param array $params
  40. * @return bool
  41. * @author 段誉
  42. * @date 2022/9/7 15:37
  43. */
  44. public static function Settled(array $params)
  45. {
  46. Db::startTrans();
  47. try {
  48. // $userSn = User::createUserSn();
  49. // $passwordSalt = Config::get('project.unique_identification');
  50. // $password = create_password($params['password'], $passwordSalt);
  51. // $avatar = ConfigService::get('default_image', 'user_avatar');
  52. UserService::create([
  53. 'user_id' => $params['user_id'],
  54. 'type' => $params['type'] ?? 1,
  55. 'name' => $params['name'],
  56. 'mobile' => $params['mobile'],
  57. 'agricultural_machinery_model' =>$params['agricultural_machinery_model'],
  58. 'images' => $params['images'],
  59. 'cate_id' => $params['cate_id'],
  60. 'area_id' => $params['area_id'],
  61. 'money' => $params['money'],
  62. ]);
  63. Db::commit();
  64. return true;
  65. } catch (\Exception $e) {
  66. Db::rollback();
  67. self::setError($e->getMessage());
  68. return false;
  69. }
  70. }
  71. /**
  72. * @notes 账号/手机号登录,手机号验证码
  73. * @param $params
  74. * @return array|false
  75. * @author 段誉
  76. * @date 2022/9/6 19:26
  77. */
  78. public static function login($params)
  79. {
  80. try {
  81. // 账号/手机号 密码登录
  82. $where = ['account|mobile' => $params['account']];
  83. if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) {
  84. //手机验证码登录
  85. $where = ['mobile' => $params['account']];
  86. }
  87. $user = User::where($where)->findOrEmpty();
  88. if ($user->isEmpty()) {
  89. throw new \Exception('用户不存在');
  90. }
  91. //更新登录信息
  92. $user->login_time = time();
  93. $user->login_ip = request()->ip();
  94. $user->save();
  95. //设置token
  96. $userInfo = UserTokenService::setToken($user->id, $params['terminal']);
  97. //返回登录信息
  98. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  99. $avatar = FileService::getFileUrl($avatar);
  100. return [
  101. 'nickname' => $userInfo['nickname'],
  102. 'sn' => $userInfo['sn'],
  103. 'mobile' => $userInfo['mobile'],
  104. 'avatar' => $avatar,
  105. 'token' => $userInfo['token'],
  106. ];
  107. } catch (\Exception $e) {
  108. self::setError($e->getMessage());
  109. return false;
  110. }
  111. }
  112. /**
  113. * @notes 退出登录
  114. * @param $userInfo
  115. * @return bool
  116. * @throws \think\db\exception\DataNotFoundException
  117. * @throws \think\db\exception\DbException
  118. * @throws \think\db\exception\ModelNotFoundException
  119. * @author 段誉
  120. * @date 2022/9/16 17:56
  121. */
  122. public static function logout($userInfo)
  123. {
  124. //token不存在,不注销
  125. if (!isset($userInfo['token'])) {
  126. return false;
  127. }
  128. //设置token过期
  129. return UserTokenService::expireToken($userInfo['token']);
  130. }
  131. /**
  132. * @notes 获取微信请求code的链接
  133. * @param string $url
  134. * @return string
  135. * @author 段誉
  136. * @date 2022/9/20 19:47
  137. */
  138. public static function codeUrl(string $url)
  139. {
  140. return (new WeChatOaService())->getCodeUrl($url);
  141. }
  142. /**
  143. * @notes 公众号登录
  144. * @param array $params
  145. * @return array|false
  146. * @throws \GuzzleHttp\Exception\GuzzleException
  147. * @author 段誉
  148. * @date 2022/9/20 19:47
  149. */
  150. public static function oaLogin(array $params)
  151. {
  152. Db::startTrans();
  153. try {
  154. //通过code获取微信 openid
  155. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  156. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_OA);
  157. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  158. // 更新登录信息
  159. self::updateLoginInfo($userInfo['id']);
  160. Db::commit();
  161. return $userInfo;
  162. } catch (\Exception $e) {
  163. Db::rollback();
  164. self::$error = $e->getMessage();
  165. return false;
  166. }
  167. }
  168. /**
  169. * @notes 小程序-静默登录
  170. * @param array $params
  171. * @return array|false
  172. * @author 段誉
  173. * @date 2022/9/20 19:47
  174. */
  175. public static function silentLogin(array $params)
  176. {
  177. try {
  178. //通过code获取微信 openid
  179. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  180. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  181. $userInfo = $userServer->getResopnseByUserInfo('silent')->getUserInfo();
  182. if (!empty($userInfo)) {
  183. // 更新登录信息
  184. self::updateLoginInfo($userInfo['id']);
  185. }
  186. return $userInfo;
  187. } catch (\Exception $e) {
  188. self::$error = $e->getMessage();
  189. return false;
  190. }
  191. }
  192. /**
  193. * @notes 小程序-授权登录
  194. * @param array $params
  195. * @return array|false
  196. * @author 段誉
  197. * @date 2022/9/20 19:47
  198. */
  199. public static function mnpLogin(array $params)
  200. {
  201. Db::startTrans();
  202. try {
  203. //通过code获取微信 openid
  204. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  205. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  206. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  207. // 更新登录信息
  208. self::updateLoginInfo($userInfo['id']);
  209. Db::commit();
  210. return $userInfo;
  211. } catch (\Exception $e) {
  212. Db::rollback();
  213. self::$error = $e->getMessage();
  214. return false;
  215. }
  216. }
  217. /**
  218. * @notes 更新登录信息
  219. * @param $userId
  220. * @throws \Exception
  221. * @author 段誉
  222. * @date 2022/9/20 19:46
  223. */
  224. public static function updateLoginInfo($userId)
  225. {
  226. $user = User::findOrEmpty($userId);
  227. if ($user->isEmpty()) {
  228. throw new \Exception('用户不存在');
  229. }
  230. $time = time();
  231. $user->login_time = $time;
  232. $user->login_ip = request()->ip();
  233. $user->update_time = $time;
  234. $user->save();
  235. }
  236. /**
  237. * @notes 小程序端绑定微信
  238. * @param array $params
  239. * @return bool
  240. * @author 段誉
  241. * @date 2022/9/20 19:46
  242. */
  243. public static function mnpAuthLogin(array $params)
  244. {
  245. try {
  246. //通过code获取微信openid
  247. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  248. $response['user_id'] = $params['user_id'];
  249. $response['terminal'] = UserTerminalEnum::WECHAT_MMP;
  250. return self::createAuth($response);
  251. } catch (\Exception $e) {
  252. self::$error = $e->getMessage();
  253. return false;
  254. }
  255. }
  256. /**
  257. * @notes 公众号端绑定微信
  258. * @param array $params
  259. * @return bool
  260. * @throws \GuzzleHttp\Exception\GuzzleException
  261. * @author 段誉
  262. * @date 2022/9/16 10:43
  263. */
  264. public static function oaAuthLogin(array $params)
  265. {
  266. try {
  267. //通过code获取微信openid
  268. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  269. $response['user_id'] = $params['user_id'];
  270. $response['terminal'] = UserTerminalEnum::WECHAT_OA;
  271. return self::createAuth($response);
  272. } catch (\Exception $e) {
  273. self::$error = $e->getMessage();
  274. return false;
  275. }
  276. }
  277. /**
  278. * @notes 生成授权记录
  279. * @param $response
  280. * @return bool
  281. * @throws \Exception
  282. * @author 段誉
  283. * @date 2022/9/16 10:43
  284. */
  285. public static function createAuth($response)
  286. {
  287. //先检查openid是否有记录
  288. $isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty();
  289. if (!$isAuth->isEmpty()) {
  290. throw new \Exception('该微信已被绑定');
  291. }
  292. if (isset($response['unionid']) && !empty($response['unionid'])) {
  293. //在用unionid找记录,防止生成两个账号,同个unionid的问题
  294. $userAuth = UserAuth::where(['unionid' => $response['unionid']])
  295. ->findOrEmpty();
  296. if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
  297. throw new \Exception('该微信已被绑定');
  298. }
  299. }
  300. //如果没有授权,直接生成一条微信授权记录
  301. UserAuth::create([
  302. 'user_id' => $response['user_id'],
  303. 'openid' => $response['openid'],
  304. 'unionid' => $response['unionid'] ?? '',
  305. 'terminal' => $response['terminal'],
  306. ]);
  307. return true;
  308. }
  309. /**
  310. * @notes 获取扫码登录地址
  311. * @return array|false
  312. * @author 段誉
  313. * @date 2022/10/20 18:23
  314. */
  315. public static function getScanCode($redirectUri)
  316. {
  317. try {
  318. $config = WeChatConfigService::getOpConfig();
  319. $appId = $config['app_id'];
  320. $redirectUri = UrlEncode($redirectUri);
  321. // 设置有效时间标记状态, 超时扫码不可登录
  322. $state = MD5(time().rand(10000, 99999));
  323. (new WebScanLoginCache())->setScanLoginState($state);
  324. // 扫码地址
  325. $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
  326. return ['url' => $url];
  327. } catch (\Exception $e) {
  328. self::$error = $e->getMessage();
  329. return false;
  330. }
  331. }
  332. /**
  333. * @notes 网站扫码登录
  334. * @param $params
  335. * @return array|false
  336. * @author 段誉
  337. * @date 2022/10/21 10:28
  338. */
  339. public static function scanLogin($params)
  340. {
  341. Db::startTrans();
  342. try {
  343. // 通过code 获取 access_token,openid,unionid等信息
  344. $userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
  345. if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
  346. throw new \Exception('获取用户授权信息失败');
  347. }
  348. // 获取微信用户信息
  349. $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
  350. // 生成用户或更新用户信息
  351. $userServer = new WechatUserService($response, UserTerminalEnum::PC);
  352. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  353. // 更新登录信息
  354. self::updateLoginInfo($userInfo['id']);
  355. Db::commit();
  356. return $userInfo;
  357. } catch (\Exception $e) {
  358. Db::rollback();
  359. self::$error = $e->getMessage();
  360. return false;
  361. }
  362. }
  363. /**
  364. * @notes 更新用户信息
  365. * @param $params
  366. * @param $userId
  367. * @return User
  368. * @author 段誉
  369. * @date 2023/2/22 11:19
  370. */
  371. public static function updateUser($params, $userId)
  372. {
  373. return User::where(['id' => $userId])->update([
  374. 'nickname' => $params['nickname'],
  375. 'avatar' => FileService::setFileUrl($params['avatar']),
  376. 'is_new_user' => YesNoEnum::NO
  377. ]);
  378. }
  379. }