MemberService.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Helpers\Jwt;
  13. use App\Models\AccountLogModel;
  14. use App\Models\BalanceLogModel;
  15. use App\Models\MemberLevelModel;
  16. use App\Models\MemberModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\RedisService;
  20. use App\Services\ToolService;
  21. use App\Services\WalletService;
  22. use Illuminate\Support\Facades\DB;
  23. use phpqrcode\QRcode;
  24. /**
  25. * 会员-服务类
  26. * @author laravel开发员
  27. * @since 2020/11/11
  28. * @package App\Services\Api
  29. */
  30. class MemberService extends BaseService
  31. {
  32. protected static $instance;
  33. /**
  34. * 构造函数
  35. * @author laravel开发员
  36. * @since 2020/11/11
  37. */
  38. public function __construct()
  39. {
  40. $this->model = new MemberModel();
  41. }
  42. /**
  43. * 静态入口
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = new static();
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * 登录注册
  54. * @param $walletUrl
  55. * @param string $scode
  56. * @return array|false
  57. */
  58. public function loginOrRegister($walletUrl, $scode = '')
  59. {
  60. if (empty($walletUrl)) {
  61. $this->error = 1038;
  62. return false;
  63. }
  64. $info = $this->model->with(['parent'])->where(['wallet_url' => $walletUrl, 'mark' => 1])
  65. ->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'])
  66. ->first();
  67. $info = $info ? $info->toArray() : [];
  68. $parentInfo = isset($info['parent']) ? $info['parent'] : [];
  69. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  70. $ip = get_client_ip();
  71. $ipData = ToolService::make()->getIpAddress($ip, '');
  72. $province = isset($ipData['regionName']) ? $ipData['regionName'] : '';
  73. $city = isset($ipData['city']) ? $ipData['city'] : '';
  74. /* TODO 注册 */
  75. if (empty($info)) {
  76. // 上级账号
  77. $parentId = 0;
  78. $parentIds = '';
  79. if ($scode) {
  80. $parentInfo = $this->model->where(['code' => $scode, 'mark' => 1])->select(['id', 'parent_ids', 'wallet_url'])->first();
  81. $parentId = isset($parentInfo['id']) ? $parentInfo['id'] : 0;
  82. $parents = isset($parentInfo['parent_ids']) ? $parentInfo['parent_ids'] : '';
  83. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  84. if ($parentId) {
  85. $parentIds = $parents ? trim($parents, ',') . ",{$parentId}," : "{$parentId},";
  86. }
  87. }
  88. // 注册奖励
  89. $awardSbtUsdt = ConfigService::make()->getConfigByCode('register_award_sbt', 0);
  90. if ($awardSbtUsdt > 0) {
  91. $sbtPrice = PriceLogService::make()->getSbtPrice();
  92. $awardSbtNum = $sbtPrice ? round($awardSbtUsdt * 1 / $sbtPrice, 2) : 0;
  93. }
  94. DB::beginTransaction();
  95. $id = $this->model->max('id') + 1;
  96. $info = [
  97. 'nickname' => 'SBT_' . substr($walletUrl, -6, 6),
  98. 'wallet_url' => $walletUrl,
  99. 'wallet_token' => make_wallet_token($walletUrl, $id),
  100. 'avatar' => '',
  101. 'recharge_url' => '',
  102. 'member_level' => 0,
  103. 'usdt' => 0.00,
  104. 'sbt' => $awardSbtNum,
  105. 'profit' => 0.00,
  106. 'bonus_rate' => 0.00,
  107. 'performance' => 0.00,
  108. 'parent_id' => $parentId,
  109. 'parent_ids' => $parentIds,
  110. 'pledge_auto' => 1,
  111. 'code' => strtoupper(get_random_code(9, 'S', "{$id}")),
  112. 'login_ip' => $ip,
  113. 'login_region' => $province . '' . $city,
  114. 'login_time' => time(),
  115. 'create_time' => time(),
  116. 'trade_status' => 1,
  117. 'status' => 1,
  118. 'mark' => 1,
  119. ];
  120. if (!$userId = $this->model->insertGetId($info)) {
  121. DB::rollBack();
  122. $this->error = 2007;
  123. return false;
  124. }
  125. if ($awardSbtNum > 0) {
  126. $log = [
  127. 'user_id' => $userId,
  128. 'type' => 13,
  129. 'order_no' => get_order_num('RW'),
  130. 'coin_type' => 2,
  131. 'money' => $awardSbtNum,
  132. 'before_money' => 0,
  133. 'create_time' => time(),
  134. 'remark' => '注册奖励',
  135. 'action_ip' => get_client_ip(),
  136. 'status' => 1,
  137. 'mark' => 1
  138. ];
  139. if (!AccountLogModel::insertGetId($log)) {
  140. DB::rollBack();
  141. $this->error = 2007;
  142. return false;
  143. }
  144. }
  145. DB::commit();
  146. // 清除团队统计数据或列表缓存
  147. RedisService::keyDel("caches:team*");
  148. } else {
  149. $userId = $info['id'];
  150. $status = isset($info['status']) ? $info['status'] : 0;
  151. if ($status != 1) {
  152. $this->error = 2015;
  153. return false;
  154. }
  155. $updateData = [
  156. 'login_ip' => $ip,
  157. 'login_region' => $province . '' . $city,
  158. 'login_time' => time(),
  159. 'update_time' => time(),
  160. ];
  161. if ($info['wallet_token'] == '') {
  162. $updateData['wallet_token'] = make_wallet_token($walletUrl, $userId);
  163. }
  164. $this->model->where(['id' => $userId])->update($updateData);
  165. }
  166. // 获取授权TOKEN
  167. $jwt = new Jwt('jwt_wx');
  168. $token = $jwt->getToken($userId);
  169. RedisService::set("auths:info:{$userId}", $info, 6 * 3600);
  170. $this->error = 2004;
  171. return [
  172. 'token' => $token,
  173. 'info' => [
  174. 'id' => $userId,
  175. 'wallet_url' => $info['wallet_url'],
  176. 'member_level' => intval($info['member_level']),
  177. 'usdt' => round($info['usdt'], 4),
  178. 'sbt' => round($info['sbt'], 2),
  179. 'profit' => round($info['profit'], 2),
  180. 'performance' => round($info['performance'], 2),
  181. 'code' => $info['code'],
  182. 'nickname' => $info['nickname'],
  183. 'parent_id' => $info['parent_id'],
  184. 'bonus_rate' => $info['bonus_rate'],
  185. 'pledge_auto' => $info['pledge_auto'],
  186. 'parent_url' => $parentWalletUrl,
  187. ],
  188. ];
  189. }
  190. /**
  191. * 用户信息
  192. * @param int $userId 用户ID
  193. * @param int $type 返回数据类型:1-默认,2-充值,3-提现
  194. * @param false $refresh
  195. * @return array|mixed
  196. */
  197. public function getInfo(int $userId, $type = 1, $refresh = false, $address='')
  198. {
  199. $cacheKey = "caches:member:info_{$userId}_{$type}";
  200. $info = RedisService::get($cacheKey);
  201. if ($info && !$refresh) {
  202. return $info;
  203. }
  204. $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])
  205. ->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', 'bonus_rate', 'pledge_auto', 'trade_status', 'status'])
  206. ->first();
  207. $info = $info ? $info->toArray() : [];
  208. if (empty($info)) {
  209. $this->error = 2016;
  210. return false;
  211. }
  212. $parentInfo = isset($info['parent']) ? $info['parent'] : [];
  213. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  214. $walletUrl = isset($info['wallet_url']) ? $info['wallet_url'] : '';
  215. $walletToken = isset($info['wallet_token']) ? $info['wallet_token'] : '';
  216. if ($type == 3 && $walletUrl && $walletToken != make_wallet_token($walletUrl, $userId)) {
  217. $info['error'] = '钱包地址已被修改';
  218. }
  219. $rechargeAddress = WalletService::make()->getWallet(1);
  220. $rechargeUrl = isset($rechargeAddress['address']) ? $rechargeAddress['address'] : '';
  221. $info = [
  222. 'id' => $userId,
  223. 'wallet_url' => $info['wallet_url'],
  224. 'member_level' => intval($info['member_level']),
  225. 'usdt' => moneyFormat($info['usdt'], 2),
  226. 'sbt' => moneyFormat($info['sbt'], 2),
  227. 'performance' => moneyFormat($info['performance'], 2),
  228. 'profit' => moneyFormat($info['profit'], 2),
  229. 'profit_total' => moneyFormat($info['profit_total'], 2),
  230. 'pledge_total' => moneyFormat($info['pledge_profit'], 2),
  231. 'share_profit' => moneyFormat($info['share_profit'], 2),
  232. 'manage_profit' => moneyFormat($info['manage_profit'], 2),
  233. 'global_profit' => moneyFormat($info['global_profit'], 2),
  234. 'pj_profit' => moneyFormat($info['pj_profit'], 2),
  235. 'code' => $info['code'],
  236. 'nickname' => $info['nickname'],
  237. 'parent_id' => $info['parent_id'],
  238. 'bonus_rate' => $info['bonus_rate'],
  239. 'pledge_auto' => $info['pledge_auto'],
  240. 'error' => isset($info['error']) ? $info['error'] : '',
  241. 'parent_url' => $parentWalletUrl,
  242. 'recharge_url' => $rechargeUrl,
  243. 'max_usdt_rate' => ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0),
  244. 'sbt_fee' => ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0),
  245. 'recharge_min' => ConfigService::make()->getConfigByCode('recharge_min_money', 0.1),
  246. 'withdraw_min' => ConfigService::make()->getConfigByCode('withdraw_min_money', 0),
  247. ];
  248. if ($type == 1) {
  249. $chainTotal = BalanceLogService::make()->getCountByType($userId, 1);
  250. $ptTotal = AccountLogService::make()->getCountByType($userId, 5, 1);
  251. $info['recharge_total'] = moneyFormat($chainTotal + $ptTotal, 2);
  252. $chainTotal = BalanceLogService::make()->getCountByType($userId, 2, 0, 0);
  253. $ptTotal = AccountLogService::make()->getCountByType($userId, 6, 1);
  254. $info['withdraw_total'] = moneyFormat($chainTotal + $ptTotal, 2);
  255. }
  256. if($address){
  257. $info['address'] = $address;
  258. $info['token_amount'] = WalletService::make()->getUsdtBalance($address, true);
  259. }
  260. RedisService::set($cacheKey, $info, rand(5, 10));
  261. return $info;
  262. }
  263. /**
  264. * 获取级数据
  265. * @param $levelId
  266. * @param $type 类型:1-当前等级数据,2-下一等级数据
  267. * @return array|mixed
  268. */
  269. public function getLevelData($levelId, $type = 1)
  270. {
  271. $cacheKey = "caches:member:level_{$levelId}_{$type}";
  272. $info = RedisService::get($cacheKey);
  273. if ($info) {
  274. return $info;
  275. }
  276. $data = MemberLevelModel::where(function ($query) use ($type, $levelId) {
  277. if ($type == 2) {
  278. $query->where('id', '>', $levelId);
  279. } else {
  280. $query->where('id', $levelId);
  281. }
  282. })
  283. ->where(['status' => 1, 'mark' => 1])
  284. ->select(['id', 'name', 'upgrade_usdt', 'bonus_rate', 'weighting_rate'])
  285. ->orderBy('sort', 'asc')
  286. ->orderBy('id', 'asc')
  287. ->first();
  288. $data = $data ? $data->toArray() : [];
  289. if ($data) {
  290. RedisService::set($cacheKey, $data, rand(3600, 7200));
  291. }
  292. return $data;
  293. }
  294. /**
  295. * 设置分红比例
  296. * @param int $userId 用户ID
  297. * @param array $params 参数,user_id-设置用户ID(必选),bonus_rate-比例
  298. * @return bool
  299. */
  300. public function setBonus(int $userId, array $params)
  301. {
  302. // 参数验证
  303. $uid = isset($params['user_id']) ? intval($params['user_id']) : 0;
  304. $bonusRate = isset($params['bonus_rate']) && $params['bonus_rate'] > 0 ? floatval($params['bonus_rate']) : 0;
  305. if ($uid <= 0) {
  306. $this->error = 2014;
  307. return false;
  308. }
  309. if ($bonusRate < 0 || $bonusRate >= 100) {
  310. $this->error = 1022;
  311. return false;
  312. }
  313. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  314. if (empty($info)) {
  315. $this->error = 2016;
  316. return false;
  317. }
  318. // 账号状态
  319. $status = isset($info['status']) ? $info['status'] : 0;
  320. if ($status != 1) {
  321. $this->error = 2015;
  322. return false;
  323. }
  324. // 设置用户
  325. $userInfo = $this->model->where(['id' => $uid, 'status' => 1, 'mark' => 1])
  326. ->select(['id', 'parent_id', 'parent_ids', 'bonus_rate'])
  327. ->first();
  328. if (empty($userInfo)) {
  329. $this->error = 1042;
  330. return false;
  331. }
  332. // 上级用户校验
  333. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  334. $parentIds = isset($userInfo['parent_ids']) ? $userInfo['parent_ids'] : '';
  335. if ($parentId != $userId) {
  336. $this->error = 1043;
  337. return false;
  338. }
  339. // 最大设置比例
  340. $maxBonusRate = $this->getUpBonusRate($uid, $parentIds);
  341. if ($maxBonusRate > 0 && $bonusRate > $maxBonusRate) {
  342. $this->errorData = ['rate' => $maxBonusRate];
  343. $this->error = 1043;
  344. return false;
  345. }
  346. // 更新数据
  347. $data = [
  348. 'bonus_rate' => floatval($bonusRate),
  349. 'update_time' => time()
  350. ];
  351. if (!$this->model->where(['id' => $uid])->update($data)) {
  352. $this->error = 1020;
  353. return false;
  354. }
  355. $this->error = 1019;
  356. return true;
  357. }
  358. /**
  359. * 获取上级团队设置的最近的比例
  360. * @param $userId
  361. * @param $parentIds
  362. * @return false|int|mixed
  363. */
  364. public function getUpBonusRate($userId, $parentIds)
  365. {
  366. $cacheKey = "caches:member:upRate_{$userId}";
  367. $data = RedisService::get($cacheKey);
  368. if ($data) {
  369. return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
  370. }
  371. $parentIds = $parentIds ? explode(',', $parentIds) : [];
  372. $parentIds = array_filter($parentIds);
  373. krsort($parentIds);
  374. if (empty($parentIds) || !is_array($parentIds)) {
  375. return 0;
  376. }
  377. $data = $this->model->whereIn('id', $parentIds)
  378. ->where('bonus_rate', '>', 0)
  379. ->where(['mark' => 1])
  380. ->select(['id', 'bonus_rate'])
  381. ->orderByRaw('FIELD(id, "' . implode(',', $parentIds) . '")')
  382. ->first();
  383. $data = $data ? $data->toArray() : [];
  384. if ($data) {
  385. RedisService::set($cacheKey, $data, rand(3, 5));
  386. }
  387. return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
  388. }
  389. /**
  390. * 设置自动质押状态
  391. * @param int $userId 用户ID
  392. * @param array $params 参数,status-状态(1-开启,0-关闭,必选)
  393. * @return bool
  394. */
  395. public function setPledge(int $userId, array $params)
  396. {
  397. // 参数验证
  398. $pledgeStatus = isset($params['status']) ? intval($params['status']) : 0;
  399. if (!in_array($pledgeStatus, [0, 1])) {
  400. $this->error = 2014;
  401. return false;
  402. }
  403. // 关闭限制验证
  404. $cacheKey = "caches:pledge:limitClose_{$userId}";
  405. if ($pledgeStatus == 0 && RedisService::get($cacheKey)) {
  406. $this->error = 2031;
  407. return false;
  408. }
  409. // 账号信息
  410. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id', 'pledge_auto', 'status'])->first();
  411. if (empty($info)) {
  412. $this->error = 2016;
  413. return false;
  414. }
  415. // 账号状态
  416. $status = isset($info['status']) ? $info['status'] : 0;
  417. if ($status != 1) {
  418. $this->error = 2015;
  419. return false;
  420. }
  421. // 质押过,且已经退本过才可关闭
  422. if ($pledgeStatus == 0 && !PledgeOrderService::make()->checkPledge($userId)) {
  423. $this->error = 2030;
  424. return false;
  425. }
  426. // 更新
  427. $data = ['pledge_auto' => $pledgeStatus, 'update_time' => time()];
  428. if (!$this->model->where(['id' => $userId])->update($data)) {
  429. $this->error = 1020;
  430. return false;
  431. }
  432. // 限制关闭次数
  433. if ($pledgeStatus == 0) {
  434. RedisService::set($cacheKey, date('Y-m-d H:i:s'), 30);
  435. }
  436. $this->error = 1019;
  437. return true;
  438. }
  439. /**
  440. * 保存资料
  441. * @param int $userId 用户ID
  442. * @param $params 参数
  443. * @return bool
  444. */
  445. public function setProfile(int $userId, $params)
  446. {
  447. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  448. if (empty($info)) {
  449. $this->error = 2016;
  450. return false;
  451. }
  452. $data = [
  453. 'update_time' => time()
  454. ];
  455. if (isset($params['nickname']) && $params['nickname']) {
  456. $data['nickname'] = trim($params['nickname']);
  457. }
  458. // 头像
  459. // 更新
  460. if (!$this->model->where(['id' => $userId])->update($data)) {
  461. $this->error = 1009;
  462. return false;
  463. }
  464. $this->error = 1008;
  465. return true;
  466. }
  467. /**
  468. * 生成普通参数二维码
  469. * @param $str 参数
  470. * @param bool $refresh 是否重新生成
  471. * @return bool
  472. */
  473. public function makeQrcode($str, $dir='qrcode', $refresh = false, $size = 4, $margin = 2, $level = 2)
  474. {
  475. $basePath = base_path() . '/public';
  476. $qrFile = "/images/{$dir}/";
  477. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  478. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  479. }
  480. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  481. $qrFile = $qrFile . "C_{$key}.png";
  482. $cacheKey = "caches:qrcodes:member_" . $key;
  483. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  484. return $qrFile;
  485. }
  486. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  487. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  488. return false;
  489. }
  490. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  491. return $qrFile;
  492. }
  493. /**
  494. * 提现
  495. * @param $userId 提现用户ID
  496. * @param $params 提现参数:money-金额(必选)、coin_type-账户类型/币种(必选)
  497. * @return array|false|mixed
  498. */
  499. public function withdraw($userId, $params)
  500. {
  501. $money = isset($params['money']) ? floatval($params['money']) : 0;
  502. $coinType = isset($params['coin_type']) ? intval($params['coin_type']) : 1;
  503. if ($money <= 0) {
  504. $this->error = 2025;
  505. return false;
  506. }
  507. // 锁
  508. $coinType = $coinType == 1 ? 1 : 2;
  509. $cacheKey = "caches:withdraw:{$userId}_{$coinType}";
  510. if (RedisService::get($cacheKey . '_lock')) {
  511. return false;
  512. }
  513. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  514. if (empty($info)) {
  515. $this->error = 2016;
  516. return false;
  517. }
  518. $status = isset($info['status']) ? $info['status'] : 0;
  519. $tradeStatus = isset($info['trade_status']) ? $info['trade_status'] : 0;
  520. $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
  521. $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
  522. $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
  523. if ($status != 1) {
  524. $this->error = 2015; // 冻结
  525. return false;
  526. }
  527. if (in_array($tradeStatus, [2, 3])) {
  528. $this->error = intval("202{$tradeStatus}");
  529. return false;
  530. }
  531. // 可提金额或手续费验证
  532. try {
  533. DB::beginTransaction();
  534. RedisService::set($cacheKey . '_lock', date('Y-m-d H:i:s'), rand(3,5));
  535. if ($coinType == 1) {
  536. $maxUsdtRate = ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0);
  537. $withdrawTotal = BalanceLogService::make()->getCountByType($userId, 2, 1, 0);
  538. $maxWithdrawMoney = ($withdrawTotal + $userUsdt);
  539. $maxWithdrawMoney = $maxUsdtRate > 0 && $maxUsdtRate < 100 ? moneyFormat($maxWithdrawMoney * $maxUsdtRate / 100, 2) : $maxWithdrawMoney;
  540. if (($withdrawTotal + floatval($money)) >= $maxWithdrawMoney) {
  541. DB::rollBack();
  542. $this->error = 2026; // 可提金额超出
  543. $this->errorData = ['money' => moneyFormat($maxWithdrawMoney - $withdrawTotal, 2)];
  544. RedisService::clear($cacheKey . '_lock');
  545. return false;
  546. }
  547. // 提现处理
  548. $updateData = ['usdt' => DB::raw("usdt - {$money}"), 'update_time' => time()];
  549. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  550. DB::rollBack();
  551. $this->error = 2033; // 提现处理失败
  552. RedisService::clear($cacheKey . '_lock');
  553. return false;
  554. }
  555. // 账单
  556. $log = [
  557. 'user_id' => $userId,
  558. 'order_no' => get_order_num('SW'),
  559. 'type' => 2,
  560. 'user_type' => 1,
  561. 'coin_type' => 1,
  562. 'money' => $money,
  563. 'actual_money' => $money,
  564. 'fee' => 0,
  565. 'pay_type' => 10,
  566. 'pay_status' => 10,
  567. 'wallet_url' => $info['wallet_url'],
  568. 'pt_wallet_url' => '',
  569. 'date' => date('Y-m-d'),
  570. 'create_time' => time(),
  571. 'audit_remark' => '',
  572. 'status' => 1,
  573. 'mark' => 1,
  574. ];
  575. if (!BalanceLogModel::insertGetId($log)) {
  576. DB::rollBack();
  577. $this->error = 2033;
  578. RedisService::clear($cacheKey . '_lock');
  579. return false;
  580. }
  581. // USDT余额账单
  582. $data = [
  583. 'user_id' => $userId,
  584. 'order_no' => $log['order_no'],
  585. 'type' => 4,
  586. 'user_type' => 1,
  587. 'coin_type' => 1,
  588. 'money' => -$money,
  589. 'before_money' => $userUsdt,
  590. 'create_time' => time(),
  591. 'action_ip' => get_client_ip(),
  592. 'remark' => '余额提现',
  593. 'status' => 1,
  594. 'mark' => 1,
  595. ];
  596. if (!AccountLogModel::insertGetId($data)) {
  597. DB::rollBack();
  598. $this->error = 2033;
  599. RedisService::clear($cacheKey . '_lock');
  600. return false;
  601. }
  602. // 成功
  603. DB::commit();
  604. return $this->getInfo($userId, 3, true);
  605. } // 收益提现
  606. else {
  607. $sbtUsdtFee = ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0);
  608. $sbtPrice = PriceLogService::make()->getSbtPrice();
  609. $sbtFee = moneyFormat(floatval($sbtUsdtFee) / $sbtPrice, 2);
  610. if ($sbtFee > $userSbt) {
  611. DB::rollBack();
  612. $this->error = 2032; // 手续费不足
  613. $this->errorData = ['money' => $sbtFee];
  614. RedisService::clear($cacheKey . '_lock');
  615. return false;
  616. }
  617. // 余额是否足
  618. if ($money > $userProfit) {
  619. DB::rollBack();
  620. $this->error = 2026; // 手续费不足
  621. $this->errorData = ['money' => $userProfit];
  622. RedisService::clear($cacheKey . '_lock');
  623. return false;
  624. }
  625. // 提现处理
  626. $updateData = ['profit' => DB::raw("profit - {$money}"), 'sbt' => DB::raw("sbt - {$sbtFee}"), 'update_time' => time()];
  627. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  628. DB::rollBack();
  629. $this->error = 2033; // 提现处理失败
  630. RedisService::clear($cacheKey . '_lock');
  631. return false;
  632. }
  633. // 账单
  634. $log = [
  635. 'user_id' => $userId,
  636. 'order_no' => get_order_num('SW'),
  637. 'type' => 2,
  638. 'user_type' => 1,
  639. 'coin_type' => 2,
  640. 'money' => $money,
  641. 'actual_money' => $money,
  642. 'fee' => $sbtFee,
  643. 'fee_usdt' => $sbtUsdtFee,
  644. 'pay_type' => 10,
  645. 'pay_status' => 10,
  646. 'wallet_url' => $info['wallet_url'],
  647. 'pt_wallet_url' => '',
  648. 'date' => date('Y-m-d'),
  649. 'create_time' => time(),
  650. 'audit_remark' => '',
  651. 'status' => 1,
  652. 'mark' => 1,
  653. ];
  654. if (!BalanceLogModel::insertGetId($log)) {
  655. DB::rollBack();
  656. $this->error = 2033;
  657. RedisService::clear($cacheKey . '_lock');
  658. return false;
  659. }
  660. // 收益账单
  661. $data = [
  662. 'user_id' => $userId,
  663. 'order_no' => $log['order_no'],
  664. 'type' => 4,
  665. 'user_type' => 1,
  666. 'coin_type' => 3,
  667. 'money' => -$money,
  668. 'before_money' => $userProfit,
  669. 'create_time' => time(),
  670. 'action_ip' => get_client_ip(),
  671. 'remark' => '收益提现',
  672. 'status' => 1,
  673. 'mark' => 1,
  674. ];
  675. if (!AccountLogModel::insertGetId($data)) {
  676. DB::rollBack();
  677. $this->error = 2033;
  678. RedisService::clear($cacheKey . '_lock');
  679. return false;
  680. }
  681. // 手续费账单
  682. if ($sbtFee > 0) {
  683. $data = [
  684. 'user_id' => $userId,
  685. 'order_no' => $log['order_no'],
  686. 'type' => 4,
  687. 'user_type' => 1,
  688. 'coin_type' => 2,
  689. 'money' => -$sbtFee,
  690. 'before_money' => $userSbt,
  691. 'create_time' => time(),
  692. 'action_ip' => get_client_ip(),
  693. 'remark' => '提现手续费',
  694. 'status' => 1,
  695. 'mark' => 1,
  696. ];
  697. if (!AccountLogModel::insertGetId($data)) {
  698. DB::rollBack();
  699. $this->error = 2033;
  700. RedisService::clear($cacheKey . '_lock');
  701. return false;
  702. }
  703. }
  704. // 成功
  705. DB::commit();
  706. RedisService::keyDel("caches:balanceLog:total*");
  707. RedisService::clear($cacheKey . '_lock');
  708. return $this->getInfo($userId, 3, true);
  709. }
  710. } catch (\Exception $exception) {
  711. DB::rollBack();
  712. $this->errorData = ['error' => $exception->getMessage()];
  713. RedisService::clear($cacheKey . '_lock');
  714. $this->error = 2028;
  715. return false;
  716. }
  717. }
  718. /**
  719. * 闪兑
  720. * @param $userId 用户
  721. * @param $params 参数:money-闪兑金额
  722. * @return array|false|mixed
  723. */
  724. public function exchange($userId, $params)
  725. {
  726. $money = isset($params['money']) ? floatval($params['money']) : 0;
  727. $coinType = 2;
  728. if ($money <= 0) {
  729. $this->error = 2101;
  730. return false;
  731. }
  732. $cacheKey = "caches:exchange:{$userId}_{$coinType}";
  733. if (RedisService::get($cacheKey . '_lock')) {
  734. return false;
  735. }
  736. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','usdt','profit','sbt','status'])->first();
  737. if (empty($info)) {
  738. $this->error = 2016;
  739. return false;
  740. }
  741. $status = isset($info['status']) ? $info['status'] : 0;
  742. $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
  743. $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
  744. $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
  745. if ($status != 1) {
  746. $this->error = 2015; // 冻结
  747. return false;
  748. }
  749. // 闪兑验证
  750. $sbtLimit = ConfigService::make()->getConfigByCode('sbt_exchange_limit', 100);
  751. $sbtPrice = PriceLogService::make()->getSbtPrice();
  752. $sbtLimit = round($sbtLimit/$sbtPrice, 2);
  753. $sbtLimit = $sbtLimit>0? $sbtLimit : 0;
  754. if($sbtLimit>0 && $sbtLimit > $userSbt){
  755. $this->errorData = ['money'=> $sbtLimit];
  756. $this->error = lang(2102);
  757. return false;
  758. }
  759. $exchangeSbtMin = ConfigService::make()->getConfigByCode('exchange_sbt_min', 100);
  760. $exchangeSbtMin = $exchangeSbtMin>10? $exchangeSbtMin : 100;
  761. if($money<$exchangeSbtMin){
  762. $this->errorData = ['money'=> $exchangeSbtMin];
  763. $this->error = lang(2106);
  764. return false;
  765. }
  766. // 可提金额或手续费验证
  767. try {
  768. DB::beginTransaction();
  769. RedisService::set($cacheKey . '_lock',date('Y-m-d H:i:s'), rand(3,5));
  770. // TODO SBT 闪兑 USDT
  771. if ($coinType == 2) {
  772. // 手续费
  773. $exchangeFeeRate = ConfigService::make()->getConfigByCode('exchange_fee_rate', 0);
  774. $exchangeFeeRate = $exchangeFeeRate>0 && $exchangeFeeRate<100? floatval($exchangeFeeRate) : 0;
  775. // 闪兑金额
  776. $sbtUsdt = moneyFormat($money * $sbtPrice, 2); // 闪兑USDT金额
  777. $feeUsdt = round($sbtUsdt * $exchangeFeeRate/100, 2);
  778. $feeUsdt = $feeUsdt>0? $feeUsdt : 0.01;
  779. $actualUsdt = moneyFormat($sbtUsdt - $feeUsdt, 2);
  780. // 闪兑入账收益账户处理
  781. $updateData = [
  782. 'profit' => DB::raw("profit + {$actualUsdt}"),
  783. 'sbt' => DB::raw("sbt - {$money}"),
  784. 'update_time' => time()
  785. ];
  786. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  787. DB::rollBack();
  788. $this->error = 2103;
  789. RedisService::clear($cacheKey . '_lock');
  790. return false;
  791. }
  792. // SBT扣除账单
  793. $orderNo = get_order_num('SE');
  794. $data = [
  795. 'user_id' => $userId,
  796. 'order_no' => $orderNo,
  797. 'type' => 2,
  798. 'user_type' => 1,
  799. 'coin_type' => 2,
  800. 'money' => -$money,
  801. 'before_money' => $userSbt,
  802. 'create_time' => time(),
  803. 'action_ip' => get_client_ip(),
  804. 'remark' => 'SBT闪兑',
  805. 'status' => 1,
  806. 'mark' => 1,
  807. ];
  808. if (!AccountLogModel::insertGetId($data)) {
  809. DB::rollBack();
  810. $this->error = 2103;
  811. RedisService::clear($cacheKey . '_lock');
  812. return false;
  813. }
  814. // 到账USDT收益账单
  815. $data = [
  816. 'user_id' => $userId,
  817. 'order_no' => $orderNo,
  818. 'type' => 2,
  819. 'user_type' => 1,
  820. 'coin_type' => 3,
  821. 'money' => $actualUsdt,
  822. 'before_money' => $userProfit,
  823. 'create_time' => time(),
  824. 'action_ip' => get_client_ip(),
  825. 'remark' => 'SBT闪兑到账',
  826. 'status' => 1,
  827. 'mark' => 1,
  828. ];
  829. if (!AccountLogModel::insertGetId($data)) {
  830. DB::rollBack();
  831. $this->error = 2103;
  832. RedisService::clear($cacheKey . '_lock');
  833. return false;
  834. }
  835. // 闪兑手续费账单
  836. $data = [
  837. 'user_id' => $userId,
  838. 'order_no' => $orderNo,
  839. 'type' => 18,
  840. 'user_type' => 1,
  841. 'coin_type' => 3,
  842. 'money' => -$feeUsdt,
  843. 'before_money' => moneyFormat($userProfit + $actualUsdt,2),
  844. 'create_time' => time(),
  845. 'action_ip' => get_client_ip(),
  846. 'remark' => 'SBT闪兑手续费',
  847. 'status' => 1,
  848. 'mark' => 1,
  849. ];
  850. if (!AccountLogModel::insertGetId($data)) {
  851. DB::rollBack();
  852. $this->error = 2103;
  853. RedisService::clear($cacheKey . '_lock');
  854. return false;
  855. }
  856. // 成功
  857. DB::commit();
  858. $this->error = 2105;
  859. return $this->getInfo($userId, 3, true);
  860. }else{
  861. DB::rollBack();
  862. $this->error = 1031;
  863. RedisService::clear($cacheKey . '_lock');
  864. return false;
  865. }
  866. } catch (\Exception $exception) {
  867. DB::rollBack();
  868. $this->errorData = ['error' => $exception->getMessage()];
  869. RedisService::clear($cacheKey . '_lock');
  870. $this->error = 2104;
  871. return false;
  872. }
  873. }
  874. /**
  875. * 更新用户等级
  876. * @param $userId 需要更新等级用户ID
  877. */
  878. public function upgradeUpdate($userId)
  879. {
  880. $cacheKey = "caches:member:levelLock_{$userId}";
  881. if (RedisService::get($cacheKey)) {
  882. $this->error = lang(4303, ['uid' => $userId]);
  883. return false;
  884. }
  885. RedisService::set($cacheKey, date('Y-m-d H:i:s'), rand(5, 10));
  886. $userInfo = $this->model->where(['id' => $userId, 'mark' => 1])
  887. ->select(['id', 'usdt', 'member_level', 'performance','upgrade_status', 'upgrade_at', 'status'])
  888. ->first();
  889. if (empty($userInfo)) {
  890. RedisService::clear($cacheKey);
  891. $this->error = lang(4301, ['uid' => $userId]);
  892. return false;
  893. }
  894. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0; // 个人等级
  895. $performance = isset($userInfo['performance']) ? $userInfo['performance'] : 0; // 个人业绩
  896. $upgradeStatus = isset($userInfo['upgrade_status']) ? $userInfo['upgrade_status'] : 0; // 升级方式
  897. $teamPerformance = TeamService::make()->getTeamPerformanceByType($userId, 2, true);
  898. $teamPerformance = round($teamPerformance + $performance, 2);
  899. // 等级条件
  900. $nextLevel = MemberLevelModel::where('upgrade_usdt', '<=', $teamPerformance)
  901. ->where(['status' => 1, 'mark' => 1])
  902. ->orderBy('sort', 'desc')
  903. ->orderBy('id', 'desc')
  904. ->value('id');
  905. $nextLevel = $nextLevel>0? intval($nextLevel) : 0;
  906. // 是否只升不降
  907. if ($$upgradeStatus==2 && $nextLevel<=$memberLevel) {
  908. RedisService::clear($cacheKey);
  909. $this->error = lang(4302, ['uid' => $userId]);
  910. return false;
  911. }
  912. // 更新等级
  913. 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()])) {
  914. RedisService::clear($cacheKey);
  915. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel]);
  916. return false;
  917. }
  918. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel]);
  919. RedisService::set($cacheKey, ['level' => $nextLevel, 'old' => $memberLevel, 'date' => date('Y-m-d H:i:s')], rand(30, 60));
  920. return ['msg' => '更新成功', 'uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel];
  921. }
  922. /**
  923. * 获取可质押用户列表(按批次数量获取)
  924. * @return mixed
  925. */
  926. public function pledgeUserList()
  927. {
  928. try {
  929. $limit = ConfigService::make()->getConfigByCode('pledge_user_count', 500);
  930. $limit = $limit > 0 ? $limit : 500;
  931. $pledgeUsdt = ConfigService::make()->getConfigByCode('pledge_money', 500);
  932. $pledgeUsdt = $pledgeUsdt > 0 ? $pledgeUsdt : 500;
  933. $sbtPrice = PriceLogService::make()->getSbtPrice();
  934. $sbtUsdtFee = ConfigService::make()->getConfigByCode('pledge_sbt_usdt_fee', 0);
  935. $sbtUsdtFee = $sbtUsdtFee > 0 ? floatval($sbtUsdtFee) : 0;
  936. $sbtFee = $sbtUsdtFee && $sbtPrice > 0 ? moneyFormat($sbtUsdtFee / $sbtPrice, 2) : 0;
  937. $datas = $this->model->from('member as a')
  938. ->leftJoin('pledge_orders as b', 'b.user_id', '=', 'a.id')
  939. ->where('a.usdt', '>=', $pledgeUsdt)
  940. ->where('a.sbt', '>=', $sbtFee)
  941. ->where(function($query){
  942. $query->where('b.id', '<=', 0)->orWhere('a.pledge_count', '<=', 0);
  943. })
  944. ->where(['a.pledge_auto' => 1, 'a.status' => 1, 'a.mark' => 1])
  945. ->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'])
  946. ->limit($limit)
  947. ->orderByRaw('rand()')
  948. ->orderBy('a.id', 'asc')
  949. ->get();
  950. return $datas?$datas->toArray() : [];
  951. } catch (\Exception $exception) {
  952. $this->error = $exception->getMessage();
  953. return false;
  954. }
  955. }
  956. /**
  957. * 获取需要更新等级用户列表(更新等级时间超出当前时间则需要更新)
  958. * @return mixed
  959. */
  960. public function getUpgradeUserList()
  961. {
  962. try {
  963. $limit = ConfigService::make()->getConfigByCode('upgrade_user_count', 500);
  964. $limit = $limit > 0 ? $limit : 500;
  965. $datas = $this->model->where('upgrade_at', '>', date('Y-m-d H:i:s'))
  966. ->where(['status' => 1, 'mark' => 1])
  967. ->select(['id', 'pledge_auto', 'usdt', 'sbt', 'profit', 'trade_status', 'parent_ids'])
  968. ->limit($limit)
  969. ->orderByRaw('rand()')
  970. ->orderBy('id', 'asc')
  971. ->get();
  972. return $datas?$datas->toArray() : [];
  973. } catch (\Exception $exception) {
  974. $this->error = $exception->getMessage();
  975. return false;
  976. }
  977. }
  978. }