| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services\Api;
- use App\Helpers\Jwt;
- use App\Models\AccountLogModel;
- use App\Models\BalanceLogModel;
- use App\Models\DeveloperModel;
- use App\Models\MemberLevelModel;
- use App\Models\MemberModel;
- use App\Services\BaseService;
- use App\Services\ConfigService;
- use App\Services\CregisPayService;
- use App\Services\RedisService;
- use App\Services\ToolService;
- use App\Services\WalletService;
- use Illuminate\Support\Facades\DB;
- use phpqrcode\QRcode;
- /**
- * 会员-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * @package App\Services\Api
- */
- class MemberService extends BaseService
- {
- protected static $instance;
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- */
- public function __construct()
- {
- $this->model = new MemberModel();
- }
- /**
- * 静态入口
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 登录注册
- * @param $walletUrl
- * @param string $scode
- * @return array|false
- */
- public function loginOrRegister($walletUrl, $scode = '')
- {
- if (empty($walletUrl)) {
- $this->error = 1038;
- return false;
- }
- $info = $this->model->with(['parent'])->where(['wallet_url' => $walletUrl, 'mark' => 1])
- ->select(['id', 'nickname', 'member_level', 'performance', 'code', 'usdt', 'sbt', 'profit', 'parent_id', 'wallet_url', 'wallet_token', 'recharge_url', 'bonus_rate', 'pledge_auto', 'trade_status', 'status'])
- ->first();
- $info = $info ? $info->toArray() : [];
- $parentInfo = isset($info['parent']) ? $info['parent'] : [];
- $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
- $ip = get_client_ip();
- /* TODO 注册 */
- if (empty($info)) {
- // 上级账号
- $parentId = 0;
- $parentIds = '';
- if ($scode) {
- $parentInfo = $this->model->where(['code' => $scode, 'mark' => 1])->select(['id', 'parent_ids', 'wallet_url'])->first();
- $parentId = isset($parentInfo['id']) ? $parentInfo['id'] : 0;
- $parents = isset($parentInfo['parent_ids']) ? $parentInfo['parent_ids'] : '';
- $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
- if ($parentId) {
- $parentIds = $parents ? trim($parents, ',') . ",{$parentId}," : "{$parentId},";
- }
- }
- // 注册奖励
- $awardSbtUsdt = ConfigService::make()->getConfigByCode('register_award_sbt', 0);
- if ($awardSbtUsdt > 0) {
- $sbtPrice = PriceLogService::make()->getSbtPrice();
- $awardSbtNum = $sbtPrice ? round($awardSbtUsdt * 1 / $sbtPrice, 2) : 0;
- }
- // U盾充值地址
- $rechargeUrl = CregisPayService::make()->createAddress(1000);
- DB::beginTransaction();
- $id = $this->model->max('id') + 1;
- $info = [
- 'nickname' => 'SBT_' . substr($walletUrl, -6, 6),
- 'wallet_url' => $walletUrl,
- 'wallet_token' => make_wallet_token($walletUrl, $id),
- 'avatar' => '',
- 'recharge_url' => $rechargeUrl,
- 'recharge_token' => $rechargeUrl?make_wallet_token($rechargeUrl, $id) : '',
- 'member_level' => 0,
- 'usdt' => 0.00,
- 'sbt' => $awardSbtNum,
- 'profit' => 0.00,
- 'bonus_rate' => 0.00,
- 'performance' => 0.00,
- 'parent_id' => $parentId,
- 'parent_ids' => $parentIds,
- 'pledge_auto' => 1,
- 'code' => strtoupper(get_random_code(9, 'S', "{$id}")),
- 'login_ip' => $ip,
- 'login_time' => time(),
- 'create_time' => time(),
- 'trade_status' => 1,
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!$userId = $this->model->insertGetId($info)) {
- DB::rollBack();
- $this->error = 2007;
- return false;
- }
- if ($awardSbtNum > 0) {
- $log = [
- 'user_id' => $userId,
- 'type' => 13,
- 'order_no' => get_order_num('RW'),
- 'coin_type' => 2,
- 'money' => $awardSbtNum,
- 'before_money' => 0,
- 'create_time' => time(),
- 'remark' => '注册奖励',
- 'action_ip' => get_client_ip(),
- 'status' => 1,
- 'mark' => 1
- ];
- if (!AccountLogModel::insertGetId($log)) {
- DB::rollBack();
- $this->error = 2007;
- return false;
- }
- }
- DB::commit();
- // 清除团队统计数据或列表缓存
- RedisService::keyDel("caches:team*");
- } else {
- $userId = $info['id'];
- $status = isset($info['status']) ? $info['status'] : 0;
- if ($status != 1) {
- $this->error = 2015;
- return false;
- }
- $updateData = [
- 'login_ip' => $ip,
- 'login_time' => time(),
- 'update_time' => time(),
- ];
- if ($info['wallet_token'] == '') {
- $updateData['wallet_token'] = make_wallet_token($walletUrl, $userId);
- }
- }
- // 获取授权TOKEN
- $jwt = new Jwt('jwt_wx');
- $token = $jwt->getToken($userId);
- RedisService::set("auths:info:{$userId}", $info, 6 * 3600);
- $this->error = 2004;
- return [
- 'token' => $token,
- 'info' => [
- 'id' => $userId,
- 'wallet_url' => $info['wallet_url'],
- 'member_level' => intval($info['member_level']),
- 'usdt' => round($info['usdt'], 4),
- 'sbt' => round($info['sbt'], 2),
- 'profit' => round($info['profit'], 2),
- 'performance' => round($info['performance'], 2),
- 'code' => $info['code'],
- 'nickname' => $info['nickname'],
- 'parent_id' => $info['parent_id'],
- 'bonus_rate' => $info['bonus_rate'],
- 'pledge_auto' => $info['pledge_auto'],
- 'recharge_url' => $info['recharge_url'],
- 'parent_url' => $parentWalletUrl,
- ],
- ];
- }
- /**
- * 用户信息
- * @param int $userId 用户ID
- * @param int $type 返回数据类型:1-默认,2-充值,3-提现
- * @param false $refresh
- * @return array|mixed
- */
- public function getInfo(int $userId, $type = 1, $refresh = false)
- {
- $cacheKey = "caches:member:info_{$userId}_{$type}";
- $info = RedisService::get($cacheKey);
- if ($info && !$refresh) {
- return $info;
- }
- $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])
- ->select(['id', 'nickname', 'code', 'member_level', 'usdt', 'sbt', 'performance', 'profit', 'profit_total', 'pledge_profit', 'manage_profit', 'share_profit', 'pj_profit', 'global_profit', 'parent_id', 'wallet_url', 'wallet_token', 'recharge_url','recharge_token', 'bonus_rate', 'pledge_auto', 'trade_status', 'status'])
- ->first();
- $info = $info ? $info->toArray() : [];
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- $parentInfo = isset($info['parent']) ? $info['parent'] : [];
- $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
- $walletUrl = isset($info['wallet_url']) ? $info['wallet_url'] : '';
- $walletToken = isset($info['wallet_token']) ? $info['wallet_token'] : '';
- if ($type == 3 && $walletUrl && $walletToken != make_wallet_token($walletUrl, $userId)) {
- $info['error'] = '钱包地址已被修改';
- }
- $rechargeUrl = isset($info['recharge_url']) ? $info['recharge_url'] : '';
- if(empty($rechargeUrl)){
- $rechargeUrl = CregisPayService::make()->createAddress(1000);
- if($rechargeUrl){
- $rechargeToken = make_wallet_token($rechargeUrl, $userId);
- $this->model->where(['id'=>$userId])->update(['recharge_url'=> $rechargeUrl,'recharge_token'=>$rechargeToken,'update_time'=>time()]);
- }
- }
- $rechargeToken = isset($info['recharge_token']) ? $info['recharge_token'] : '';
- if ($type == 2 && $rechargeUrl && $rechargeToken != make_wallet_token($rechargeUrl, $userId)) {
- $info['error'] = '钱包地址已被修改';
- }
- $info = [
- 'id' => $userId,
- 'wallet_url' => $info['wallet_url'],
- 'member_level' => intval($info['member_level']),
- 'usdt' => moneyFormat($info['usdt'], 2),
- 'sbt' => moneyFormat($info['sbt'], 2),
- 'performance' => moneyFormat($info['performance'], 2),
- 'profit' => moneyFormat($info['profit'], 2),
- 'profit_total' => moneyFormat($info['profit_total'], 2),
- 'pledge_total' => moneyFormat($info['pledge_profit'], 2),
- 'share_profit' => moneyFormat($info['share_profit'], 2),
- 'manage_profit' => moneyFormat($info['manage_profit'], 2),
- 'global_profit' => moneyFormat($info['global_profit'], 2),
- 'pj_profit' => moneyFormat($info['pj_profit'], 2),
- 'code' => $info['code'],
- 'nickname' => $info['nickname'],
- 'parent_id' => $info['parent_id'],
- 'bonus_rate' => $info['bonus_rate'],
- 'pledge_auto' => $info['pledge_auto'],
- 'error' => isset($info['error']) ? $info['error'] : '',
- 'parent_url' => $parentWalletUrl,
- 'recharge_url' => $rechargeUrl,
- 'max_usdt_rate' => ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0),
- 'sbt_fee' => ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0),
- 'recharge_min' => ConfigService::make()->getConfigByCode('recharge_min_money', 0.1),
- 'withdraw_min' => ConfigService::make()->getConfigByCode('withdraw_min_money', 0),
- 'recharge_open' => ConfigService::make()->getConfigByCode('recharge_open', 1),
- 'withdraw_open' => ConfigService::make()->getConfigByCode('withdraw_open', 1),
- ];
- if ($type == 1) {
- $chainTotal = BalanceLogService::make()->getCountByType($userId, 1);
- $ptTotal = AccountLogService::make()->getCountByType($userId, 5, 1);
- $info['recharge_total'] = moneyFormat($chainTotal + $ptTotal, 2);
- $chainTotal = BalanceLogService::make()->getCountByType($userId, 2, 0, 0);
- $ptTotal = AccountLogService::make()->getCountByType($userId, 6, 1);
- $info['withdraw_total'] = moneyFormat($chainTotal + $ptTotal, 2);
- }
- RedisService::set($cacheKey, $info, rand(5, 10));
- return $info;
- }
- /**
- * 获取级数据
- * @param $levelId
- * @param $type 类型:1-当前等级数据,2-下一等级数据
- * @return array|mixed
- */
- public function getLevelData($levelId, $type = 1)
- {
- $cacheKey = "caches:member:level_{$levelId}_{$type}";
- $info = RedisService::get($cacheKey);
- if ($info) {
- return $info;
- }
- $data = MemberLevelModel::where(function ($query) use ($type, $levelId) {
- if ($type == 2) {
- $query->where('id', '>', $levelId);
- } else {
- $query->where('id', $levelId);
- }
- })
- ->where(['status' => 1, 'mark' => 1])
- ->select(['id', 'name', 'upgrade_usdt', 'bonus_rate', 'weighting_rate'])
- ->orderBy('sort', 'asc')
- ->orderBy('id', 'asc')
- ->first();
- $data = $data ? $data->toArray() : [];
- if ($data) {
- RedisService::set($cacheKey, $data, rand(3600, 7200));
- }
- return $data;
- }
- /**
- * 设置分红比例
- * @param int $userId 用户ID
- * @param array $params 参数,user_id-设置用户ID(必选),bonus_rate-比例
- * @return bool
- */
- public function setBonus(int $userId, array $params)
- {
- // 参数验证
- $uid = isset($params['user_id']) ? intval($params['user_id']) : 0;
- $bonusRate = isset($params['bonus_rate']) && $params['bonus_rate'] > 0 ? floatval($params['bonus_rate']) : 0;
- if ($uid <= 0) {
- $this->error = 2014;
- return false;
- }
- if ($bonusRate < 0 || $bonusRate >= 100) {
- $this->error = 1022;
- return false;
- }
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- // 账号状态
- $status = isset($info['status']) ? $info['status'] : 0;
- if ($status != 1) {
- $this->error = 2015;
- return false;
- }
- // 设置用户
- $userInfo = $this->model->where(['id' => $uid, 'status' => 1, 'mark' => 1])
- ->select(['id', 'parent_id', 'parent_ids', 'bonus_rate'])
- ->first();
- if (empty($userInfo)) {
- $this->error = 1042;
- return false;
- }
- // 上级用户校验
- $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
- $parentIds = isset($userInfo['parent_ids']) ? $userInfo['parent_ids'] : '';
- if ($parentId != $userId) {
- $this->error = 1043;
- return false;
- }
- // 最大设置比例
- $maxBonusRate = $this->getUpBonusRate($uid, $parentIds);
- if ($maxBonusRate > 0 && $bonusRate > $maxBonusRate) {
- $this->errorData = ['rate' => $maxBonusRate];
- $this->error = 2036;
- return false;
- }
- // 更新数据
- $data = [
- 'bonus_rate' => floatval($bonusRate),
- 'update_time' => time()
- ];
- if (!$this->model->where(['id' => $uid])->update($data)) {
- $this->error = 1020;
- return false;
- }
- $this->error = 1019;
- return true;
- }
- /**
- * 获取上级团队设置的最近的比例
- * @param $userId
- * @param $parentIds
- * @return false|int|mixed
- */
- public function getUpBonusRate($userId, $parentIds)
- {
- $cacheKey = "caches:member:upRate_{$userId}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
- }
- $parentIds = $parentIds ? explode(',', $parentIds) : [];
- $parentIds = array_filter($parentIds);
- krsort($parentIds);
- if (empty($parentIds) || !is_array($parentIds)) {
- return 0;
- }
- $data = $this->model->whereIn('id', $parentIds)
- ->where('bonus_rate', '>', 0)
- ->where(['mark' => 1])
- ->select(['id', 'bonus_rate'])
- ->orderByRaw('FIELD(id, "' . implode(',', $parentIds) . '")')
- ->first();
- $data = $data ? $data->toArray() : [];
- if ($data) {
- RedisService::set($cacheKey, $data, rand(3, 5));
- }
- return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
- }
- /**
- * 获取上级团队设置的最近的工作室分红比例
- * @param $userId
- * @param $parentIds
- * @return false|int|mixed
- */
- public function getUpRoomBonusRate($userId, $parentIds)
- {
- $cacheKey = "caches:member:upRoomRate_{$userId}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
- }
- $parentIds = $parentIds ? explode(',', $parentIds) : [];
- $parentIds = array_filter($parentIds);
- krsort($parentIds);
- if (empty($parentIds) || !is_array($parentIds)) {
- return 0;
- }
- $data = $this->model->whereIn('id', $parentIds)
- ->where('room_bonus_rate', '>', 0)
- ->where(['mark' => 1])
- ->select(['id', 'room_bonus_rate'])
- ->orderByRaw('FIELD(id, "' . implode(',', $parentIds) . '")')
- ->first();
- $data = $data ? $data->toArray() : [];
- if ($data) {
- RedisService::set($cacheKey, $data, rand(3, 5));
- }
- return isset($data['room_bonus_rate']) ? $data['room_bonus_rate'] : 0;
- }
- /**
- * 设置自动质押状态
- * @param int $userId 用户ID
- * @param array $params 参数,status-状态(1-开启,0-关闭,必选)
- * @return bool
- */
- public function setPledge(int $userId, array $params)
- {
- // 参数验证
- $pledgeStatus = isset($params['status']) ? intval($params['status']) : 0;
- if (!in_array($pledgeStatus, [0, 1])) {
- $this->error = 2014;
- return false;
- }
- // 关闭限制验证
- $cacheKey = "caches:pledge:limitClose_{$userId}";
- if ($pledgeStatus == 0 && RedisService::get($cacheKey)) {
- $this->error = 2031;
- return false;
- }
- // 账号信息
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id', 'pledge_auto', 'status'])->first();
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- // 账号状态
- $status = isset($info['status']) ? $info['status'] : 0;
- if ($status != 1) {
- $this->error = 2015;
- return false;
- }
- // 质押过,且已经退本过才可关闭
- if ($pledgeStatus == 0 && !PledgeOrderService::make()->checkPledge($userId)) {
- $this->error = 2030;
- return false;
- }
- // 更新
- $data = ['pledge_auto' => $pledgeStatus, 'update_time' => time()];
- if (!$this->model->where(['id' => $userId])->update($data)) {
- $this->error = 1020;
- return false;
- }
- // 限制关闭次数
- if ($pledgeStatus == 0) {
- RedisService::set($cacheKey, date('Y-m-d H:i:s'), 30);
- }
- $this->error = 1019;
- return true;
- }
- /**
- * 保存资料
- * @param int $userId 用户ID
- * @param $params 参数
- * @return bool
- */
- public function setProfile(int $userId, $params)
- {
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- $data = [
- 'update_time' => time()
- ];
- if (isset($params['nickname']) && $params['nickname']) {
- $data['nickname'] = trim($params['nickname']);
- }
- // 头像
- // 更新
- if (!$this->model->where(['id' => $userId])->update($data)) {
- $this->error = 1009;
- return false;
- }
- $this->error = 1008;
- return true;
- }
- /**
- * 生成普通参数二维码
- * @param $str 参数
- * @param bool $refresh 是否重新生成
- * @return bool
- */
- public function makeQrcode($str, $dir='qrcode', $refresh = false, $size = 4, $margin = 2, $level = 2)
- {
- try {
- $basePath = base_path() . '/public';
- $qrFile = "/images/{$dir}/";
- 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;
- }catch (\Exception $exception){
- return false;
- }
- }
- /**
- * 提现
- * @param $userId 提现用户ID
- * @param $params 提现参数:money-金额(必选)、coin_type-账户类型/币种(必选)
- * @return array|false|mixed
- */
- public function withdraw($userId, $params)
- {
- $money = isset($params['money']) ? floatval($params['money']) : 0;
- $coinType = isset($params['coin_type']) ? intval($params['coin_type']) : 1;
- if ($money <= 0) {
- $this->error = 2025;
- return false;
- }
- // 锁
- $coinType = $coinType == 1 ? 1 : 2;
- $cacheKey = "caches:withdraw:{$userId}_{$coinType}";
- if (RedisService::get($cacheKey . '_lock')) {
- return false;
- }
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- $status = isset($info['status']) ? $info['status'] : 0;
- $tradeStatus = isset($info['trade_status']) ? $info['trade_status'] : 0;
- $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
- $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
- $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
- if ($status != 1) {
- $this->error = 2015; // 冻结
- return false;
- }
- if (in_array($tradeStatus, [2, 3])) {
- $this->error = intval("202{$tradeStatus}");
- return false;
- }
- // 可提金额或手续费验证
- try {
- DB::beginTransaction();
- RedisService::set($cacheKey . '_lock', date('Y-m-d H:i:s'), rand(3,5));
- if ($coinType == 1) {
- $maxUsdtRate = ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0);
- $withdrawTotal = BalanceLogService::make()->getCountByType($userId, 2, 1, 0);
- $maxWithdrawMoney = ($withdrawTotal + $userUsdt);
- $maxWithdrawMoney = $maxUsdtRate > 0 && $maxUsdtRate < 100 ? moneyFormat($maxWithdrawMoney * $maxUsdtRate / 100, 2) : $maxWithdrawMoney;
- if (($withdrawTotal + floatval($money)) >= $maxWithdrawMoney) {
- DB::rollBack();
- $this->error = 2026; // 可提金额超出
- $this->errorData = ['money' => moneyFormat($maxWithdrawMoney - $withdrawTotal, 2)];
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 提现处理
- $updateData = ['usdt' => DB::raw("usdt - {$money}"), 'update_time' => time()];
- if (!$this->model->where(['id' => $userId])->update($updateData)) {
- DB::rollBack();
- $this->error = 2033; // 提现处理失败
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 账单
- $log = [
- 'user_id' => $userId,
- 'order_no' => get_order_num('SW'),
- 'type' => 2,
- 'user_type' => 1,
- 'coin_type' => 1,
- 'money' => $money,
- 'actual_money' => $money,
- 'fee' => 0,
- 'pay_type' => 10,
- 'pay_status' => 10,
- 'wallet_url' => $info['wallet_url'],
- 'pt_wallet_url' => '',
- 'date' => date('Y-m-d'),
- 'create_time' => time(),
- 'audit_remark' => '',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!BalanceLogModel::insertGetId($log)) {
- DB::rollBack();
- $this->error = 2033;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // USDT余额账单
- $data = [
- 'user_id' => $userId,
- 'order_no' => $log['order_no'],
- 'type' => 4,
- 'user_type' => 1,
- 'coin_type' => 1,
- 'money' => -$money,
- 'before_money' => $userUsdt,
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => '余额提现',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2033;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 成功
- DB::commit();
- return $this->getInfo($userId, 3, true);
- } // 收益提现
- else {
- $sbtUsdtFee = ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0);
- $sbtPrice = PriceLogService::make()->getSbtPrice();
- $sbtFee = moneyFormat(floatval($sbtUsdtFee) / $sbtPrice, 2);
- if ($sbtFee > $userSbt) {
- DB::rollBack();
- $this->error = 2032; // 手续费不足
- $this->errorData = ['money' => $sbtFee];
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 余额是否足
- if ($money > $userProfit) {
- DB::rollBack();
- $this->error = 2026; // 手续费不足
- $this->errorData = ['money' => $userProfit];
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 提现处理
- $updateData = ['profit' => DB::raw("profit - {$money}"), 'sbt' => DB::raw("sbt - {$sbtFee}"), 'update_time' => time()];
- if (!$this->model->where(['id' => $userId])->update($updateData)) {
- DB::rollBack();
- $this->error = 2033; // 提现处理失败
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 账单
- $log = [
- 'user_id' => $userId,
- 'order_no' => get_order_num('SW'),
- 'type' => 2,
- 'user_type' => 1,
- 'coin_type' => 2,
- 'money' => $money,
- 'actual_money' => $money,
- 'fee' => $sbtFee,
- 'fee_usdt' => $sbtUsdtFee,
- 'pay_type' => 10,
- 'pay_status' => 10,
- 'wallet_url' => $info['wallet_url'],
- 'pt_wallet_url' => '',
- 'date' => date('Y-m-d'),
- 'create_time' => time(),
- 'audit_remark' => '',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!BalanceLogModel::insertGetId($log)) {
- DB::rollBack();
- $this->error = 2033;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 收益账单
- $data = [
- 'user_id' => $userId,
- 'order_no' => $log['order_no'],
- 'type' => 4,
- 'user_type' => 1,
- 'coin_type' => 3,
- 'money' => -$money,
- 'before_money' => $userProfit,
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => '收益提现',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2033;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 手续费账单
- if ($sbtFee > 0) {
- $data = [
- 'user_id' => $userId,
- 'order_no' => $log['order_no'],
- 'type' => 4,
- 'user_type' => 1,
- 'coin_type' => 2,
- 'money' => -$sbtFee,
- 'before_money' => $userSbt,
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => '提现手续费',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2033;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- }
- // 成功
- DB::commit();
- RedisService::keyDel("caches:balanceLog:total*");
- RedisService::clear($cacheKey . '_lock');
- return $this->getInfo($userId, 3, true);
- }
- } catch (\Exception $exception) {
- DB::rollBack();
- $this->errorData = ['error' => $exception->getMessage()];
- RedisService::clear($cacheKey . '_lock');
- $this->error = 2028;
- return false;
- }
- }
- /**
- * 闪兑
- * @param $userId 用户
- * @param $params 参数:money-闪兑金额
- * @return array|false|mixed
- */
- public function exchange($userId, $params)
- {
- $money = isset($params['money']) ? floatval($params['money']) : 0;
- $coinType = 2;
- if ($money <= 0) {
- $this->error = 2101;
- return false;
- }
- $cacheKey = "caches:exchange:{$userId}_{$coinType}";
- if (RedisService::get($cacheKey . '_lock')) {
- return false;
- }
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','usdt','profit','sbt','status'])->first();
- if (empty($info)) {
- $this->error = 2016;
- return false;
- }
- $status = isset($info['status']) ? $info['status'] : 0;
- $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
- $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
- $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
- if ($status != 1) {
- $this->error = 2015; // 冻结
- return false;
- }
- // 闪兑验证
- $sbtLimit = ConfigService::make()->getConfigByCode('sbt_exchange_limit', 100);
- $sbtPrice = PriceLogService::make()->getSbtPrice();
- $sbtLimit = round($sbtLimit/$sbtPrice, 2);
- $sbtLimit = $sbtLimit>0? $sbtLimit : 0;
- if($sbtLimit>0 && $sbtLimit > $userSbt){
- $this->errorData = ['money'=> $sbtLimit];
- $this->error = lang(2102);
- return false;
- }
- $exchangeSbtMin = ConfigService::make()->getConfigByCode('exchange_sbt_min', 100);
- $exchangeSbtMin = $exchangeSbtMin>10? $exchangeSbtMin : 100;
- if($money<$exchangeSbtMin){
- $this->errorData = ['money'=> $exchangeSbtMin];
- $this->error = lang(2106);
- return false;
- }
- // 可提金额或手续费验证
- try {
- DB::beginTransaction();
- RedisService::set($cacheKey . '_lock',date('Y-m-d H:i:s'), rand(3,5));
- // TODO SBT 闪兑 USDT
- if ($coinType == 2) {
- // 手续费
- $exchangeFeeRate = ConfigService::make()->getConfigByCode('exchange_fee_rate', 0);
- $exchangeFeeRate = $exchangeFeeRate>0 && $exchangeFeeRate<100? floatval($exchangeFeeRate) : 0;
- // 闪兑金额
- $sbtUsdt = moneyFormat($money * $sbtPrice, 2); // 闪兑USDT金额
- $feeUsdt = round($sbtUsdt * $exchangeFeeRate/100, 2);
- $feeUsdt = $feeUsdt>0? $feeUsdt : 0.01;
- $actualUsdt = moneyFormat($sbtUsdt - $feeUsdt, 2);
- // 闪兑入账收益账户处理
- $updateData = [
- 'profit' => DB::raw("profit + {$actualUsdt}"),
- 'sbt' => DB::raw("sbt - {$money}"),
- 'update_time' => time()
- ];
- if (!$this->model->where(['id' => $userId])->update($updateData)) {
- DB::rollBack();
- $this->error = 2103;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // SBT扣除账单
- $orderNo = get_order_num('SE');
- $data = [
- 'user_id' => $userId,
- 'order_no' => $orderNo,
- 'type' => 2,
- 'user_type' => 1,
- 'coin_type' => 2,
- 'money' => -$money,
- 'before_money' => $userSbt,
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => 'SBT闪兑',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2103;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 到账USDT收益账单
- $data = [
- 'user_id' => $userId,
- 'order_no' => $orderNo,
- 'type' => 2,
- 'user_type' => 1,
- 'coin_type' => 3,
- 'money' => $actualUsdt,
- 'before_money' => $userProfit,
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => 'SBT闪兑到账',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2103;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 闪兑手续费账单
- $data = [
- 'user_id' => $userId,
- 'order_no' => $orderNo,
- 'type' => 18,
- 'user_type' => 1,
- 'coin_type' => 3,
- 'money' => -$feeUsdt,
- 'before_money' => moneyFormat($userProfit + $actualUsdt,2),
- 'create_time' => time(),
- 'action_ip' => get_client_ip(),
- 'remark' => 'SBT闪兑手续费',
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($data)) {
- DB::rollBack();
- $this->error = 2103;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- // 成功
- DB::commit();
- $this->error = 2105;
- return $this->getInfo($userId, 3, true);
- }else{
- DB::rollBack();
- $this->error = 1031;
- RedisService::clear($cacheKey . '_lock');
- return false;
- }
- } catch (\Exception $exception) {
- DB::rollBack();
- $this->errorData = ['error' => $exception->getMessage()];
- RedisService::clear($cacheKey . '_lock');
- $this->error = 2104;
- return false;
- }
- }
- /**
- * 更新用户等级
- * @param $userId 需要更新等级用户ID
- */
- public function upgradeUpdate($userId)
- {
- $cacheKey = "caches:member:levelLock_{$userId}";
- if (RedisService::get($cacheKey)) {
- $this->error = lang(4303, ['uid' => $userId]);
- return false;
- }
- RedisService::set($cacheKey, date('Y-m-d H:i:s'), rand(5, 10));
- $userInfo = $this->model->where(['id' => $userId, 'mark' => 1])
- ->select(['id', 'usdt', 'member_level', 'performance','upgrade_status', 'upgrade_at', 'status'])
- ->first();
- if (empty($userInfo)) {
- RedisService::clear($cacheKey);
- $this->error = lang(4301, ['uid' => $userId]);
- return false;
- }
- $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0; // 个人等级
- $performance = isset($userInfo['performance']) ? $userInfo['performance'] : 0; // 个人业绩
- $upgradeStatus = isset($userInfo['upgrade_status']) ? $userInfo['upgrade_status'] : 0; // 升级方式
- $teamPerformance = TeamService::make()->getTeamPerformanceByType($userId, 2, true);
- $teamPerformance = round($teamPerformance + $performance, 2);
- // 等级条件
- $nextLevel = MemberLevelModel::where('upgrade_usdt', '<=', $teamPerformance)
- ->where(['status' => 1, 'mark' => 1])
- ->orderBy('sort', 'desc')
- ->orderBy('id', 'desc')
- ->value('id');
- $nextLevel = $nextLevel>0? intval($nextLevel) : 0;
- // 是否只升不降
- if ($$upgradeStatus==2 && $nextLevel<=$memberLevel) {
- RedisService::clear($cacheKey);
- $this->error = lang(4302, ['uid' => $userId]);
- return false;
- }
- // 更新等级
- if (!$this->model->where(['id' => $userId])->update(['member_level' => $nextLevel, 'old_level' => $memberLevel,'upgrade_at'=>date('Y-m-d H:i:s'), 'update_time' => time()])) {
- RedisService::clear($cacheKey);
- $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel]);
- return false;
- }
- $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel]);
- RedisService::set($cacheKey, ['level' => $nextLevel, 'old' => $memberLevel, 'date' => date('Y-m-d H:i:s')], rand(30, 60));
- return ['msg' => '更新成功', 'uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel];
- }
- /**
- * 获取可质押用户列表(按批次数量获取)
- * @return mixed
- */
- public function pledgeUserList()
- {
- try {
- $limit = ConfigService::make()->getConfigByCode('pledge_user_count', 500);
- $limit = $limit > 0 ? $limit : 500;
- $pledgeUsdt = ConfigService::make()->getConfigByCode('pledge_money', 500);
- $pledgeUsdt = $pledgeUsdt > 0 ? $pledgeUsdt : 500;
- $sbtPrice = PriceLogService::make()->getSbtPrice();
- $sbtUsdtFee = ConfigService::make()->getConfigByCode('pledge_sbt_usdt_fee', 0);
- $sbtUsdtFee = $sbtUsdtFee > 0 ? floatval($sbtUsdtFee) : 0;
- $sbtFee = $sbtUsdtFee && $sbtPrice > 0 ? moneyFormat($sbtUsdtFee / $sbtPrice, 2) : 0;
- $datas = $this->model->from('member as a')
- ->leftJoin('pledge_orders as b', 'b.user_id', '=', 'a.id')
- ->where('a.usdt', '>=', $pledgeUsdt)
- ->where('a.sbt', '>=', $sbtFee)
- ->where(function($query){
- $query->where('b.id', '<=', 0)->orWhere('a.pledge_count', '<=', 0);
- })
- ->where(['a.pledge_auto' => 1, 'a.status' => 1, 'a.mark' => 1])
- ->select(['a.id', 'a.pledge_auto', 'a.usdt', 'a.sbt', 'a.profit', 'a.trade_status','a.settle_status','a.status', 'a.parent_ids', 'b.id as pledge_id'])
- ->limit($limit)
- ->orderByRaw('rand()')
- ->orderBy('a.id', 'asc')
- ->get();
- return $datas?$datas->toArray() : [];
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * 获取需要更新等级用户列表(更新等级时间超出当前时间则需要更新)
- * @return mixed
- */
- public function getUpgradeUserList()
- {
- try {
- $limit = ConfigService::make()->getConfigByCode('upgrade_user_count', 500);
- $limit = $limit > 0 ? $limit : 500;
- $datas = $this->model->where('upgrade_at', '>', date('Y-m-d H:i:s'))
- ->where(['status' => 1, 'mark' => 1])
- ->select(['id', 'pledge_auto', 'usdt', 'sbt', 'profit', 'trade_status', 'parent_ids'])
- ->limit($limit)
- ->orderByRaw('rand()')
- ->orderBy('id', 'asc')
- ->get();
- return $datas?$datas->toArray() : [];
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * 有效开发者列表
- * @return array|mixed
- */
- public function getDeveloperList()
- {
- $cacheKey = "caches:developer:list";
- $datas = RedisService::get($cacheKey);
- if($datas){
- return $datas;
- }
- $datas = DeveloperModel::where(['status'=>1])
- ->where('last_settle_at','<',date('Y-m-d', time() - 7 * 86400))
- ->limit(200)
- ->get();
- $datas = $datas? $datas->toArray() : [];
- if($datas){
- RedisService::set($cacheKey, $datas, rand(3600, 7200));
- }
- return $datas;
- }
- }
|