MemberService.php 42 KB

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