MemberService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Common;
  12. use App\Helpers\Jwt;
  13. use App\Models\ActionLogModel;
  14. use App\Models\MemberModel;
  15. use App\Models\ShopModel;
  16. use App\Services\BaseService;
  17. use App\Services\RedisService;
  18. use phpQrcode\QRcode;
  19. /**
  20. * 会员管理-服务类
  21. * @author laravel开发员
  22. * @since 2020/11/11
  23. * Class MemberService
  24. * @package App\Services\Common
  25. */
  26. class MemberService extends BaseService
  27. {
  28. // 静态对象
  29. protected static $instance = null;
  30. /**
  31. * 构造函数
  32. * @author laravel开发员
  33. * @since 2020/11/11
  34. * MemberService constructor.
  35. */
  36. public function __construct()
  37. {
  38. $this->model = new MemberModel();
  39. }
  40. /**
  41. * 静态入口
  42. * @return static|null
  43. */
  44. public static function make()
  45. {
  46. if (!self::$instance) {
  47. self::$instance = (new static());
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * 获取资料详情
  53. * @param $where
  54. * @param array $field
  55. */
  56. public function getInfo($where, array $field = [])
  57. {
  58. $field = $field ? $field : ['id', 'username', 'realname', 'nickname','code','parent_id', 'openid','score_rate', 'idcard', 'idcard_check', 'idcard_front_img', 'idcard_back_img', 'member_level', 'bonus','bonus_total','score', 'status', 'avatar'];
  59. if (is_array($where)) {
  60. $info = $this->model->where($where)->select($field)->first();
  61. } else {
  62. $info = $this->model->where(['id' => (int)$where])->select($field)->first();
  63. }
  64. $info = $info ? $info->toArray() : [];
  65. if ($info) {
  66. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : '';
  67. $info['bonus'] = round($info['bonus'],0);
  68. $info['show_bonus'] = GoodsService::make()->checkNewGoods($info['id']);
  69. // 二维码
  70. $qrcode = $this->makeQrcode(env('WEB_URL').'h5/#/pages/register/index?code='.$info['code']);
  71. $info['qrcode'] = $qrcode? get_image_url($qrcode):'';
  72. }
  73. return $info;
  74. }
  75. /**
  76. * 用户登录
  77. * @param $params
  78. * @return array|false
  79. */
  80. public function login($params)
  81. {
  82. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  83. $password = isset($params['password']) ? $params['password'] : '';
  84. $shopCode = isset($params['shop_code']) ? $params['shop_code'] : '';
  85. if (empty($mobile) || empty($password)) {
  86. $this->error = 2009;
  87. return false;
  88. }
  89. if(empty($shopCode)){
  90. $this->error = 2010;
  91. return false;
  92. }
  93. // 验证店铺
  94. if(!$shopId = ShopModel::where(['code'=> $shopCode,'status'=>1,'mark'=>1])->value('id')){
  95. $this->error = 2011;
  96. return false;
  97. }
  98. // 用户验证
  99. $info = $this->model->getOne([['mobile', '=', $mobile]]);
  100. if (!$info) {
  101. $this->error = 2001;
  102. return false;
  103. }
  104. // 密码校验
  105. $password = get_password($password . md5($password . env('APP_NAME')));
  106. if ($password != $info['password']) {
  107. $this->error = 2002;
  108. return false;
  109. }
  110. // 使用状态校验
  111. if ($info['status'] != 1) {
  112. $this->error = 2012;
  113. return false;
  114. }
  115. // 设置日志标题
  116. ActionLogModel::setTitle("会员登录");
  117. ActionLogModel::record($info);
  118. // JWT生成token
  119. $jwt = new Jwt('jwt_app');
  120. $token = $jwt->getToken($info['id']);
  121. RedisService::set("stores:auths:info:{$info['id']}", $info, 5, 10);
  122. // 登录
  123. $updateData = ['login_time' => time(),'login_shop_id'=> $shopId,'login_count'=>$info['login_count']+1, 'login_ip' => get_client_ip()];
  124. $this->model->where(['id' => $info['id']])->update($updateData);
  125. // 登录数据
  126. return [
  127. 'token' => $token,
  128. 'user_id' => $info['id'],
  129. 'shop_id' => $shopId,
  130. ];
  131. }
  132. /**
  133. * 用户注册
  134. * @param $params
  135. * @return bool
  136. */
  137. public function register($params)
  138. {
  139. // 检测账号是否存在
  140. if ($this->checkExists('mobile', $params['mobile'])) {
  141. $this->error = '2005';
  142. return false;
  143. }
  144. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  145. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  146. $password = isset($params['password']) ? trim($params['password']) : '';
  147. $safePassword = isset($params['safe_password']) ? trim($params['safe_password']) : '';
  148. $inviteCode = isset($params['invite_code']) ? trim($params['invite_code']) : '';
  149. $inviteInfo = $this->model->where(['code'=> $inviteCode,'mark'=>1])->select(['id','code','username','parents'])->first();
  150. if(empty($inviteInfo)){
  151. $this->error = '2013';
  152. return false;
  153. }
  154. $parentId = isset($inviteInfo['id'])? $inviteInfo['id'] : 0;
  155. $parents = isset($inviteInfo['parents'])? $inviteInfo['parents'] : '';
  156. $parents = $parents? rtrim($parents,',').",{$parentId}," : "{$parentId},";
  157. $data = [
  158. 'nickname' => $nickname,
  159. 'username' => strtoupper('U'.get_random_code(7)),
  160. 'password' => get_password($password . md5($password . env('APP_NAME'))),
  161. 'safe_password' => get_password($safePassword . md5($safePassword . env('APP_NAME'))),
  162. 'mobile' => $mobile,
  163. 'parents' => $parents,
  164. 'parent_id' => $parentId,
  165. 'status' => 1,
  166. 'mark' => 1,
  167. 'create_time' => time(),
  168. ];
  169. if ($id = $this->model->edit($data)) {
  170. $this->model->where(['id'=> $id])->update(['code'=> strtoupper('Q'.get_random_code(8))]);
  171. $this->error = 2008;
  172. return true;
  173. }
  174. $this->error = 2007;
  175. return false;
  176. }
  177. /**
  178. * @param $params
  179. * @param int $pageSize
  180. * @return array
  181. */
  182. public function getDataList($params, $pageSize = 15)
  183. {
  184. $where = ['a.mark' => 1];
  185. $status = isset($params['status'])? $params['status'] : 0;
  186. $parentId = isset($params['parent_id'])? $params['parent_id'] : 0;
  187. if($parentId>0){
  188. $where['a.parent_id'] = $parentId;
  189. }
  190. if($status>0){
  191. $where['a.status'] = $status;
  192. }
  193. $list = $this->model->from('member as a')
  194. ->leftJoin('shop as b', 'b.user_id', '=', 'a.id')
  195. ->leftJoin('member as c', 'c.id', '=', 'a.parent_id')
  196. ->where($where)
  197. ->where(function ($query) use($params){
  198. $keyword = isset($params['keyword'])? $params['keyword'] : '';
  199. if($keyword){
  200. $query->where('a.username','like',"%{$keyword}%")->orWhere('a.mobile','like',"%{$keyword}%");
  201. }
  202. })
  203. ->select(['a.*','b.id as shop_id','b.name as shop_name','c.code as parent_code','c.nickname as parent_name'])
  204. ->orderBy('a.create_time','desc')
  205. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  206. $list = $list? $list->toArray() :[];
  207. if($list){
  208. foreach($list['data'] as &$item){
  209. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H.i.s') : '';
  210. $item['login_time'] = $item['login_time']? datetime($item['login_time'],'Y-m-d H.i.s') : '';
  211. $item['avatar'] = isset($item['avatar']) && $item['avatar']? get_image_url($item['avatar']) : '';
  212. $item['parent_code'] = isset($item['parent_code']) && $item['parent_code']? $item['parent_code'] : '无';
  213. $item['invite_num'] = MemberService::make()->getInviteNums($item['id']);
  214. }
  215. }
  216. return [
  217. 'pageSize'=> $pageSize,
  218. 'total'=>isset($list['total'])? $list['total'] : 0,
  219. 'list'=> isset($list['data'])? $list['data'] : []
  220. ];
  221. }
  222. /**
  223. * 直推用户数
  224. * @param $userId
  225. * @return array|mixed
  226. */
  227. public function getInviteNums($userId)
  228. {
  229. $cacheKey = "caches:member:inviteNums";
  230. $data = RedisService::get($cacheKey);
  231. if($data){
  232. return $data;
  233. }
  234. $data = $this->model->where(['parent_id'=> $userId, 'mark'=> 1])->count('id');
  235. if($data){
  236. RedisService::set($cacheKey, $data, rand(3, 5));
  237. }
  238. return $data;
  239. }
  240. /**
  241. * 上级用户列表
  242. * @return array
  243. */
  244. public function parents()
  245. {
  246. // 获取参数
  247. $param = request()->all();
  248. // 用户ID
  249. $keyword = getter($param, "keyword");
  250. $parentId = getter($param, "parent_id");
  251. $userId = getter($param, "user_id");
  252. $datas = $this->model->where(function($query) use($parentId){
  253. if($parentId){
  254. $query->where(['id'=> $parentId,'mark'=>1]);
  255. }else{
  256. $query->where(['status'=> 1,'mark'=>1]);
  257. }
  258. })
  259. ->where(function($query) use($userId){
  260. if($userId){
  261. $query->whereNotIn('id', [$userId]);
  262. }
  263. })
  264. ->where(function($query) use($keyword){
  265. if($keyword){
  266. $query->where('username','like',"{$keyword}%")->orWhere('mobile','like',"{$keyword}%");
  267. }
  268. })
  269. ->select(['id','username','code','nickname','status'])
  270. ->get();
  271. return $datas? $datas->toArray() : [];
  272. }
  273. /**
  274. * 生成普通参数二维码
  275. * @param $str 参数
  276. * @param bool $refresh 是否重新生成
  277. * @return bool
  278. */
  279. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  280. {
  281. $qrFile = '/images/qrcode/';
  282. if (!is_dir('/uploads' . $qrFile)) {
  283. @mkdir('./uploads' . $qrFile, 0755, true);
  284. }
  285. $qrFile = $qrFile . 'C_' . strtoupper(md5($str . '_' . $size . $margin . $level)) . '.png';
  286. $cacheKey = "caches:qrcodes:member_" . md5($str);
  287. if (RedisService::get($cacheKey) && is_file('/uploads' . $qrFile) && !$refresh) {
  288. //return $qrFile;
  289. }
  290. QRcode::png($str, './uploads' . $qrFile, $level, $size, $margin);
  291. if (!file_exists('./uploads' . $qrFile)) {
  292. return false;
  293. }
  294. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  295. return $qrFile;
  296. }
  297. /**
  298. * 推荐树
  299. * @return array|false|mixed
  300. */
  301. public function getTree()
  302. {
  303. // 请求参数
  304. $keyword = request()->post('keyword','');
  305. $cacheKey = "caches:member:trees:".md5('t'.$keyword);
  306. $datas = RedisService::get($cacheKey);
  307. if($datas){
  308. return $datas;
  309. }
  310. $datas = $this->model->where(['status'=>1,'mark'=>1])
  311. ->select(['id','username','nickname','mobile','parent_id','status'])
  312. ->get()->keyBy('id');
  313. $datas = $datas? $datas->toArray() : [];
  314. $pid = 0;
  315. if($keyword){
  316. $data = $this->model->where(function($query) use($keyword){
  317. $query->where('nickname','like',"{$keyword}%")->orWhere('mobile','like',"{$keyword}%");
  318. })
  319. ->where(['status'=>1,'mark'=>1])
  320. ->orderBy('parent_id','asc')
  321. ->select(['id','parent_id','nickname','mobile','username'])
  322. ->first();
  323. $nickname = isset($data['nickname'])? $data['nickname'] : '';
  324. $username = isset($data['username'])? $data['username'] : '';
  325. $mobile = isset($data['mobile'])? $data['mobile'] : '';
  326. if($data){
  327. $pid = isset($data['id'])? $data['id'] : 0;
  328. $data['label'] = $nickname.($mobile?"({$mobile})":"");
  329. unset($data['nickname']);
  330. unset($data['username']);
  331. }
  332. }
  333. $datas = get_tree($datas, $pid);
  334. if($datas){
  335. if($pid){
  336. $data['children'] = $datas;
  337. $newDatas[0] = $data;
  338. $datas = $newDatas;
  339. }
  340. RedisService::set($cacheKey, $datas, rand(3,5));
  341. }
  342. return $datas;
  343. }
  344. /**
  345. * 添加会编辑会员
  346. * @return array
  347. * @since 2020/11/11
  348. * @author laravel开发员
  349. */
  350. public function edit()
  351. {
  352. // 请求参数
  353. $data = request()->all();
  354. // 头像处理
  355. $avatar = isset($data['avatar'])? trim($data['avatar']) : '';
  356. if ($avatar && strpos($avatar, "temp")) {
  357. $data['avatar'] = save_image($avatar, 'member');
  358. } else if($avatar){
  359. $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
  360. }
  361. return parent::edit($data); // TODO: Change the autogenerated stub
  362. }
  363. /**
  364. * 重置密码
  365. * @return array
  366. * @since 2020/11/14
  367. * @author laravel开发员
  368. */
  369. public function resetPwd()
  370. {
  371. // 获取参数
  372. $param = request()->all();
  373. // 用户ID
  374. $userId = getter($param, "id");
  375. if (!$userId) {
  376. return message("用户ID不能为空", false);
  377. }
  378. $userInfo = $this->model->getInfo($userId);
  379. if (!$userInfo) {
  380. return message("用户信息不存在", false);
  381. }
  382. // 设置新密码
  383. $password = '123456';
  384. $userInfo['password'] = get_password($password . md5($password.env('APP_NAME')));
  385. $result = $this->model->edit($userInfo);
  386. if (!$result) {
  387. return message("重置密码失败", false);
  388. }
  389. return message("重置密码成功");
  390. }
  391. /**
  392. * 修改账号
  393. * @param $userId
  394. * @param $params
  395. * @return bool
  396. */
  397. public function modify($userId, $params)
  398. {
  399. $username = isset($params['username']) ? $params['username'] : '';
  400. $newUsername = isset($params['new_username']) ? $params['new_username'] : '';
  401. $password = isset($params['password']) ? $params['password'] : '';
  402. if (empty($username) || empty($password)) {
  403. $this->error = 1013;
  404. return false;
  405. }
  406. // 用户验证
  407. $info = $this->model->getOne([['username', '=', $username]]);
  408. if (!$info || $info['id'] != $userId) {
  409. $this->error = 2001;
  410. return false;
  411. }
  412. // 使用状态校验
  413. if ($info['status'] != 1) {
  414. $this->error = 2009;
  415. return false;
  416. }
  417. // 密码校验
  418. $password = get_password($password . md5($password . 'otc'));
  419. if ($password != $info['password']) {
  420. $this->error = 2002;
  421. return false;
  422. }
  423. $checkInfo = $this->model->getOne([['username', '=', $newUsername]]);
  424. if ($checkInfo && $checkInfo['id'] != $info['id']) {
  425. $this->error = 2005;
  426. return false;
  427. }
  428. if (!$this->model->where(['id' => $info['id']])->update(['username' => $newUsername, 'update_time' => time()])) {
  429. $this->error = 2021;
  430. return false;
  431. }
  432. $this->error = 2020;
  433. return true;
  434. }
  435. /**
  436. * 修改更新登录密码
  437. * @param $userId
  438. * @param $params
  439. * @return bool
  440. */
  441. public function updatePassword($userId, $params)
  442. {
  443. $username = isset($params['username']) ? $params['username'] : '';
  444. $password = isset($params['password']) ? $params['password'] : '';
  445. if (empty($username) || empty($password)) {
  446. $this->error = 1013;
  447. return false;
  448. }
  449. // 用户验证
  450. $info = $this->model->getOne([['username', '=', $username]]);
  451. if (!$info || $info['id'] != $userId) {
  452. $this->error = 2001;
  453. return false;
  454. }
  455. // 使用状态校验
  456. if ($info['status'] != 1) {
  457. $this->error = 2009;
  458. return false;
  459. }
  460. // 更新登录密码
  461. $password = get_password($password . md5($password . 'otc'));
  462. if (!$this->model->where(['id' => $info['id']])->update(['password' => $password, 'update_time' => time()])) {
  463. $this->error = 2025;
  464. return false;
  465. }
  466. $this->error = 2024;
  467. return true;
  468. }
  469. }