MemberService.php 42 KB

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