// +---------------------------------------------------------------------- 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 App\Services\WalletService; 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 = [], $userId=0) { $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'); $info['balance'] = moneyFormat($info['balance'], 2); $info['usdt'] = moneyFormat($info['usdt'], 2); $info['score'] = moneyFormat($info['score'], 2); // 二维码 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'); // 点赞喜欢数量 if($userId != $info['id']){ $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了 }else{ $info['is_follow'] = 1; } } 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 == 'recharge') { $wallet = WalletService::make()->getWallet(1); $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : ''; $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100); if($info['recharge_trc_url']){ $qrcode = $this->makeQrcode($info['recharge_trc_url']); $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : ''; }else{ $info['trc_qrcode'] = ''; } } 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'], 2, 0); // 团队人数 }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({$userId},parents)"); } 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) { $email = isset($params['email']) ? $params['email'] : ''; $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['email']) && $email) { // 修改邮箱 $newEmail = isset($params['new_email'])? trim($params['new_email']) : ''; if(isset($params['new_email']) && $newEmail){ $data['email'] = $email; $data['username'] = $email; $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first(); if ($checkInfo && $checkInfo['id'] != $userId) { $this->error = 2005; return false; } } // 邮箱验证码 $code = isset($params['code'])? trim($params['code']) : ''; $scene = isset($params['scene'])? trim($params['scene']) : ''; if (!EmailService::make()->check($email, $code, $scene)) { $this->error = EmailService::make()->getError(); return false; } } // 修改数据 $nickname = isset($params['nickname']) ? $params['nickname'] : ''; if (isset($params['nickname']) && $nickname) { $data['nickname'] = $nickname; } $gender = isset($params['gender']) ? intval($params['gender']) : 3; if (isset($params['gender']) && $gender) { $data['gender'] = $gender; } $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) { $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0; $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : ''; $money = isset($params['money'])? floatval($params['money']) : 0; if(empty($toUserId) || $money<=0){ $this->error = 2420; return false; } $cacheKey = "caches:members:transfer:{$userId}"; if(RedisService::get($cacheKey)){ $this->error = 1034; return false; } // 验证账户 $userInfo = $this->model->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','username','usdt','pay_password','balance','status']) ->first(); $status = isset($userInfo['status'])? $userInfo['status'] : 0; $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0; $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : ''; $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : ''; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } // 余额支付支付密码验证 if(empty($userPayPassword)){ $this->error = 1040; return false; } $payPassword = get_password($payPassword); if($payPassword != $userPayPassword){ $this->error = 2038; return false; } // 验证账户 $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1]) ->select(['id','nickname','usdt','username','balance','status']) ->first(); $status = isset($accountInfo['status'])? $accountInfo['status'] : 0; $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0; $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : ''; if(empty($accountInfo) || $status != 1){ $this->error = 2421; return false; } if($money > $usdt){ $this->error = 2422; return false; } // 用户余额转账到用户 DB::beginTransaction(); RedisService::set($cacheKey, $params, rand(2,5)); $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()]; if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2028; RedisService::clear($cacheKey); return false; } // 明细 $orderNo = get_order_num('TR'); $log = [ 'user_id' => $userId, 'source_id' => $toUserId, 'source_order_no' => $orderNo, 'type' => 6, 'coin_type' => 1, 'user_type'=> 1, 'money' => -$money, 'actual_money' => -$money, 'balance' => $usdt, 'create_time' => time(), 'update_time' => time(), 'remark' => "USDT转账", 'status' => 1, 'mark' => 1, ]; if(!AccountLogModel::insertGetId($log)){ DB::rollBack(); $this->error = 2423; RedisService::clear($cacheKey); return false; } // 到账 $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5); $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0; $feeUsdt = round($money * $fee,2); $realUsdt = moneyFormat($money - $feeUsdt,2); $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()]; if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2424; RedisService::clear($cacheKey); return false; } // 明细 $log = [ 'user_id' => $toUserId, 'source_id' => $userId, 'source_order_no' => $orderNo, 'type' => 6, 'coin_type' => 1, 'user_type'=> 1, 'money' => $realUsdt, 'actual_money' => $realUsdt, 'balance' => $accountUsdt, 'create_time' => time(), 'update_time' => time(), 'remark' => "USDT转账", 'status' => 1, 'mark' => 1, ]; if(!AccountLogModel::insertGetId($log)){ DB::rollBack(); $this->error = 2029; RedisService::clear($cacheKey); return false; } // 平台明细 $log = [ 'user_id' => 0, 'source_id' => $userId, 'source_order_no' => $orderNo, 'type' => 6, 'coin_type' => 1, 'user_type'=> 4, 'money' => $feeUsdt, 'actual_money' => $feeUsdt, 'balance' => 0, 'create_time' => time(), 'update_time' => time(), 'remark' => "USDT转账", 'status' => 1, 'mark' => 1, ]; if(!AccountLogModel::insertGetId($log)){ DB::rollBack(); $this->error = 2029; RedisService::clear($cacheKey); return false; } // 平台 FinanceService::make()->saveLog(0, $feeUsdt,1); // 消息 $dateTime = date('Y-m-d H:i:s'); MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3); $dateTime = date('Y-m-d H:i:s'); MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3); DB::commit(); RedisService::clear($cacheKey); $this->error = 2425; return true; } /** * 余额充值 * @param $userId * @param $params * @return array|false */ public function recharge($userId, $params) { $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : ''; $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0; $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2; $payType = 10; if($usdt<=0){ $this->error = 2031; return false; } $userInfo = $this->model->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','usdt','pay_password','balance','status']) ->first(); $status = isset($userInfo['status'])? $userInfo['status'] : 0; $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0; $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0; $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : ''; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } if($userPayPassword != get_password($payPassword)){ $this->error = 2038; return false; } // 充值订单 $orderNo = get_order_num('DR'); $money = $usdt; // 星豆 DB::beginTransaction(); if($coinType == 2){ $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100); $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100; $money = round($xdPrice * $usdt,2); if($usdt > $userUsdt){ $this->error = 2035; return false; } // 扣除usdt余额 $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()]; if(!$this->model->where(['id'=> $userId])->update($updateData)){ $this->error = 2036; DB::rollBack(); return false; } } $data = [ 'order_no'=> $orderNo, 'user_id'=> $userId, 'type'=> 1, 'user_type'=> 1, 'coin_type'=> 2, 'money'=> $usdt, 'actual_money'=> $money, 'pay_type'=> $payType, 'pay_status'=> 20, 'pay_at'=> date('Y-m-d H:i:s'), 'create_time'=> time(), 'update_time'=> time(), 'status'=> 2, 'mark'=> 1, ]; if(!$orderId = BalanceLogModel::insertGetId($data)){ $this->error = 2033; DB::rollBack(); return false; } // 扣除USDT $log = [ 'user_id'=> $userId, 'source_order_no'=> $data['order_no'], 'user_type'=> 1, 'type'=> 5, 'coin_type'=> 1, 'money'=> -$usdt, 'actual_money'=> -$usdt, 'balance'=> $userUsdt, 'date'=> date('Y-m-d'), 'create_time'=> time(), 'remark'=> '星豆余额充值扣除', 'status'=>1, 'mark'=>1 ]; if(!AccountLogModel::insertGetId($log)){ $this->error = 2029; DB::rollBack(); return false; } // 增加星豆余额 $log = [ 'user_id'=> $userId, 'source_order_no'=> $data['order_no'], 'user_type'=> 1, 'type'=> 5, 'coin_type'=> 2, 'money'=> $usdt, 'actual_money'=> $money, 'balance'=> $balance, 'date'=> date('Y-m-d'), 'create_time'=> time(), 'remark'=> '星豆余额充值', 'status'=>1, 'mark'=>1 ]; if(!AccountLogModel::insertGetId($log)){ $this->error = 2029; DB::rollBack(); return false; } // 消息 $dateTime = date('Y-m-d H:i:s'); MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3); DB::commit(); // 充值星豆任务 TaskService::make()->updateTask($userId,9, 0); $this->error = 2037; return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)]; } /** * 余额提现 * @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']) : ''; $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1; if($money<=0){ $this->error = 2401; return false; } if(!in_array($userType,[1,2])){ $this->error = 2404; return false; } $userInfo = $this->model->with(['merchant']) ->where(['id'=> $userId,'mark'=>1]) ->select(['id','nickname','usdt','trc_url','pay_password','status']) ->first(); $status = isset($userInfo['status'])? $userInfo['status'] : 0; $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0; $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : ''; $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : []; $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0; $merchantId = isset($merchant['id'])? $merchant['id'] : 0; $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0; if(empty($userInfo) || $status != 1){ $this->error = 2024; return false; } if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){ $this->error = 2024; return false; } // 提现金额验证 $accountUsdt = $userType==1? $userUsdt : $merchantUsdt; if ($money > $accountUsdt) { $this->error = web_lang(2402, ['money' => $accountUsdt]); return false; } // 提现账户 $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : ''; if (empty($trcUrl)) { $this->error = 2403; return false; } if($userPayPassword != get_password($payPassword)){ $this->error = 2038; return false; } $cacheKey = "caches:member:withdraw:lock_{$userId}"; if(RedisService::get($cacheKey)){ $this->error = 1034; return false; } DB::beginTransaction(); RedisService::set($cacheKey, $userInfo, rand(2,3)); // 提现记录 $orderNo = get_order_num('DW'); $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5); $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0; $fee = round($money*$feeRate, 2); $realUsdt = moneyFormat($money - $fee, 2); $data = [ 'order_no'=> $orderNo, 'user_id'=> $userType==1? $userId : $merchantId, 'type'=> 2, 'user_type'=> $userType, 'coin_type'=> 1, 'money'=> $money, 'actual_money'=> $realUsdt, 'fee'=> $fee, 'trc_url'=> $trcUrl, 'pay_type'=> 20, 'date'=> date('Y-m-d'), 'create_time'=> time(), 'update_time'=> time(), 'status'=> 1, 'mark'=> 1, ]; if(!$id = BalanceLogModel::insertGetId($data)){ DB::rollBack(); $this->error = 2405; RedisService::clear($cacheKey); return false; } // 商户扣款 if($userType == 2){ $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()]; if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2406; RedisService::clear($cacheKey); return false; } // 明细 $log = [ 'user_id' => $merchantId, 'source_id' => $userId, 'source_order_no' => $orderNo, 'type' => 5, 'coin_type' => 1, 'user_type'=> 2, 'money' => -$money, 'actual_money' => -$money, 'balance' => $merchantUsdt, 'create_time' => time(), 'update_time' => time(), 'remark' => "商户账户余额提现", 'status' => 1, 'mark' => 1, ]; if (!AccountLogModel::insertGetId($log)) { $this->error = 2407; DB::rollBack(); RedisService::clear($cacheKey); return false; } } // 用户扣款 else{ $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()]; if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){ DB::rollBack(); $this->error = 2406; RedisService::clear($cacheKey); return false; } // 明细 $log = [ 'user_id' => $userId, 'source_id' => 0, 'source_order_no' => $orderNo, 'type' => 5, 'coin_type' => 1, 'user_type'=> 1, 'money' => -$money, 'actual_money' => -$money, 'balance' => $userUsdt, 'create_time' => time(), 'update_time' => time(), 'remark' => "USDT余额提现", 'status' => 1, 'mark' => 1, ]; if (!AccountLogModel::insertGetId($log)) { $this->error = 2407; DB::rollBack(); RedisService::clear($cacheKey); return false; } } DB::commit(); // 站内消息 $dateTime = date('Y-m-d H:i:s'); $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功'; $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!"; MessageService::make()->pushMessage($userId, $title, $message); // 提现自动审核,低于该金额自动审核 $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300); $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0; if ($money <= $autoCheckUsdt) { // 打款处理 $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realUsdt); $txID = isset($result['txId']) ? $result['txId'] : ''; $payAddress = isset($result['address']) ? $result['address'] : ''; if ($txID && $payAddress) { $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()]; if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){ $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功'; $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!"; MessageService::make()->pushMessage($userId, $title, $message); AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]); // 平台明细 $log = [ 'user_id' => 0, 'source_id' => $userId, 'source_order_no' => $orderNo, 'type' => 5, 'coin_type' => 1, 'user_type'=> 4, 'money' => $fee, 'actual_money' => $fee, 'balance' => 0, 'create_time' => time(), 'update_time' => time(), 'hash' => $txID, 'remark' => "USDT余额提现", 'status' => 1, 'mark' => 1, ]; AccountLogModel::insertGetId($log); // 平台流水 FinanceService::make()->saveLog(0, $fee, 1); } } } $this->error = $title; RedisService::clear($cacheKey); return [ 'id'=> $id, 'money'=> $money, 'user_type'=> $userType, ]; } /** * 获取点对点上级节点 * @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; } }