MemberService.php 42 KB

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