MemberService.php 42 KB

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