MemberService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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\Api;
  12. use App\Models\ActionLogModel;
  13. use App\Models\GoodsModel;
  14. use App\Models\MemberBankModel;
  15. use App\Models\MemberModel;
  16. use App\Services\BaseService;
  17. use App\Services\ConfigService;
  18. use App\Services\JwtService;
  19. use App\Services\MpService;
  20. use App\Services\RedisService;
  21. use Illuminate\Support\Facades\DB;
  22. use phpQrcode\QRcode;
  23. /**
  24. * 会员管理-服务类
  25. * @author laravel开发员
  26. * @since 2020/11/11
  27. * Class MemberService
  28. * @package App\Services\Api
  29. */
  30. class MemberService extends BaseService
  31. {
  32. // 静态对象
  33. protected static $instance = null;
  34. /**
  35. * 构造函数
  36. * @author laravel开发员
  37. * @since 2020/11/11
  38. * MemberService constructor.
  39. */
  40. public function __construct()
  41. {
  42. $this->model = new MemberModel();
  43. }
  44. /**
  45. * 静态入口
  46. * @return MemberService|static|null
  47. */
  48. public static function make()
  49. {
  50. if (!self::$instance) {
  51. self::$instance = new static();
  52. }
  53. return self::$instance;
  54. }
  55. /**
  56. * 验证账号
  57. * @param $code
  58. * @param array $params
  59. * @return array|false
  60. */
  61. public function login($code, $params = [])
  62. {
  63. // 账号登录
  64. if (empty($code)) {
  65. $this->error = 1041;
  66. return false;
  67. }
  68. // 获取用户信息
  69. $result = MpService::make()->getUserInfo($code);
  70. $openid = isset($result['openid']) ? $result['openid'] : '';
  71. if (empty($openid)) {
  72. $this->error = 1042;
  73. return false;
  74. }
  75. // 验证是否注册,没有则注册
  76. $where = ['openid' => $openid,'mark'=>1];
  77. $data = $this->model->where($where)
  78. ->select(['id', 'openid', 'mobile','area_id','buy_type', 'user_type', 'nickname', 'avatar', 'code', 'status', 'mark'])
  79. ->first();
  80. $data = $data ? $data->toArray() : [];
  81. $userId = isset($data['id']) ? $data['id'] : 0;
  82. $status = isset($data['status']) ? $data['status'] : 0;
  83. $mobile = isset($data['mobile']) ? $data['mobile'] : '';
  84. $nickname = isset($data['nickname']) ? $data['nickname'] : '';
  85. $avatar = isset($data['nickname']) ? $data['avatar'] : '';
  86. if($data && $status!= 1){
  87. $this->error = '账号已被冻结,请联系客服~';
  88. return false;
  89. }
  90. // 未注册或未完善资料
  91. if(empty($data) || empty($nickname) || empty($mobile)){
  92. return [
  93. 'access_token'=>'',
  94. 'info'=>['uid'=>$userId, 'openid'=>$openid,'mobile'=>$mobile]
  95. ];
  96. }
  97. // 已注册
  98. $system = isset($params['system']) ? $params['system'] : [];
  99. $system = $system && !is_array($system) ? json_decode($system, true) : $system;
  100. $appSources = isset($system['app_sources']) && $system['app_sources'] ? $system['app_sources'] : 'ios';
  101. $uuid = isset($system['uuid']) ? $system['uuid'] : '';
  102. $version = isset($system['app_version']) ? $system['app_version'] : '';
  103. if (!RedisService::get("caches:members:login_{$userId}")) {
  104. $updateData = [
  105. 'login_ip' => get_client_ip(),
  106. 'login_time' => time(),
  107. 'app_uuid' => $uuid,
  108. 'login_count' => DB::raw("login_count+1"),
  109. 'app_version' => $version,
  110. 'device' => $appSources == 'ios' ? 1 : 2,
  111. 'mark' => 1,
  112. ];
  113. $this->model->where(['id' => $userId])->update($updateData);
  114. RedisService::set("caches:members:login_{$userId}", $updateData, rand(30, 60));
  115. }
  116. // 获取登录授权token
  117. $token = JwtService::make()->encode($userId);
  118. // 结果返回
  119. $result = [
  120. 'access_token' => $token,
  121. 'info' => ['id' => $userId, 'openid' => $openid,'nickname'=>$nickname, 'mobile' => $mobile],
  122. ];
  123. // 用户缓存信息
  124. $this->error = 2019;
  125. $data['token'] = $token;
  126. unset($data['mobile']);
  127. RedisService::keyDel("caches:members:teamList*");
  128. RedisService::set("caches:index:area_".get_client_ip(),['uid'=>$userId,'area_id'=>$data['area_id'],'buy_type'=>$data['buy_type']], 6 * 30 * 86400);
  129. RedisService::set("auths:info:{$userId}", $data, 24 * 3600);
  130. RedisService::set("caches:members:cacheInfo_{$userId}", $data, 600);
  131. return $result;
  132. }
  133. /**
  134. * 授权注册
  135. * @param $code
  136. * @param array $params
  137. * @return array|false
  138. */
  139. public function register($params = [])
  140. {
  141. $openid = isset($params['openid'])? $params['openid'] : '';
  142. $areaId = isset($params['area_id']) && $params['area_id']? $params['area_id'] : 0;
  143. $phone = isset($params['mobile'])? $params['mobile'] : '';
  144. $avatar = isset($params['avatar'])? $params['avatar'] : '';
  145. $nickname = isset($params['nickname'])? $params['nickname'] : '';
  146. if(empty($openid)){
  147. $this->error = '请先获取授权';
  148. return false;
  149. }
  150. // 所属区域
  151. if($areaId<=0){
  152. $this->error = '请设置您所在区域';
  153. return false;
  154. }
  155. // 手机号
  156. if (empty($phone)) {
  157. $this->error = '请先授权获取手机号';
  158. return false;
  159. }
  160. if(empty($avatar) || empty($nickname)){
  161. $this->error = '请先授权设置用户信息';
  162. return false;
  163. }
  164. $avatar = save_base64_image($avatar, 'avatar');
  165. // 验证是否注册,没有则注册
  166. $where = ['openid' => $openid,'mark'=>1];
  167. $data = $this->model->where($where)
  168. ->select(['id', 'openid', 'mobile','area_id','buy_type', 'user_type', 'nickname', 'avatar', 'code', 'status', 'mark'])
  169. ->first();
  170. $data = $data ? $data->toArray() : [];
  171. $userId = isset($data['id']) ? $data['id'] : 0;
  172. $status = isset($data['status']) ? $data['status'] : 0;
  173. if ($data && $userId && $status != 1) {
  174. $this->error = '账号已被冻结,请来奶昔客服~';
  175. return false;
  176. }
  177. $system = isset($params['system']) ? $params['system'] : [];
  178. $system = $system && !is_array($system) ? json_decode($system, true) : $system;
  179. $appSources = isset($system['app_sources']) && $system['app_sources'] ? $system['app_sources'] : 'ios';
  180. $uuid = isset($system['uuid']) ? $system['uuid'] : '';
  181. $version = isset($system['app_version']) ? $system['app_version'] : '';
  182. if (empty($data)) {
  183. // 清理无效注册数据
  184. $this->model->where(['openid'=>$openid,'mark'=>0])->delete();
  185. // 用户ID
  186. $userId = $this->model->max('id') + 1;
  187. // 推荐人
  188. $rid = isset($params['rid']) ? intval($params['rid']) : 0;
  189. $parents = '';
  190. if ($rid) {
  191. $inviteInfo = $this->model->where(['id' => $rid, 'mark' => 1])
  192. ->select(['id', 'parent_id', 'parents', 'status'])
  193. ->first();
  194. $rid = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  195. $parents = isset($inviteInfo['parents']) ? $inviteInfo['parents'] : '';
  196. if ($inviteInfo) {
  197. $parents = $parents ? $parents . $rid . ',' : ",{$rid},";
  198. }else{
  199. $rid = 1;
  200. $parents = ',1,';
  201. }
  202. }else{
  203. $rid = 1;
  204. $parents = ',1,';
  205. }
  206. // 滑落节点
  207. $pointId = 0;
  208. $points = '';
  209. $pointSorts = '';
  210. if($rid>0){
  211. $pointData = $this->getPointParentId($rid);
  212. $pointId = isset($pointData['point_id'])?$pointData['point_id'] : 0;
  213. $pointSort = isset($pointData['point_sort']) && $pointData['point_sort']?$pointData['point_sort'] : 0;
  214. if($pointId){
  215. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points','point_sort'])->first();
  216. $points = isset($pointParent['points']) && $pointParent['points']? $pointParent['points'].$pointId.',' : ($pointId ? $pointId . ',' : '');
  217. $pointSorts = isset($pointParent['point_sort']) && $pointParent['point_sort']? $pointParent['point_sort'].''.$pointSort : $pointSort;
  218. }
  219. }
  220. DB::beginTransaction();
  221. $data = [
  222. 'nickname' => $nickname,
  223. 'openid' => $openid,
  224. 'mobile' => $phone,
  225. 'avatar' => $avatar,
  226. 'parent_id' => $rid,
  227. 'parents' => $parents,
  228. 'point_id' => $pointId,
  229. 'buy_type' => $areaId,
  230. 'area_id' => $areaId,
  231. 'points' => $points,
  232. 'point_sort' => $pointSorts,
  233. 'code' => get_random_code(9, 'Q', $userId),
  234. 'password' => get_password('a123456'),
  235. 'login_ip' => get_client_ip(),
  236. 'create_time' => time(),
  237. 'login_time' => time(),
  238. 'login_count' => DB::raw("login_count+1"),
  239. 'app_version' => $version,
  240. 'app_uuid' => $uuid,
  241. 'device' => $appSources == 'ios' ? 1 : 2,
  242. ];
  243. if (!$userId = $this->model->insertGetId($data)) {
  244. DB::rollBack();
  245. $this->error = 2018;
  246. return false;
  247. }
  248. DB::commit();
  249. } // 更新登录信息
  250. else if (!RedisService::get("caches:members:login_{$userId}")) {
  251. $updateData = [
  252. 'login_ip' => get_client_ip(),
  253. 'login_time' => time(),
  254. 'app_uuid' => $uuid,
  255. 'login_count' => DB::raw("login_count+1"),
  256. 'app_version' => $version,
  257. 'device' => $appSources == 'ios' ? 1 : 2,
  258. 'mark' => 1,
  259. ];
  260. $this->model->where(['id' => $userId])->update($updateData);
  261. RedisService::set("caches:members:login_{$userId}", $updateData, rand(30, 60));
  262. }
  263. // 获取登录授权token
  264. $token = JwtService::make()->encode($userId);
  265. // 结果返回
  266. $result = [
  267. 'access_token' => $token,
  268. 'info' => ['id' => $userId, 'openid' => $openid, 'mobile' => $data['mobile']],
  269. ];
  270. // 用户缓存信息
  271. $this->error = 2019;
  272. $data['token'] = $token;
  273. unset($data['mobile']);
  274. RedisService::keyDel("caches:members:teamList*");
  275. RedisService::set("caches:index:area_".get_client_ip(),['uid'=>$userId,'area_id'=>$data['area_id'],'buy_type'=>$data['buy_type']], 6 * 30 * 86400);
  276. RedisService::set("auths:info:{$userId}", $data, 24 * 3600);
  277. RedisService::set("caches:members:cacheInfo_{$userId}", $data, 600);
  278. return $result;
  279. }
  280. /**
  281. * 获取点对点上级节点
  282. * @param $userId 推荐人ID
  283. * @return int|mixed
  284. */
  285. public function getPointParentId($userId)
  286. {
  287. if($userId<=0){
  288. return 0;
  289. }
  290. // 上级
  291. $parentId = $this->model->where(['id'=>$userId])->value('parent_id');
  292. // 自己团队和平级用户
  293. $userList = $this->model->where(['mark'=> 1])
  294. ->whereNotIn('id',[$userId])
  295. ->where(function($query) use($userId,$parentId){
  296. $query->whereRaw('FIND_IN_SET(?,points)', $userId);
  297. // 节点平级用户
  298. if($parentId>0){
  299. $query->orWhereRaw('point_id', $parentId);
  300. }
  301. })
  302. ->select(['id','point_id','point_sort','points'])
  303. ->orderBy('point_sort','asc')
  304. ->orderBy('id','asc')
  305. ->get();
  306. $userList = $userList? $userList->toArray() : [];
  307. if(count($userList) < 2){
  308. return $userId;
  309. }
  310. $users = [];
  311. foreach($userList as $item){
  312. $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
  313. $points = array_filter($points);
  314. $users[$item['id']]['pointLen'] = count($points);
  315. $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
  316. $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
  317. }
  318. $pointId = 0;
  319. $tempPointLen = 0;
  320. $tempChildren = 0;
  321. foreach ($userList as $item) {
  322. $id = isset($item['id'])? $item['id'] : 0;
  323. $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
  324. $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
  325. //dump("ID:{$id}-{$pointId}-{$tempChildren}-{$children}-{$pointLen}");
  326. if($pointLen<=$tempPointLen || $pointId == 0){
  327. if($children < 2 && $pointId <= 0){
  328. $pointId = $id;
  329. $tempPointLen = $pointLen;
  330. $tempChildren = $children+1;
  331. }
  332. }
  333. }
  334. return ['point_id'=>$pointId,'point_sort'=>$tempChildren];
  335. }
  336. /**
  337. * 重置密码
  338. * @param $params
  339. * @return array|false
  340. */
  341. public function forget($params)
  342. {
  343. // 账号登录
  344. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  345. $password = isset($params['password']) ? trim($params['password']) : '';
  346. if (empty($params) || empty($mobile) || empty($password)) {
  347. $this->error = 1041;
  348. return false;
  349. }
  350. // 验证是否注册
  351. if (!$userId = $this->model->where(['mobile' => $mobile, 'mark' => 1])->value('id')) {
  352. $this->error = 1038;
  353. return false;
  354. }
  355. if (!$this->model->where(['id' => $userId])->update(['password' => get_password($password), 'update_time' => time()])) {
  356. $this->error = 2030;
  357. return false;
  358. }
  359. // 操作日志
  360. ActionLogModel::setRecord($userId, ['type' => 2, 'title' => '重置密码', 'content' => '重置登录密码', 'module' => 'member']);
  361. ActionLogModel::record();
  362. $this->error = 2031;
  363. return true;
  364. }
  365. /**
  366. * 获取资料详情
  367. * @param $where
  368. * @param array $field
  369. */
  370. public function getInfo($where, array $field = [], $refresh = true)
  371. {
  372. if (empty($where)) {
  373. return false;
  374. }
  375. $fieldKey = $field ? '_' . md5(json_encode($field)) : '';
  376. $cacheKey = "caches:members:info_" . (!is_array($where) ? $where . $fieldKey : md5(json_encode($where) . $fieldKey));
  377. $info = RedisService::get($cacheKey);
  378. if ($info && !$refresh) {
  379. return $info;
  380. }
  381. $defaultField = ['id', 'user_type', 'realname', 'mobile','is_auth','member_level','idcard','buy_type','area_id', 'nickname','parent_id','point_id', 'balance','ls_score','bd_score','property','property_total','withdraw_property','bonus_total','withdraw_total', 'code', 'openid','create_time', 'status', 'avatar'];
  382. $field = $field ? $field : $defaultField;
  383. if (is_array($where)) {
  384. $info = $this->model->with(['parent','point','levelData'])->where(['mark' => 1])->where($where)->select($field)->first();
  385. } else {
  386. $info = $this->model->with(['parent','point','levelData'])->where(['mark' => 1])->where(['id' => (int)$where])->select($field)->first();
  387. }
  388. $info = $info ? $info->toArray() : [];
  389. if ($info) {
  390. $info['create_time'] = $info['create_time']?datetime(strtotime($info['create_time']),'Y-m-d H:i') : '';
  391. if (isset($info['mobile'])) {
  392. $info['mobile_text'] = $info['mobile'] ? format_mobile($info['mobile']) : '';
  393. }
  394. $params = request()->all();
  395. $type = isset($params['type'])?$params['type']:'';
  396. if($type == 'qrcode'){
  397. $info['qrcode'] = MpService::make()->getMiniQrcode('pages/index/index',"{$info['id']}");
  398. $info['qrcode'] = $info['qrcode']? get_image_url($info['qrcode']):'';
  399. }
  400. if($type == 'center'){
  401. $info['invite_count'] = $this->model->where(['parent_id'=>$info['id'],'mark'=>1])->count('id');
  402. }
  403. if($type == 'account' || $type == 'center'){
  404. $info['property_price'] = PriceService::make()->getTodayPrice(1);
  405. $info['property_total'] = floatval($info['property'] * $info['property_price']);
  406. }
  407. RedisService::set($cacheKey, $info, rand(10, 20));
  408. }
  409. return $info;
  410. }
  411. /**
  412. * 缓存资料
  413. * @param $userId
  414. * @return array|mixed
  415. */
  416. public function getCacheInfo($userId,$refresh = true)
  417. {
  418. $cacheKey = "caches:members:cacheInfo_{$userId}";
  419. $info = RedisService::get($cacheKey);
  420. if ($info && !$refresh) {
  421. return $info;
  422. }
  423. $info = $this->model->where(['id' => $userId, 'mark' => 1])
  424. ->select(['id', 'openid', 'mobile','balance','property','ls_score','area_id','buy_type', 'user_type', 'nickname', 'avatar', 'code', 'status', 'mark'])
  425. ->first();
  426. $info = $info?$info->toArray() : [];
  427. if($info){
  428. RedisService::set($cacheKey, $info, rand(3600,7200));
  429. }
  430. return $info;
  431. }
  432. /**
  433. * 绑定收款账户
  434. * @param $userId
  435. * @return array|mixed
  436. */
  437. public function bindAccount($userId, $params)
  438. {
  439. if($params['type']==1){
  440. $alipay = MemberBankModel::where(['type'=>1,'user_id'=>$userId,'mark'=>1])
  441. ->select(['id','user_id','type','realname','account','account_remark','status'])
  442. ->first();
  443. $alipayId = isset($alipay['id'])?$alipay['id'] : 0;
  444. $data = [
  445. 'type'=> 1,
  446. 'user_id'=> $userId,
  447. 'realname'=>$params['realname'],
  448. 'account'=>$params['account'],
  449. 'account_remark'=>isset($params['account_remark']) && $params['account_remark']?$params['account_remark']:'支付宝',
  450. 'status'=>1
  451. ];
  452. if($alipayId){
  453. $data['update_time']=time();
  454. MemberBankModel::where(['id'=>$alipayId])->update($data);
  455. }else {
  456. $data['create_time']=time();
  457. MemberBankModel::insertGetId($data);
  458. }
  459. } else if($params['type']==2){
  460. $banks = MemberBankModel::where(['type'=>2,'user_id'=>$userId,'mark'=>1])
  461. ->select(['id','user_id','type','realname','account','account_remark','status'])
  462. ->first();
  463. $bankId = isset($banks['id'])?$banks['id'] : 0;
  464. $data = [
  465. 'type'=>2,
  466. 'user_id'=> $userId,
  467. 'realname'=>$params['realname'],
  468. 'account'=>$params['account'],
  469. 'account_remark'=>$params['account_remark'],
  470. 'status'=>1
  471. ];
  472. if($bankId){
  473. $data['update_time']=time();
  474. MemberBankModel::where(['id'=>$bankId])->update($data);
  475. }else {
  476. $data['create_time']=time();
  477. MemberBankModel::insertGetId($data);
  478. }
  479. }else{
  480. $this->error = '账号类型错误';
  481. return false;
  482. }
  483. RedisService::keyDel("caches:members:account:{$userId}*");
  484. $this->error = '绑定收款账号成功';
  485. return true;
  486. }
  487. /**
  488. * 团队人数
  489. * @param $uid
  490. * @return array|int|mixed
  491. */
  492. public function getTeamCount($uid)
  493. {
  494. $cacheKey = "caches:members:teamCount:{$uid}";
  495. $data = RedisService::get($cacheKey);
  496. if ($data) {
  497. return $data;
  498. }
  499. $data = $this->model->from('member as a')
  500. ->where('a.parents', 'like', "%,{$uid},%")
  501. ->where(['a.status' => 1, 'a.mark' => 1])
  502. ->count('id');
  503. if($data){
  504. RedisService::set($cacheKey, $data, rand(5,10));
  505. }
  506. return $data;
  507. }
  508. /**
  509. * 生成普通参数二维码
  510. * @param $str 参数
  511. * @param bool $refresh 是否重新生成
  512. * @return bool
  513. */
  514. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  515. {
  516. $basePath = base_path() . '/public';
  517. $qrFile = '/images/qrcode/';
  518. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  519. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  520. }
  521. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  522. $qrFile = $qrFile . "C_{$key}.png";
  523. $cacheKey = "caches:qrcodes:member_" . $key;
  524. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  525. return $qrFile;
  526. }
  527. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  528. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  529. return false;
  530. }
  531. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  532. return $qrFile;
  533. }
  534. /**
  535. * 修改信息
  536. * @param $userId
  537. * @param $params
  538. * @return bool
  539. */
  540. public function modify($userId, $params)
  541. {
  542. $cacheLockKey = "caches:members:modify_{$userId}";
  543. if (RedisService::get($cacheLockKey)) {
  544. $this->error = 1034;
  545. return false;
  546. }
  547. // 用户验证
  548. RedisService::set($cacheLockKey, ['user_id' => $userId, 'params' => $params], rand(2, 3));
  549. $info = $this->model->where(['id' => $userId, 'mark' => 1])
  550. ->select(['id', 'nickname','avatar','company','position','department', 'status'])
  551. ->first();
  552. if (!$info || $info['status'] != 1) {
  553. $this->error = 2016;
  554. RedisService::clear($cacheLockKey);
  555. return false;
  556. }
  557. // 修改数据
  558. $data = ['update_time' => time()];
  559. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  560. if (isset($params['nickname']) && $nickname) {
  561. $data['nickname'] = $nickname;
  562. }
  563. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  564. if (isset($params['mobile']) && $mobile) {
  565. $data['mobile'] = $mobile;
  566. }
  567. $company = isset($params['company']) ? $params['company'] : '';
  568. if (isset($params['company']) && $company) {
  569. $data['company'] = $company;
  570. }
  571. $department = isset($params['department']) ? $params['department'] : '';
  572. if (isset($params['department']) && $department) {
  573. $data['department'] = $department;
  574. }
  575. $position = isset($params['position']) ? $params['position'] : '';
  576. if (isset($params['position']) && $position) {
  577. $data['position'] = $position;
  578. }
  579. // 头像
  580. $avatar = isset($params['avatar']) ? $params['avatar'] : '';
  581. if (isset($params['avatar']) && $avatar) {
  582. $data['avatar'] = save_base64_image($avatar, 'avatar');
  583. }
  584. if (!$this->model->where(['id' => $userId])->update($data)) {
  585. $this->error = 1014;
  586. RedisService::clear($cacheLockKey);
  587. return false;
  588. }
  589. $oldAvatar = isset($info['avatar']) ? $info['avatar'] : '';
  590. if ($avatar && $oldAvatar && ($avatar != $oldAvatar) && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  591. @unlink(ATTACHMENT_PATH . $oldAvatar);
  592. }
  593. $this->error = 1013;
  594. RedisService::clear($cacheLockKey);
  595. RedisService::clear("caches:members:authInfo:{$userId}");
  596. RedisService::clear("caches:members:info_{$userId}");
  597. return true;
  598. }
  599. /**
  600. * 认证
  601. * @param $userId
  602. * @param $params
  603. * @return bool
  604. */
  605. public function auth($userId, $params)
  606. {
  607. $cacheLockKey = "caches:members:auth_{$userId}";
  608. if (RedisService::get($cacheLockKey)) {
  609. $this->error = 1034;
  610. return false;
  611. }
  612. // 用户验证
  613. RedisService::set($cacheLockKey, ['user_id' => $userId, 'params' => $params], rand(2, 3));
  614. $info = $this->model->where(['id' => $userId, 'mark' => 1])
  615. ->select(['id', 'realname','idcard','is_auth', 'status'])
  616. ->first();
  617. if (!$info || $info['status'] != 1) {
  618. $this->error = '账号或已被冻结,请联系客服';
  619. RedisService::clear($cacheLockKey);
  620. return false;
  621. }
  622. if($info['is_auth'] == 1 && $info['idcard'] && $info['realname']){
  623. $this->error = '抱歉,您已完成认证';
  624. RedisService::clear($cacheLockKey);
  625. return false;
  626. }
  627. // 认证数据
  628. $data = [
  629. 'realname'=> isset($params['realname'])?$params['realname'] : '',
  630. 'company'=> isset($params['company'])?$params['company'] : '',
  631. 'idcard'=> isset($params['idcard'])?$params['idcard'] : '',
  632. 'is_auth'=> 1,
  633. 'update_time' => time()
  634. ];
  635. if (!$this->model->where(['id' => $userId])->update($data)) {
  636. $this->error = '认证提交失败';
  637. RedisService::clear($cacheLockKey);
  638. return false;
  639. }
  640. $this->error = '恭喜您,已完成认证';
  641. RedisService::clear($cacheLockKey);
  642. RedisService::clear("caches:members:authInfo:{$userId}");
  643. RedisService::keyDel("caches:members:teamList*");
  644. return true;
  645. }
  646. /**
  647. * 获取团队列表
  648. * @param $userId
  649. * @param $params
  650. * @return array
  651. */
  652. public function getTeamList($userId,$params)
  653. {
  654. $page = isset($params['page'])?$params['page']: 1;
  655. $pageSize = isset($params['pageSize'])?$params['pageSize']: 12;
  656. $cacheKey = "caches:members:teamList_{$userId}:{$page}_".md5(json_encode($params));
  657. $list = RedisService::get($cacheKey);
  658. if ($list) {
  659. return [
  660. 'cache'=>true,
  661. 'pageSize'=> $pageSize,
  662. 'total'=>isset($list['total'])? $list['total'] : 0,
  663. 'list'=> isset($list['data'])? $list['data'] : []
  664. ];
  665. }
  666. $list = $this->model->from('member as a')
  667. ->where(['a.parent_id'=>$userId,'a.mark'=>1])
  668. ->where(function($query) use($params){
  669. $keyword = isset($params['keyword'])? $params['keyword'] : '';
  670. if($keyword){
  671. $query->where(function($query) use($keyword){
  672. $query->where('a.realname','like',"%{$keyword}%")
  673. ->orWhere('a.nickname','like',"%{$keyword}%")
  674. ->orWhere('a.mobile','like',"%{$keyword}%");
  675. });
  676. }
  677. })
  678. ->select(['a.id','a.realname','a.mobile','a.nickname','a.parent_id','a.avatar','a.is_auth','a.create_time','a.status'])
  679. ->groupBy('a.id')
  680. ->orderBy('a.create_time','desc')
  681. ->orderBy('a.id','desc')
  682. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  683. $list = $list? $list->toArray() :[];
  684. $total = isset($list['total'])? $list['total'] : 0;
  685. if($total){
  686. RedisService::set($cacheKey, $list, rand(5,10));
  687. }
  688. return [
  689. 'pageSize'=> $pageSize,
  690. 'total'=>$total,
  691. 'list'=> isset($list['data'])? $list['data'] : []
  692. ];
  693. }
  694. /**
  695. * 设置账户参数
  696. * @param $userId
  697. * @param $params
  698. * @return array|false|mixed|string
  699. */
  700. public function setting($userId, $params)
  701. {
  702. $apiUrl = ConfigService::make()->getConfigByCode('bonus_settle_url','');
  703. if(empty($apiUrl)){
  704. $this->error = '设置失败,参数错误';
  705. return false;
  706. }
  707. $token = request()->headers->get('Authorization');
  708. $token = str_replace("Bearer ", null, $token);
  709. $header = [
  710. 'authorization: '.$token
  711. ];
  712. $position = isset($params['position'])?trim($params['position']): '';
  713. $point = isset($params['commission_point'])?floatval($params['commission_point']): 0;
  714. $result = httpRequest($apiUrl.'/team/setting',['id'=>$userId,'position'=>$position,'point'=>$point],'post','',5,$header);
  715. $err = isset($result['err']) && $result['err']?$result['err'] : -1;
  716. $msg = isset($result['msg']) && $result['msg']?$result['msg'] : '1003';
  717. $data = isset($result['data']) && $result['data']?$result['data'] : [];
  718. if($err==0){
  719. $this->error = '操作成功';
  720. return $data;
  721. }else{
  722. $this->error = $msg;
  723. return false;
  724. }
  725. }
  726. /*
  727. * 各等级身份人数
  728. * @return array|mixed
  729. */
  730. public function getCountsByLevel()
  731. {
  732. $cacheKey = "caches:member:counts_by_level";
  733. $data = RedisService::get($cacheKey);
  734. if($data){
  735. return $data;
  736. }
  737. $data = $this->model->where('member_level','>', 0)
  738. ->where(['mark'=>1])
  739. ->select(['id','member_level',DB::raw("count(id) as count")])
  740. ->groupBy('member_level')
  741. ->get()
  742. ->keyBy('member_level');
  743. $data = $data?$data->toArray() : [];
  744. if($data){
  745. RedisService::set($cacheKey, $data, rand(5,10));
  746. }
  747. return $data;
  748. }
  749. /**
  750. * 账号注销
  751. * @param $userId
  752. * @return bool
  753. */
  754. public function logOff($userId)
  755. {
  756. $info = $this->model->where(['id' => $userId, 'mark' => 1])
  757. ->select(['id', 'password', 'status'])
  758. ->first();
  759. $status = isset($info['status']) ? $info['status'] : 0;
  760. if (empty($info)) {
  761. $this->error = 2044;
  762. return false;
  763. }
  764. if ($status != 1) {
  765. $this->error = 2044;
  766. return false;
  767. }
  768. if (!$this->model->where(['id' => $userId])->update(['status' => 3, 'update_time' => time()])) {
  769. $this->error = 2049;
  770. return false;
  771. }
  772. $this->error = 2048;
  773. RedisService::clear("auths:info:" . $userId);
  774. return true;
  775. }
  776. /**
  777. * 获取需要复购的用户列表
  778. * @param int $limit
  779. * @return array|mixed
  780. */
  781. public function getReplyBuyUsers($limit=500)
  782. {
  783. $cacheKey = "caches:members:replyList";
  784. $data = RedisService::get($cacheKey);
  785. if($data){
  786. return $data;
  787. }
  788. $maxLevel = GoodsModel::where(['type'=>2,'status'=>1,'mark'=>1])->max('id');
  789. $maxLevel = $maxLevel>0 && $maxLevel<=10?$maxLevel: 4;
  790. $data = $this->model->where('buy_type','<=', $maxLevel)
  791. ->where('balance','>',0)
  792. ->where(['bonus_status'=>2,'status'=>1,'mark'=>1])
  793. ->select(['id','mobile','nickname','buy_type','status'])
  794. ->limit($limit)
  795. ->get();
  796. $data = $data? $data->toArray() : [];
  797. if($data){
  798. RedisService::set($cacheKey, $data, rand(300,600));
  799. }
  800. return $data;
  801. }
  802. }