// +---------------------------------------------------------------------- namespace App\Services\Api; use App\Helpers\Jwt; use App\Models\AccountLogModel; use App\Models\BalanceLogModel; use App\Models\LiveModel; use App\Models\MemberBankModel; use App\Models\MemberModel; use App\Models\MerchantModel; use App\Models\VideoModel; use App\Services\BaseService; use App\Services\CityService; use App\Services\ConfigService; use App\Services\EmailService; use App\Services\RedisService; use App\Services\SmsService; use App\Services\ToolService; use App\Services\UdunpayService; use Illuminate\Support\Facades\DB; use phpQrcode\QRcode; /** * 会员管理-服务类 * @author laravel开发员 * @since 2020/11/11 * Class MemberService * @package App\Services\Api */ class MemberService extends BaseService { // 静态对象 protected static $instance = null; /** * 构造函数 * @author laravel开发员 * @since 2020/11/11 * MemberService constructor. */ public function __construct() { $this->model = new MemberModel(); } /** * 静态入口 * @return MemberService|static|null */ public static function make() { if (!self::$instance) { self::$instance = new static(); } return self::$instance; } /** * 获取资料详情 * @param $where * @param array $field */ public function getInfo($where, $type = 'detail', array $field = []) { $defaultField = ['id', 'username','email', 'realname', 'mobile','gender','member_level', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state','trc_url','recharge_trc_url', 'point_id', 'balance','trx','usdt','wait_score', 'score','pay_password','realname','idcard_check', 'member_level', 'status', 'avatar']; $withs = ['merchant','acceptor','parent','point','level']; if ($type == 'team') { $defaultField = ['id', 'username','email','member_level', 'nickname', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar']; }else if($type == 'share'){ $withs = ['parent','level']; $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar']; }else if($type == 'check'){ $withs = ['parent','level']; $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar']; }else if ($type == 'info'){ $withs = ['parent','level']; } $field = $field ? $field : $defaultField; if (is_array($where)) { $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first(); } else { $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first(); } $info = $info ? $info->toArray() : []; if ($info && !in_array($type, ['auth', 'check','login'])) { $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png'); // 二维码 if (in_array($type, ['detail'])) { if (isset($info['wxpay_qrcode'])) { $info['wxpay_qrcode'] = $info['wxpay_qrcode'] ? get_image_url($info['wxpay_qrcode']) : ''; } if (isset($info['alipay_qrcode'])) { $info['alipay_qrcode'] = $info['alipay_qrcode'] ? get_image_url($info['alipay_qrcode']) : ''; } $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无']; $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注) $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量 $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量 } else if ($type == 'info') { $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0); $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0; $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0; } else if ($type == 'team' || $type == 'share') { $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']); $qrcode = $this->makeQrcode($inviteUrl); $info['qrcode'] = $qrcode ? get_image_url($qrcode) : ''; $info['invite_url'] = $inviteUrl; $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):''; $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数 $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数 $info['team_count'] = $this->getUserCountByType($info['id'], 1, 1); // 节点推荐人数 }else { // 默认地址 $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']); } } return $info; } /** * 获取主页信息 * @param $where * @param array $field */ public function getHomeInfo($id, $userId=0) { $field = ['id', 'username','email', 'realname', 'mobile','gender', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state', 'point_id', 'balance','trx','usdt','wait_score', 'score','realname', 'member_level', 'status', 'avatar']; $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first(); $info = $info ? $info->toArray() : []; if ($info) { $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png'); $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注) $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量 $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量 $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了 $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝 $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播 } return $info; } /** * 获取用户缓存信息 * @param $where * @param array $field * @param int $expired * @return array|mixed */ public function getCacheInfo($where, $field = [], $expired = 0) { $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired); $info = RedisService::get($cacheKey); if ($info) { return $info; } $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar']; $field = $field ? $field : $defaultField; $info = $this->model->where($where)->where('mark', 1)->select($field)->first(); $info = $info ? $info->toArray() : []; if ($info) { if (isset($info['avatar'])) { $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png'; $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : ''; } RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5)); } return $info; } /** * 生成普通参数二维码 * @param $str 参数 * @param bool $refresh 是否重新生成 * @return bool */ public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2) { $basePath = base_path() . '/public'; $qrFile = '/images/qrcode/'; if (!is_dir($basePath . '/uploads' . $qrFile)) { @mkdir($basePath . '/uploads' . $qrFile, 0755, true); } $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level)); $qrFile = $qrFile . "C_{$key}.png"; $cacheKey = "caches:qrcodes:member_" . $key; if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) { return $qrFile; } QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin); if (!file_exists($basePath . '/uploads' . $qrFile)) { return false; } RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600); return $qrFile; } /** * 获取团队用户数量 * @param $userId 当前用户ID * @param int $type 层级:1-直推,2-团队 * @param int $isPoint 节点:1-滑落推荐,0-直接推荐 * @return array|mixed */ public function getUserCountByType($userId, $type = 1, $isPoint=0) { $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}"; $data = RedisService::get($cacheKey); if ($data) { return $data; } $where = ['status' => 1, 'mark' => 1]; $data = $this->model->where($where) ->where(function ($query) use ($type, $isPoint, $userId) { if($isPoint){ if ($type == 1) { // 滑落推荐 $query->where('point_id', $userId); } else if($type == 2){ // 滑落团队人数 $query->whereRaw('FIND_IN_SET(?,points)', $userId); } }else{ if ($type == 1) { // 直推人数 $query->where('parent_id', $userId); } else if($type == 2){ // 团队人数 $query->whereRaw('FIND_IN_SET(?,parents)', $userId); } else if($type == 3){ // 滑落人数 $query->where('parent_id', $userId)->where('point_id','!=', $userId); } } })->count('id'); if ($data) { RedisService::set($cacheKey, $data, rand(3, 5)); } return $data; } /** * 分销用户列表 * @param $userId * @param $params * @param int $pageSize * @return array */ public function getTeamList($userId, $params, $pageSize=15) { $page = request()->post('page',1); $cacheKey = "caches:teams:list_{$userId}_{$page}"; $datas = RedisService::get($cacheKey); if ($datas) { return [ 'pageSize' => $pageSize, 'total' => isset($datas['total']) ? $datas['total'] : 0, 'list' => isset($datas['data']) ? $datas['data'] : [] ]; } $where = ['status' => 1, 'mark' => 1]; $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status']; $datas = $this->model->with(['level'])->where($where) ->where(function ($query) use ($userId) { $query->where('parent_id', $userId); }) ->where(function($query) use($params){ $kw = isset($params['kw'])? trim($params['kw']) : ''; if($kw){ $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%"); } }) ->select($field) ->orderBy('create_time', 'desc') ->orderBy('id', 'desc') ->paginate($pageSize > 0 ? $pageSize : 9999999); $datas = $datas ? $datas->toArray() : []; if ($datas) { foreach ($datas['data'] as &$item) { $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png'; $item['avatar'] = get_image_url($item['avatar']); $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : ''; $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0; } unset($item); RedisService::set($cacheKey, $datas, rand(5, 10)); } return [ 'pageSize' => $pageSize, 'total' => isset($datas['total']) ? $datas['total'] : 0, 'list' => isset($datas['data']) ? $datas['data'] : [] ]; } /** * 手机号是否已注册 * @param $mobile * @return mixed */ public function checkPhoneExists($mobile) { return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub } /** * 账号注册 * @param $params * @return array|false */ public function register($params) { // 授权 $email = isset($params['email']) ? trim($params['email']) : ''; $mobile = isset($params['mobile']) ? trim($params['mobile']) : ''; $nickname = isset($params['nickname']) ? trim($params['nickname']) : ''; $code = isset($params['code']) ? trim($params['code']) : ''; $scene = isset($params['scene']) ? $params['scene'] : ''; $appSources = isset($params['app_sources']) ? $params['app_sources'] : ''; $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : ''; if (empty($params) || empty($email) || $code <= 0) { $this->error = 2014; return false; } // 验证码 if (!EmailService::make()->check($email, $code, $scene)) { $this->error = EmailService::make()->getError(); return false; } // 验证是否注册 if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){ $this->error = 2009; return false; } // 推荐人 $parentId = 0; $pointId = 0; $parents = ''; $points = ''; if ($inviteCode) { $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1]) ->select(['id', 'parents', 'parent_id']) ->first(); $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0; $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : ''); // 挂靠节点 if($parentId>0){ $pointId = $this->getPointParentId($parentId); if($pointId){ $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first(); $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : ''); } } } // 注册 $id = $this->model->max('id') + 1; $system = isset($params['system'])? $params['system'] : []; $ip = get_client_ip(); $ipData = ToolService::make()->getIpAddress($ip,''); $province = isset($ipData['regionName'])? $ipData['regionName'] : ''; $city = isset($ipData['city'])? $ipData['city'] : ''; $emailName = explode('@', $email)[0]; // 钱包 $data = [ 'parent_id' => $parentId, 'point_id' => $pointId, 'points' => $points, 'openid' => '', 'avatar' => '', 'nickname' => $nickname ? $nickname : '用户'.substr($emailName,-8,8), 'username' => $email, 'password' => get_password('xl123456'), 'code' => strtoupper(get_random_code(9, 'X', "{$id}")), 'email' => $email, 'mobile' => $mobile, 'recharge_trc_url' => UdunpayService::make()->createAddress(195), 'parents' => $parents, 'province_id' => CityService::make()->getFieldByName($province), 'city_id' => CityService::make()->getFieldByName($city), 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '', 'device' => $appSources == 'android' ? 2 : 1, 'status' => 1, 'balance' => 0, 'score' => 0, 'mark' => 1, 'login_ip' => $ip, 'create_time' => time(), ]; $userId = $this->model->insertGetId($data); $this->error = 2008; return [ 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"), 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']], ]; } /** * 邮箱登录 * @param $params * @return array|false */ public function loginByEmail($params) { // 授权 $email = isset($params['email']) ? $params['email'] : ''; $code = isset($params['code']) ? $params['code'] : ''; $scene = isset($params['scene']) ? $params['scene'] : ''; $appSources = isset($params['app_sources']) ? $params['app_sources'] : ''; if (empty($params) || empty($email) || empty($scene) || $code <= 0) { $this->error = 2014; return false; } // 验证码 if (!EmailService::make()->check($email, $code, $scene)) { $this->error = EmailService::make()->getError(); return false; } // 验证是否注册,没有则注册 $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status'])->first(); $data = $data ? $data->toArray() : []; $userId = isset($data['id']) ? $data['id'] : 0; $status = isset($data['status']) ? $data['status'] : 0; if(empty($data) || $userId<=0){ $this->error = 2001; return false; } if ($status != 1) { $this->error = 2015; return false; } // 获取登录授权token $jwt = new Jwt('jwt_dys_app'); $token = $jwt->getToken($userId); // 结果返回 $result = [ 'access_token' => $token, 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']], ]; // 用户信息 $ip = get_client_ip(); $updateData = [ 'login_time' => time(), 'login_ip' => $ip, ]; if(!RedisService::get("caches:member:updateArea:{$userId}")){ $ipData = ToolService::make()->getIpAddress($ip,''); $province = isset($ipData['regionName'])? $ipData['regionName'] : ''; $city = isset($ipData['city'])? $ipData['city'] : ''; $updateData['province_id'] = CityService::make()->getFieldByName($province); $updateData['city_id'] = CityService::make()->getFieldByName($city); } $this->model->where(['id'=> $userId])->update($updateData); $this->error = 2004; $data['token'] = $token; RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600); RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600); return $result; } /** * 手机号登录 * @param $params * @return array|false */ public function loginByMobile($params) { // 授权 $mobile = isset($params['mobile']) ? $params['mobile'] : ''; $code = isset($params['sms_code']) ? $params['sms_code'] : ''; $smsType = isset($params['sms_type']) ? $params['sms_type'] : ''; $nickname = isset($params['nickname']) ? $params['nickname'] : ''; $openid = isset($params['openid']) ? $params['openid'] : ''; $avatar = isset($params['avatar']) ? $params['avatar'] : ''; $regType = isset($params['type']) ? $params['type'] : 'app'; $appSources = isset($params['app_sources']) ? $params['app_sources'] : ''; $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : ''; if (empty($params) || empty($mobile) || $code <= 0) { $this->error = 2014; return false; } // 验证码 if (!SmsService::make()->check($mobile, $code, $smsType?$smsType:'login')) { $this->error = SmsService::make()->getError(); return false; } // 推荐人 $parentId = 0; $parents = ''; if ($inviteCode) { $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1]) ->select(['id', 'parents', 'parent_id']) ->first(); $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0; $parents = isset($inviteInfo['parents']) ? $inviteInfo['parents'] . $parentId . ',' : ($parentId ? $parentId . ',' : ''); } // 验证是否注册,没有则注册 $data = $this->model->with(['merchant','mechanic'])->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'openid', 'username', 'parent_id', 'code', 'push_cid', 'status'])->first(); $data = $data ? $data->toArray() : []; $userId = isset($data['id']) ? $data['id'] : 0; $status = isset($data['status']) ? $data['status'] : 0; if ($userId && $status != 1) { $this->error = 2015; return false; } // 是否是商家或技师,有订单提醒 $noticeUser = ['id'=> 0,'uid'=>$userId,'type'=>1]; $merchant = isset($data['merchant'])? $data['merchant'] : []; $merchantStatus = isset($merchant['status'])? $merchant['status'] : 0; $mechanic = isset($data['mechanic'])? $data['mechanic'] : []; $mechanicStatus = isset($mechanic['status'])? $mechanic['status'] : 0; if($merchantStatus==2){ $uid = isset($merchant['id'])? $merchant['id'] : 0; if($uid>0){ $noticeUser = ['id'=>$uid,'type'=>2,'uid'=> $userId]; } }else if($mechanicStatus == 2){ $uid = isset($mechanic['id'])? $mechanic['id'] : 0; if($uid>0){ $noticeUser = ['id'=>$uid,'type'=>3,'uid'=>$userId]; } } $pushCid = isset($params['push_cid']) ? $params['push_cid'] : ''; if (!$userId) { $id = $this->model->max('id') + 1; $data = [ 'parent_id' => $parentId, 'openid' => $openid, 'avatar' => $avatar, 'nickname' => $nickname ? $nickname : get_random_code(4, '用户u').substr($mobile,-4,4), 'username' => get_username($id), 'password' => get_password('123456'), 'code' => strtoupper(get_random_code(8, 'D', "{$id}")), 'mobile' => $mobile, 'parents' => $parents, 'push_cid' => isset($params['push_cid']) ? $params['push_cid'] : '', 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '', 'device' => $appSources == 'android' ? 2 : 1, 'status' => 1, 'balance' => 0, 'score' => 0, 'mark' => 1, 'login_time' => time(), 'login_ip' => get_client_ip(), 'create_time' => time(), ]; $userId = $this->model->insertGetId($data); } elseif ($regType != 'h5') { // 登录更新 $updateData = [ 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '', 'login_count' => DB::raw("login_count+1"), 'login_time' => time(), 'login_ip' => get_client_ip(), 'update_time' => time(), ]; if ($pushCid) { $updateData['push_cid'] = $pushCid; } $this->model->where(['id' => $userId])->update($updateData); } // H5 邀请注册,无需登录 if ($regType == 'h5') { $this->error = $status ? 2023 : 2022; return [ 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"), 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'username' => $data['username']], ]; } // 获取登录授权token $jwt = new Jwt('jwt_dys_app'); $token = $jwt->getToken($userId); // 结果返回 $result = [ 'access_token' => $token, 'info' => ['uid' => $userId,'notice_user'=>$noticeUser, 'openid' => $data['openid'], 'username' => $data['username']], ]; // 用户信息 $this->error = 2004; $data['token'] = $token; unset($data['password']); // 实现初始化账单明细表 AccountLogModel::where('id','<=',1)->value('id'); RedisService::clear( "caches:map:{$userId}"); RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600); return $result; } /** * 修改头像/商家logo/技师头像 * @param $userId * @param $avatar * @return mixed */ public function saveAvatar($userId, $avatar) { $type = request()->post('type', 1); if($type == 1){ $oldAvatar = $this->model->where(['id' => $userId])->value('avatar'); if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) { if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) { @unlink(ATTACHMENT_PATH . $oldAvatar); } return true; } }else if($type == 2){ $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo'); if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) { if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) { @unlink(ATTACHMENT_PATH . $oldAvatar); } return true; } }else if($type == 3){ $oldAvatar = MechanicModel::where(['user_id' => $userId])->value('avatar'); if (MechanicModel::where(['user_id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) { if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) { @unlink(ATTACHMENT_PATH . $oldAvatar); } return true; } } return false; } /** * 修改账号 * @param $userId * @param $params * @return bool */ public function modify($userId, $params) { $username = isset($params['username']) ? $params['username'] : ''; $password = isset($params['password']) ? $params['password'] : ''; $payPassword = isset($params['pay_password']) ? $params['pay_password'] : ''; // 用户验证 $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id', 'status'])->first(); if (!$info) { $this->error = 2001; return false; } // 使用状态校验 if ($info['status'] != 1) { $this->error = 2009; return false; } // 密码校验 $data = ['update_time' => time()]; if (isset($params['password']) && $password) { $password = get_password($password); $data['password'] = $password; if ($password != $info['password']) { $this->error = 2002; return false; } } // 用户账号验证 if (isset($params['username']) && $username) { $data['username'] = $username; $checkInfo = $this->model->where(['username' => $username, 'mark' => 1])->select(['id', 'status'])->first(); if ($checkInfo && $checkInfo['id'] != $userId) { $this->error = 2005; return false; } } // 手机号验证 $mobile = isset($params['mobile']) ? $params['mobile'] : ''; if (isset($params['mobile']) && $mobile) { $data['mobile'] = $mobile; $checkInfo = $this->model->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'status'])->first(); if ($checkInfo && $checkInfo['id'] != $userId) { $this->error = 2009; return false; } // 短信验证码 $code = isset($params['code']) ? $params['code'] : ''; if (empty($code)) { $this->error = 2013; return false; } if (!SmsService::make()->check($mobile, $code, 'modify')) { $this->error = SmsService::make()->getError(); return false; } } // 修改数据 $nickname = isset($params['nickname']) ? $params['nickname'] : ''; if (isset($params['nickname']) && $nickname) { $data['nickname'] = $nickname; } $sex = isset($params['sex']) ? $params['sex'] : 0; if (isset($params['sex']) && $sex) { $data['sex'] = $sex; } $intro = isset($params['intro']) ? $params['intro'] : ''; if (isset($params['intro']) && $intro) { $data['intro'] = $intro; } if (isset($params['pay_password']) && $payPassword) { $payPassword = get_password($payPassword); $data['pay_password'] = $payPassword; } $this->model->where(['id' => $userId])->update($data); $this->error = 1008; return true; } /** * 身份认证 * @param $userId * @param $params * @return bool */ public function auth($userId, $params) { // 用户验证 $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first(); if (!$info) { $this->error = 2001; return false; } // 使用状态校验 if ($info['status'] != 1) { $this->error = 2009; return false; } // 密码校验 $data = ['update_time' => time(),'idcard_check'=>1]; if (isset($params['realname']) && $params['realname']) { $data['realname'] = trim($params['realname']); } $idcard = isset($params['idcard']) && $params['idcard']; if ($idcard) { $data['idcard'] = trim($params['idcard']); } if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) { $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']); } if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) { $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']); } $this->model->where(['id' => $userId])->update($data); // 发送消息 $params = [ 'title'=> "身份认证提交成功", 'body' => "您的身份认证信息已提交成功,请耐心等候审核", 'type' => 1, // 1-公告通知,2-订单通知,3-交易通知,4-其他 'content' => [ 'account' => ['name' => '账号', 'text' => $info['username']], 'pay_time' => ['name' => '申请时间', 'text' => date('Y-m-d H:i:s')], 'status' => ['name' => '状态', 'text' => '待审核'], ], 'click_type' => 'payload', 'url' => '/pages/my/profile/auth', ]; PushService::make()->pushMessageByUser($userId, $params, 0); $this->error = 2036; return true; } /** * 转账 * @param $userId * @param $params * @return bool */ public function transfer($userId, $params) { $account = isset($params['account'])? trim($params['account']) : ''; $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : ''; $type = isset($params['type']) && $params['type']? intval($params['type']) : 1; $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1; $money = isset($params['money'])? floatval($params['money']) : 0; if(empty($account) || $money<=0){ $this->error = 2501; return false; } $cachekey = "caches:members:transfer:{$userId}"; if(RedisService::get($cachekey)){ $this->error = 1034; return false; } // 验证账户 $userInfo = $this->model->with(['merchant']) ->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','username','pay_password','balance','status']) ->first(); $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : []; $status = isset($userInfo['status'])? $userInfo['status'] : 0; $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0; $username = isset($userInfo['username'])? $userInfo['username'] : ''; $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : ''; $merchId = isset($merchant['id'])? $merchant['id'] : 0; $merchName = isset($merchant['name'])? $merchant['name'] : ''; $merchBalance = isset($merchant['balance'])? $merchant['balance'] : 0; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } // 余额支付支付密码验证 if(empty($userPayPassword)){ $this->error ='1039'; return false; } $payPassword = get_password($payPassword); if($payPassword != $userPayPassword){ $this->error ='1038'; return false; } // 验证账户 $accountInfo = $this->model->where(['username'=> $account,'mark'=>1]) ->select(['id','nickname','username','balance','status']) ->first(); $status = isset($accountInfo['status'])? $accountInfo['status'] : 0; $accountBalance = isset($accountInfo['balance'])? $accountInfo['balance'] : 0; if(empty($accountInfo) || $status != 1){ $this->error = 2025; return false; } if($accountInfo['id'] == $userId && $type == 1){ $this->error = 2645; return false; } // 用户余额转账到用户 DB::beginTransaction(); if($type == 1){ if($money>$balance){ $this->error = 2026; return false; } // 扣除账户余额 RedisService::set($cachekey, $params, rand(2,5)); $updateData = ['balance'=> DB::raw("balance - {$money}"),'update_time'=> time()]; if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2028; RedisService::clear($cachekey); return false; } } // 商户余额转账到用户 else if($type == 2){ if($money>$merchBalance){ $this->error = 2027; return false; } // if($merchId<=0){ $this->error = 2018; return false; } // 扣除商户余额 RedisService::set($cachekey, $params, rand(2,5)); $updateData = ['balance'=> DB::raw("balance - {$money}"),'update_time'=> time()]; if(!MerchantModel::where(['id'=> $merchId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2028; RedisService::clear($cachekey); return false; } } // 到账 $updateData = ['balance'=> DB::raw("balance + {$money}"),'update_time'=> time()]; if(!$this->model->where(['id'=> $accountInfo['id'],'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2028; RedisService::clear($cachekey); return false; } // 明细 $log = [ 'user_id' => $userId, 'merch_id' => $merchId, 'source_uid' => $accountInfo['id'], 'source_order_no' => '', 'type' => 6, 'coin_type' => 4, 'user_type'=> $type==2? 2 : ($userType!=2? $userType : 1), 'money' => -$money, 'balance' => $type==2? $merchBalance : $balance, 'create_time' => time(), 'update_time' => time(), 'remark' => $type==2? "商户余额转账给【{$account}】": "账户余额转账给【{$account}】", 'status' => 1, 'mark' => 1, ]; if(!AccountLogModel::insertGetId($log)){ DB::rollBack(); $this->error = 2029; RedisService::clear($cachekey); return false; } // 到账明细 $log = [ 'user_id' => $accountInfo['id'], 'merch_id' => $merchId, 'source_uid' => $userId, 'source_order_no' => '', 'type' => 6, 'coin_type' => 4, 'user_type'=> 1, 'money' => $money, 'balance' => $accountBalance, 'create_time' => time(), 'update_time' => time(), 'remark' => $type==2? "来自商家【{$merchName}】的转账": "来自".($userType==3?'技师':($userType==4?'代理':'用户'))."【{$username}】的转账", 'status' => 1, 'mark' => 1, ]; if(!AccountLogModel::insertGetId($log)){ DB::rollBack(); $this->error = 2029; RedisService::clear($cachekey); return false; } // 发送消息 $params = [ 'title'=> "转账成功通知", 'body' => $type == 2? "收到一笔来自商家的转账":"收到一笔来自用户的转账", 'type' => 2, // 1-公告通知,2-订单通知,3-交易通知,4-其他 'content' => [ 'account' => ['name' => $type==2?'来自商家':'来自用户', 'text' => $type==2? $merchName : $userInfo['username']], 'pay_time' => ['name' => '到账时间', 'text' => date('Y-m-d H:i:s')], 'money' => ['name' => '到账金额', 'text' => $money], 'status' => ['name' => '状态', 'text' => '已到账'], ], 'click_type' => 'payload', 'url' => '/pages/account/index', ]; if(!PushService::make()->pushMessageByUser($accountInfo['id'], $params, 0)){ DB::rollBack(); $this->error = PushService::make()->getError(); RedisService::clear($cachekey); return false; } DB::commit(); $this->error = 2030; return true; } /** * 余额充值 * @param $userId * @param $params * @return array|false */ public function recharge($userId, $params) { $money = isset($params['money'])? $params['money'] : 0; $payType = isset($params['pay_type']) && $params['pay_type']? intval($params['pay_type']) : 10; if($money<=0){ $this->error = 2031; return false; } if(!in_array($payType, [10,20])){ $this->error = 2032; return false; } $userInfo = $this->model->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','balance','status']) ->first(); $status = isset($userInfo['status'])? $userInfo['status'] : 0; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } // 充值订单 $orderNo = get_order_num('DR'); $data = [ 'order_no'=> $orderNo, 'user_id'=> $userId, 'type'=> 1, 'user_type'=> 1, 'money'=> $money, 'gift_money'=> 0, 'pay_type'=> $payType, 'create_time'=> time(), 'update_time'=> time(), 'status'=> 1, 'mark'=> 1, ]; if(!$orderId = BalanceLogModel::insertGetId($data)){ $this->error = 2033; return false; } // 支付方式 $order = [ 'order_no'=> $orderNo, 'type'=> 0, 'pay_type'=> $payType, 'pay_money'=> $money, 'body'=> '充值订单支付', ]; switch($payType){ case 20: // 支付宝 $payment = PaymentService::make()->aliPay($userInfo, $order,'recharge'); if(empty($payment)){ DB::rollBack(); $this->error = PaymentService::make()->getError(); return false; } break; case 10: // 微信支付 $payment = PaymentService::make()->wechatPay($userInfo, $order,'recharge'); if(empty($payment)){ DB::rollBack(); $this->error = PaymentService::make()->getError(); return false; } break; default: $this->error = 1030; return false; } $this->error = 2034; return [ 'id'=> $orderId, 'payment'=> $payment, 'total'=> $money, 'order_no'=> $orderNo, 'pay_type'=> $payType, ]; } /** * 余额提现 * @param $userId * @param $params * @return array|false */ public function withdraw($userId, $params) { $money = isset($params['money'])? floatval($params['money']) : 0; $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : ''; $payType = isset($params['pay_type']) && $params['pay_type']? intval($params['pay_type']) : 10; $bankId = isset($params['bank_id']) && $params['bank_id']? intval($params['bank_id']) : 0; $type = isset($params['type']) && $params['type']? intval($params['type']) : 1; if($money<=0){ $this->error = 2031; return false; } if(!in_array($payType, [10,20,50])){ $this->error = 2425; return false; } $userInfo = $this->model->with(['merchant']) ->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','balance','pay_password','wxpay_qrcode','alipay_qrcode','status']) ->first(); $status = isset($userInfo['status'])? $userInfo['status'] : 0; $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0; $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : ''; $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : []; $merchBalance = isset($merchant['balance'])? $merchant['balance'] : 0; $merchPayPassword = isset($merchant['pay_password'])? $merchant['pay_password'] : ''; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } // 验证提现类型金额 $qrcode = ''; $account = ''; if($type == 2){ // 支付密码验证 if(empty($merchPayPassword)){ $this->error ='1042'; return false; } $payPassword = get_password($payPassword); if($payPassword != $merchPayPassword){ $this->error ='1043'; return false; } if(empty($merchant)){ $this->error = 2646; return false; } if($money>$merchBalance){ $this->error = 2647; return false; } $wxpayQrcode = isset($merchant['wxpay_qrcode'])? $merchant['wxpay_qrcode'] : ''; $alipayQrcode = isset($merchant['alipay_qrcode'])? $merchant['alipay_qrcode'] : ''; if($payType == 10){ $qrcode = $wxpayQrcode; if(empty($wxpayQrcode)){ $this->error = 2649; return false; } } if($payType == 20){ $qrcode = $alipayQrcode; if(empty($alipayQrcode)) { $this->error = 2649; return false; } } }else{ // 支付密码验证 if(empty($userPayPassword)){ $this->error ='1039'; return false; } $payPassword = get_password($payPassword); if($payPassword != $userPayPassword){ $this->error ='1038'; return false; } if($money>$balance){ $this->error = 2648; return false; } $wxpayQrcode = isset($userInfo['wxpay_qrcode'])? $userInfo['wxpay_qrcode'] : ''; $alipayQrcode = isset($userInfo['alipay_qrcode'])? $userInfo['alipay_qrcode'] : ''; if($payType == 10){ $qrcode = $wxpayQrcode; if(empty($wxpayQrcode)) { $this->error = 2420; return false; } } if($payType == 20){ $qrcode = $alipayQrcode; if(empty($alipayQrcode)){ $this->error = 2421; return false; } } if($payType == 50){ $bankInfo = MemberBankModel::where(['id'=> $bankId,'mark'=>1]) ->select(['realname','bank_name','bank_card']) ->first(); $bankInfo = $bankInfo? $bankInfo->toArray() : []; $bankInfo = array_values($bankInfo); if(empty($bankInfo)){ $this->error = 2422; return false; }else { $account = $bankInfo? implode(' ', $bankInfo) : ''; } } } // 提现订单 $orderNo = get_order_num('DW'); $data = [ 'order_no'=> $orderNo, 'user_id'=> $userId, 'type'=> 2, 'user_type'=> $type, 'money'=> $money, 'actual_money'=> 0, 'qrcode'=> $qrcode, 'account'=> $account, 'pay_type'=> $payType, 'create_time'=> time(), 'update_time'=> time(), 'status'=> 1, 'mark'=> 1, ]; // 提现记录 DB::beginTransaction(); if(!$id = BalanceLogModel::insertGetId($data)){ DB::rollBack(); $this->error = 2033; return false; } // 商户扣款 if($type == 2){ $updateData = ['balance'=>DB::raw("balance - {$money}"),'update_time'=> time()]; if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2423; return false; } /*$log = [ 'user_id' => 0, 'merch_id' => $merchant['id'], 'source_uid' => $userId, 'source_order_no' => $orderNo, 'type' => 12, 'coin_type' => 4, 'user_type'=> 2, 'money' => -$money, 'balance' => $merchBalance, 'create_time' => time(), 'update_time' => time(), 'remark' => "商户余额提现", 'status' => 1, 'mark' => 1, ];*/ } // 用户扣款 else{ $updateData = ['balance'=>DB::raw("balance - {$money}"),'update_time'=> time()]; if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2423; return false; } /*$log = [ 'user_id' => $userId, 'merch_id' => 0, 'source_uid' => 0, 'source_order_no' => $orderNo, 'type' => 11, 'coin_type' => 4, 'user_type'=> 1, 'money' => -$money, 'balance' => $balance, 'create_time' => time(), 'update_time' => time(), 'remark' => "账户余额提现", 'status' => 1, 'mark' => 1, ];*/ } // 推送消息 $pushData = [ 'title' => '提现申请提交成功', 'body' => "您的提现申请已提交请耐心等候审核", 'type' => 3, // 1-公告通知,2-订单通知,3-交易通知,4-其他 'content' => [ 'order_no' => ['name' => '订单号', 'text' => $orderNo], 'pay_time' => ['name' => '申请时间', 'text' => date('Y-m-d H:i:s')], 'pay_type' => ['name' => '付款方式', 'text' => $payType==10?'微信支付':($payType==20?'支付宝':'银行卡')], 'money' => ['name' => '提现金额', 'text' => $money], 'status' => ['name' => '状态', 'text' => '待审核'], ], 'click_type' => 'payload', 'url' => '', ]; $merchId = isset($merchant['id'])? $merchant['id'] : 0; if($type == 2 && $merchId){ PushService::make()->pushMessageByUser($merchId, $pushData, 2); }else{ PushService::make()->pushMessageByUser($userId, $pushData); } DB::commit(); $this->error = 2424; return [ 'id'=> $id, 'money'=> $money, 'pay_type'=> $payType, ]; } /** * 分销佣金入账 * @param $info * @return false */ public function settleBonus($info, $level=1) { $money = isset($info['money'])? floatval($info['money']) : 0; $merchId = isset($info['merch_id'])? intval($info['merch_id']) : 0; $userId = isset($info['user_id'])? intval($info['user_id']) : 0; // 分销佣金 $settleUserId = isset($info["bonus_level{$level}_id"])? $info["bonus_level{$level}_id"] : 0; $settleMoney = isset($info["bonus_level{$level}_money"])? $info["bonus_level{$level}_money"] : 0; if($settleUserId>0 && $settleMoney>0){ $userInfo = $this->model->where(['id'=> $settleUserId,'mark'=>1]) ->select(['id','nickname','balance']) ->first(); $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0; if($settleUserId && $userInfo){ // 更新账户 $updateData = [ 'balance'=>DB::raw("balance + {$settleMoney}"), 'bonus_total'=>DB::raw("bonus_total + {$settleMoney}"), "bonus_level{$level}_total"=>DB::raw("bonus_level{$level}_total + {$settleMoney}"), 'update_time'=> time() ]; if(!MemberModel::where(['id'=> $settleUserId,'mark'=>1])->update($updateData)){ $this->error = lang(3413, ['level'=> $level]); return false; } $log = [ 'user_id'=> $settleUserId, 'merch_id'=> $merchId, 'source_uid'=> $userId, 'source_order_no'=> isset($info['order_no'])? $info['order_no'] :'', 'type'=> 3, 'coin_type'=> 2, 'user_type'=> 1, 'money'=> $settleMoney, 'balance'=>$balance? $balance : 0.00, 'create_time'=> time(), 'update_time'=> time(), 'remark'=> "服务订单[{$money}]元的{$level}级分销佣金", 'status'=>1, 'mark'=>1 ]; if(!AccountLogModel::insertGetId($log)){ $this->error = lang(3414, ['level'=> $level]); return false; } $this->error = lang(3415, ['level'=> $level]); return true; } } $this->error = lang(3412, ['level'=> $level]); return true; } /** * 获取点对点上级节点 * @param $userId 推荐人ID * @return int|mixed */ public function getPointParentId($userId) { if($userId<=0){ return 0; } $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get(); $userList = $userList? $userList->toArray() : []; if(count($userList) < 3){ return $userId; } $users = []; foreach($userList as $item){ $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : []; $points = array_filter($points); $users[$item['id']]['pointLen'] = count($points); $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0; $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1; } //var_dump($users); $pointId = 0; $tempPointLen = 0; $tempChildren = 0; foreach ($userList as $item) { $id = isset($item['id'])? $item['id'] : 0; $children = isset($users[$id]['children'])? $users[$id]['children'] : 0; $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0; //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren); if($pointLen<=$tempPointLen || $pointId == 0){ //var_dump($id.'++'.$pointLen.'--'.$children."\n\n"); if($children <$tempChildren || $pointId == 0){ $pointId = $id; $tempPointLen = $pointLen; $tempChildren = $children; } } } return $pointId; } }