// +---------------------------------------------------------------------- namespace App\Services\Api; use App\Helpers\Jwt; use App\Models\AccountLogModel; use App\Models\BalanceLogModel; use App\Models\BonusLogModel; use App\Models\CityModel; use App\Models\MechanicModel; use App\Models\MemberBankModel; use App\Models\MemberCollectModel; use App\Models\MemberModel; use App\Models\MerchantClerkModel; use App\Models\MerchantModel; use App\Models\OrderModel; use App\Services\BaseService; use App\Services\CityService; use App\Services\ConfigService; use App\Services\EmailService; use App\Services\PushService; use App\Services\RedisService; use App\Services\SmsService; use App\Services\ToolService; use App\Services\UdunpayService; use App\Services\ZegoService; 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', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'openid', 'balance', 'score','pay_password', 'wxpay_qrcode', 'alipay_qrcode','realname','idcard_check','idcard','idcard_front_img','idcard_back_img','idcard_audit_remark', 'member_level', 'status', 'avatar']; if ($type == 'home') { $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'openid', 'balance', 'score', 'member_level', 'status', 'avatar']; } else if ($type == 'team') { $defaultField = ['id', 'username', 'nickname', 'code', 'balance', 'score', 'withdraw_total', 'bonus_total', 'bonus_level1_total', 'bonus_level2_total','bonus_level3_total', 'status', 'avatar']; }else if($type == 'share'){ $defaultField = ['id', 'username', 'nickname', 'code', 'balance', 'score', 'withdraw_total', 'bonus_total', 'bonus_level1_total', 'bonus_level2_total','bonus_level3_total', 'status', 'avatar']; }else if($type == 'login'){ $defaultField = ['id', 'username', 'nickname', 'code','push_cid', 'balance', 'score', 'status']; } $field = $field ? $field : $defaultField; if (is_array($where)) { $info = $this->model->where('mark',1)->where($where)->select($field)->first(); } else { $info = $this->model->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'] = round($info['balance'], 2); $info['mobile_text'] = isset($info['mobile']) ? $info['mobile'] : ''; $info['mobile'] = $info['mobile_text'] ? format_mobile($info['mobile_text']) : ''; $info['show_my_job'] = intval(ConfigService::make()->getConfigByCode('show_my_job')); 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']) : ''; } if (!in_array($type, ['team', 'bonus'])) { // 是否技师 $mechanic = MechanicService::make()->getCacheInfoByUser($info['id'], '', $type); $info['mechanic'] = $mechanic ? $mechanic : ['id' => 0, 'status' => 0,'bonus_wait'=>'0.00','views'=>0]; if($mechanic){ $info['mechanic']['bonus_wait'] = BonusLogModel::where(['mech_id'=> $mechanic['id'],'status'=>1]) ->where('settle_at','>',date('Y-m-d H:i:s')) ->sum('mech_money'); } // 是否商家 $merchant = MerchantService::make()->getCacheInfoByUser($info['id']); $info['merchant'] = $merchant ? $merchant : ['id' => 0, 'status' => 0]; // 是否代理 $agent = AgentService::make()->getCacheInfoByUser($info['id']); $info['agent'] = $agent ? $agent : ['id' => 0, 'status' => 0]; } // 二维码 if (in_array($type, ['detail','share'])) { $inviteUrl = get_web_url('/#/pages/register/index?scene=' . $info['code']); $qrcode = $this->makeQrcode($inviteUrl); $info['qrcode'] = $qrcode ? get_image_url($qrcode) : ''; $info['invite_url'] = $inviteUrl; $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):''; $info['parent_info'] = ['nickname' => '无', 'code' => '无']; if (isset($info['parent_id']) && $info['parent_id']) { $info['parent_info'] = $this->model->where(['id' => $info['parent_id'], 'mark' => 1]) ->select(['id', 'nickname', 'username', 'code']) ->first(); } $info['orders'] = ['status2'=>0,'status3'=>0,'status5'=>0]; if($type == 'share'){ $info['bonus_wait'] = BonusService::make()->getTotalByUser($info['id']); $info['bonus_level_total'] = moneyFormat($info['bonus_level1_total']+$info['bonus_level2_total']+$info['bonus_level3_total'],2); }else{ $num1 = OrderModel::where(['user_id'=> $info['id'],'type'=>2,'user_delete'=>1,'status'=>2,'mark'=>1])->count('id'); $num2 = OrderModel::where(['user_id'=> $info['id'],'type'=>2,'user_delete'=>1,'status'=>3,'mark'=>1])->count('id'); $num3 = OrderModel::where(['user_id'=> $info['id'],'type'=>2,'user_delete'=>1,'status'=>5,'mark'=>1])->count('id'); $info['orders'] = [ 'status2'=> $num1>99?'99+':intval($num1), 'status3'=> $num2>99?'99+':intval($num2), 'status5'=> $num3>99?'99+':intval($num3), ]; $info['idcard_front_img'] = $info['idcard_front_img'] ? get_image_url($info['idcard_front_img']) : ''; $info['idcard_back_img'] = $info['idcard_back_img'] ? get_image_url($info['idcard_back_img']) : ''; } } // 商家后台 else if ($type == 'mech') { } // 技师后台 else if ($type == 'merch') { } // 代理后台 else if ($type == 'agent') { } else if ($type == 'team') { $info['bonus_level1_count'] = (int)$this->getTeamsUserCountByLevel($info['id'], 1); $info['bonus_level2_count'] = (int)$this->getTeamsUserCountByLevel($info['id'], 2); }else if ($type == 'bonus') { $info['counts'] = BonusService::make()->bonusCountByTime($info['id'], 0); }else if($type == 'payment'){ $data = ['ac'=> $info['username'],'ut'=>1,'scene'=>'pay']; $qrcode = $this->makeQrcode(json_encode($data, 256)); $info['payment_qrcode'] = $qrcode ? get_image_url($qrcode) : ''; } else { // 默认地址 $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']); } } return $info; } /** * 获取收款二维码 * @param $account 账号ID * @param $params * @return string|\图片地址 */ public function getSceneQrcode($account, $params) { $type = isset($params['type']) && $params['type']? $params['type'] : 1; $scene = isset($params['scene']) && $params['scene']? $params['scene'] : ''; $room = isset($params['room']) && $params['room']? $params['room'] : ''; $merchId = isset($params['merch_id']) && $params['merch_id']? $params['merch_id'] : ''; $money = isset($params['money']) && $params['money']? floatval($params['money']) : ''; $data = ['ac'=> $account,'scene'=>$scene]; if($type){ $data['ut'] = $type; } if($money){ $data['my'] = $money; } if($merchId){ $data['mid'] = $merchId; } if($room){ $data['rm'] = $room; unset($data['ac']); unset($data['ut']); } $qrcode = $this->makeQrcode(json_encode($data, 256)); return $qrcode ? get_image_url($qrcode) : ''; } /** * 主页信息 * @param $id * @param int $userId * @return array */ public function getHomeInfo($id, $userId = 0) { $info = $this->getInfo($id, 'home'); if ($info) { $info['collect_num'] = (int)MemberCollectModel::where(['collect_uid' => $id, 'status' => 1, 'mark' => 1])->count('id'); $info['is_collect'] = (int)MemberCollectModel::where(['collect_uid' => $id, 'user_id' => $userId, 'status' => 1, 'mark' => 1])->value('id'); $services = isset($info['mechanic']['services']) ? explode(',', $info['mechanic']['services']) : []; $info['services'] = []; if ($services) { $info['services'] = GoodsService::make()->getListByIds($services); } } 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', 'openid', 'balance', '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_preview'] = get_image_url($info['avatar']); } RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5)); } return $info; } /** * 获取用户聊天显示缓存信息 * @param $where * @param array $field * @param int $expired * @return array|mixed */ public function getChatInfo($userId, $field = [], $domain = '') { try { $cacheKey = "caches:member:chatInfo:cache_{$userId}" . ($field ? '_' . md5(json_encode($field, 256)) : ''); $info = RedisService::get($cacheKey); if ($info) { return $info; } $defaultField = ['id', 'username', 'nickname', 'avatar']; $field = $field ? $field : $defaultField; $info = $this->model->where(['id' => $userId])->where('mark', 1)->select($field)->first(); $info = $info ? $info->toArray() : []; if ($info) { if (isset($info['avatar'])) { $info['avatar'] = get_image_url($info['avatar']); } $merchInfo = MerchantModel::where(['user_id' => $userId])->whereIn('status', [2, 3])->select(['name', 'logo'])->first(); $merchInfo = $merchInfo ? $merchInfo->toArray() : []; if ($merchInfo && isset($info['nickname'])) { $info['nickname'] = isset($merchInfo['name']) ? $merchInfo['name'] : $info['nickname']; } if ($merchInfo && isset($info['avatar'])) { $info['avatar'] = isset($merchInfo['logo']) && $merchInfo['logo'] ? get_image_url($merchInfo['logo'], $domain) : $info['avatar']; } RedisService::set($cacheKey, $info, rand(5, 10)); } return $info; } catch (\Exception $exception) { return false; } } /** * 生成普通参数二维码 * @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 $level 层级:1-一级分销用户,2-二级分销用户 * @return array|mixed */ public function getTeamsUserCountByLevel($userId, $level = 1) { $cacheKey = "caches:members:bonusUser:count_{$userId}_{$level}"; $data = RedisService::get($cacheKey); if ($data) { return $data; } $where = ['status' => 1, 'mark' => 1]; $data = $this->model->where($where) ->where(function ($query) use ($level, $userId) { if ($level == 1) { $query->where('parent_id', $userId); } else if($level == 2){ $query->whereIn('parent_id', MemberModel::where(['parent_id'=> $userId,'status'=>1,'mark'=>1])->pluck('id')); } })->count('id'); if ($data) { RedisService::set($cacheKey, $data, rand(3, 5)); } return $data; } /** * 分销用户列表 * @param $userId * @param $params * @param int $pageSize * @return array */ public function getTeamsUserByLevel($userId, $params, $pageSize=12) { $page = request()->post('page',1); $level = isset($params['type'])? $params['type'] : 1; $cacheKey = "caches:members:bonusUser:list_{$userId}_{$level}_{$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', 'nickname', 'username', 'mobile', 'balance', 'parent_id','create_time', 'status']; $datas = $this->model->with(['merchant'])->where($where) ->where(function ($query) use ($level, $userId) { if ($level == 1) { $query->where('parent_id', $userId); } else if($level == 2){ $ids = MemberModel::where(['parent_id'=> $userId,'status'=>1,'mark'=>1])->pluck('id'); $query->whereIn('parent_id', $ids? $ids : []); } }) ->where(function($query) use($params){ $kw = isset($params['kw'])? trim($params['kw']) : ''; if($kw){ $query->where('mobile','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['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : ''; $item['mobile_text'] = isset($item['mobile']) && $item['mobile'] ? format_mobile($item['mobile']) : ''; $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0; $count = isset($params['count'])? $params['count'] : 0; $item['children'] = []; $item['children_count'] = 0; if($count){ $item['children_count'] = $this->getTeamsUserCountByLevel($item['id'], 1); } } unset($item); RedisService::set($cacheKey, $datas, rand(3, 5)); } 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'] : ''; // 钱包 $data = [ 'parent_id' => $parentId, 'point_id' => $pointId, 'points' => $points, 'openid' => '', 'avatar' => '', 'nickname' => $nickname ? $nickname : get_username($id,'用户'), 'username' => $email, 'password' => get_password('xl123456'), 'code' => strtoupper(get_random_code(8, 'XL', "{$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); 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'] : ''; $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : ''; if (empty($params) || empty($email) || empty($scene) || $code <= 0) { $this->error = 2014; return false; } // 验证码 if (!EmailService::make()->check($email, $code, $scene)) { $this->error = SmsService::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 ($userId && $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 mixed */ public function saveQrcode($userId, $params) { if (isset($params['wxpay']) && $params['wxpay']) { $qrcode = $this->model->where(['id' => $userId])->value('wxpay_qrcode'); if ($this->model->where(['id' => $userId])->update(['wxpay_qrcode' => $params['wxpay'], 'update_time' => time()])) { if ($qrcode && file_exists(ATTACHMENT_PATH . $qrcode)) { @unlink(ATTACHMENT_PATH . $qrcode); } return true; } } if (isset($params['alipay']) && $params['alipay']) { $qrcode = $this->model->where(['id' => $userId])->value('alipay_qrcode'); if ($this->model->where(['id' => $userId])->update(['alipay_qrcode' => $params['alipay'], 'update_time' => time()])) { if ($qrcode && file_exists(ATTACHMENT_PATH . $qrcode)) { @unlink(ATTACHMENT_PATH . $qrcode); } 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 updateMap($userId, $params) { $cacheKey = "caches:map:{$userId}"; if (RedisService::get($cacheKey)) { $this->error = 1015; return false; } $lng = isset($params['lng']) ? $params['lng'] : ''; $lat = isset($params['lat']) ? $params['lat'] : ''; if (empty($lng) || empty($lat)) { $this->error = 2014; return false; } $address = []; $data = ['update_time' => time(), 'lng' => $lng, 'lat' => $lat]; $addressData = isset($params['address']) && $params['address'] ? json_decode($params['address'], true) : []; $city = isset($addressData['city']) ? $addressData['city'] : ''; $address[] = isset($addressData['province']) ? $addressData['province'] : ''; $address[] = $city; $address[] = isset($addressData['district']) ? $addressData['district'] : ''; $ids = CityModel::whereIn('name',$address)->where(['mark'=>1])->pluck('id'); $address = array_filter($address); if ($address) { $data['province_id'] = isset($ids[0])? $ids[0] : 0; $data['city_id'] = isset($ids[1])? $ids[1] : 0; $data['district_id'] = isset($ids[2])? $ids[2] : 0; $data['address'] = implode(' ', $address); $data['city'] = $city; } RedisService::set("caches:maps:{$userId}",['data'=> $data,'params'=>$params], 300); if ($this->model->where(['id' => $userId])->update($data)) { // 如果是个人商家 $updateData = [ 'province' => isset($addressData['province']) ? $addressData['province'] : '', 'city' => isset($addressData['city']) ? $addressData['city'] : '', 'district' => isset($addressData['district']) ? $addressData['district'] : '', 'lng' => $lng, 'lat' => $lat, ]; MerchantModel::where(['user_id' => $userId, 'type' => 2, 'mark' => 1])->whereIn('status', [1, 2])->update($updateData); RedisService::set($cacheKey, $data, rand(30, 60)); $this->error = 1016; return true; } else { RedisService::set($cacheKey.'_error', $data, rand(30, 60)); $this->error = 1016; return false; } } /** * 转账 * @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 $info * @return false */ public function settleMerchBonus($info, $level=1) { $money = isset($info['money'])? floatval($info['money']) : 0; $merchId = isset($info['merch_id'])? intval($info['merch_id']) : 0; // 分销佣金 $settleUserId = isset($info["merch_level{$level}_id"])? $info["merch_level{$level}_id"] : 0; $settleMoney = isset($info["merch_level{$level}_money"])? $info["merch_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'=> $merchId, '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; } $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; if($pointLen<=$tempPointLen || $pointId = 0){ if($children < $tempChildren || $pointId = 0){ $pointId = $id; $tempPointLen = $pointLen; } } } return $pointId; } }