MemberService.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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\CartsModel;
  16. use App\Models\DrawLogModel;
  17. use App\Models\LiveModel;
  18. use App\Models\MachineModel;
  19. use App\Models\MemberBankModel;
  20. use App\Models\MemberLevelModel;
  21. use App\Models\MemberModel;
  22. use App\Models\MerchantModel;
  23. use App\Models\VideoModel;
  24. use App\Services\BaseService;
  25. use App\Services\CityService;
  26. use App\Services\ConfigService;
  27. use App\Services\EmailService;
  28. use App\Services\RedisService;
  29. use App\Services\SmsService;
  30. use App\Services\ToolService;
  31. use App\Services\UdunpayService;
  32. use App\Services\WalletService;
  33. use Illuminate\Support\Facades\DB;
  34. use phpQrcode\QRcode;
  35. /**
  36. * 会员管理-服务类
  37. * @author laravel开发员
  38. * @since 2020/11/11
  39. * Class MemberService
  40. * @package App\Services\Api
  41. */
  42. class MemberService extends BaseService
  43. {
  44. // 静态对象
  45. protected static $instance = null;
  46. /**
  47. * 构造函数
  48. * @author laravel开发员
  49. * @since 2020/11/11
  50. * MemberService constructor.
  51. */
  52. public function __construct()
  53. {
  54. $this->model = new MemberModel();
  55. }
  56. /**
  57. * 静态入口
  58. * @return MemberService|static|null
  59. */
  60. public static function make()
  61. {
  62. if (!self::$instance) {
  63. self::$instance = new static();
  64. }
  65. return self::$instance;
  66. }
  67. /**
  68. * 获取资料详情
  69. * @param $where
  70. * @param array $field
  71. */
  72. public function getInfo($where, $type = 'detail', array $field = [], $userId=0)
  73. {
  74. $defaultField = ['id', 'username','email', 'realname', 'mobile','gender','member_level','box_num', 'nickname', 'code','supper_point', 'parent_id','birthday','city_id','signature','power_num','upgrade_profit_total','trade_state','trc_url','recharge_trc_url', 'point_id', 'balance','trx','usdt','wait_score','intro', 'score','pay_password','realname','idcard_check', 'member_level', 'status', 'avatar'];
  75. $withs = ['merchant','acceptor','parent','point','level'];
  76. if ($type == 'team') {
  77. $defaultField = ['id', 'username','email','member_level', 'nickname','usdt', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar'];
  78. }else if($type == 'share'){
  79. $withs = ['parent','level'];
  80. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar'];
  81. }else if($type == 'check'){
  82. $withs = ['parent','level'];
  83. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar'];
  84. }else if ($type == 'info'){
  85. $withs = ['parent','level'];
  86. }
  87. $field = $field ? $field : $defaultField;
  88. if (is_array($where)) {
  89. $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first();
  90. } else {
  91. $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first();
  92. }
  93. $info = $info ? $info->toArray() : [];
  94. if ($info && !in_array($type, ['auth', 'check','login'])) {
  95. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  96. $info['balance'] = moneyFormat($info['balance'], 2);
  97. $info['usdt'] = isset($info['usdt'])?moneyFormat($info['usdt'], 2):'0.00';
  98. $info['score'] = moneyFormat($info['score'], 2);
  99. $info['merchant'] = isset($info['merchant']) && $info['merchant']? $info['merchant'] : ['id'=>0];
  100. $info['acceptor'] = isset($info['acceptor']) && $info['acceptor']? $info['acceptor'] : ['id'=>0];
  101. $info['level'] = isset($info['level']) && $info['level']? $info['level'] : ['id'=>0,'name'=>'普通用户'];
  102. $info['custom_phone'] = ConfigService::make()->getConfigByCode('custom_phone');
  103. $info['custom_telegram'] = ConfigService::make()->getConfigByCode('custom_telegram');
  104. $info['custom_email'] = ConfigService::make()->getConfigByCode('custom_email');
  105. if(isset($info['birthday'])){
  106. $info['birthday_text'] = $info['birthday']? date('Y-m-d',$info['birthday']) : '';
  107. }
  108. // 二维码
  109. if (in_array($type, ['detail'])) {
  110. $info['parent_code'] = '';
  111. $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无'];
  112. if($info['parent']['id']>0){
  113. $info['parent_code'] = isset($info['parent']['code'])? $info['parent']['code'] :'';
  114. }
  115. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  116. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  117. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  118. if($userId != $info['id']){
  119. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  120. }else{
  121. $info['is_follow'] = 1;
  122. }
  123. $info['app_version'] = ConfigService::make()->getConfigByCode('app_version');
  124. }
  125. else if ($type == 'info') {
  126. $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0);
  127. $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0;
  128. $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0;
  129. }else if($type == 'buy'){
  130. $address = MemberAddressService::make()->getBindInfo($userId);
  131. $info['address'] = $address;
  132. $streetCode = isset($address['street_code'])? $address['street_code'] : '';
  133. $info['freight_address_id'] = $streetCode? $streetCode : (isset($address['district_code'])? $address['district_code'] : '');
  134. $info['address_id'] = isset($address['id'])? $address['id'] : 0;
  135. $info['cart_num'] = GoodsService::make()->getCartCount($info['id']);
  136. }else if($type == 'upgrade'){
  137. $level = isset($info['level'])? $info['level'] : [];
  138. $nextLevel = MemberLevelModel::where('id','>', $info['member_level'])->orderBy('id','asc')->first();
  139. $info['next_level'] = isset($nextLevel['id']) && $nextLevel['id']? $nextLevel['id'] : $info['member_level'];
  140. $info['next_level_profit'] = isset($nextLevel['upgrade_usdt_profit']) && $nextLevel['upgrade_usdt_profit']? $nextLevel['upgrade_usdt_profit'] : (isset($level['upgrade_usdt_profit'])? $level['upgrade_usdt_profit']:0);
  141. $info['next_level_usdt'] = isset($nextLevel['upgrade_usdt']) && $nextLevel['upgrade_usdt']? $nextLevel['upgrade_usdt'] : (isset($level['upgrade_usdt'])? $level['upgrade_usdt']:0);
  142. $info['next_level_name'] = isset($nextLevel['name'])? $nextLevel['name'] : (isset($level['name'])? $level['name']:'');
  143. }
  144. else if ($type == 'recharge') {
  145. $wallet = WalletService::make()->getWallet(1);
  146. $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : '';
  147. $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100);
  148. if($info['recharge_trc_url']){
  149. $qrcode = $this->makeQrcode($info['recharge_trc_url']);
  150. $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  151. }else{
  152. $info['trc_qrcode'] = '';
  153. }
  154. }
  155. else if ($type == 'team' || $type == 'share') {
  156. $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']);
  157. $qrcode = $this->makeQrcode($inviteUrl);
  158. $info['qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  159. $info['invite_url'] = $inviteUrl;
  160. $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):'';
  161. $info['qrcode_header'] = get_image_url('/images/qrcode/qrcode-header.png');
  162. $info['qrcode_header_base64'] = getImageContent('/images/qrcode/qrcode-header.png');
  163. $info['qrcode_bg'] = get_image_url('/images/qrcode/qrcode-bg.png');
  164. $info['qrcode_bg_base64'] = getImageContent('/images/qrcode/qrcode-bg.png');
  165. $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数
  166. $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数
  167. $info['team_count'] = $this->getUserCountByType($info['id'], 2, 0); // 团队人数
  168. }else {
  169. // 默认地址
  170. $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']);
  171. }
  172. }
  173. return $info;
  174. }
  175. /**
  176. * 获取主页信息
  177. * @param $where
  178. * @param array $field
  179. */
  180. public function getHomeInfo($id, $userId=0)
  181. {
  182. $field = ['id', 'username','email', 'realname', 'mobile','gender', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state', 'point_id', 'balance','trx','usdt','wait_score', 'score','realname', 'member_level', 'status', 'avatar'];
  183. $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first();
  184. $info = $info ? $info->toArray() : [];
  185. if ($info) {
  186. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  187. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  188. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  189. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  190. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  191. $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝
  192. $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播
  193. }
  194. return $info;
  195. }
  196. /**
  197. * 获取用户缓存信息
  198. * @param $where
  199. * @param array $field
  200. * @param int $expired
  201. * @return array|mixed
  202. */
  203. public function getCacheInfo($where, $field = [], $expired = 0)
  204. {
  205. $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired);
  206. $info = RedisService::get($cacheKey);
  207. if ($info) {
  208. return $info;
  209. }
  210. $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar'];
  211. $field = $field ? $field : $defaultField;
  212. $info = $this->model->where($where)->where('mark', 1)->select($field)->first();
  213. $info = $info ? $info->toArray() : [];
  214. if ($info) {
  215. if (isset($info['avatar'])) {
  216. $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png';
  217. $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : '';
  218. }
  219. RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5));
  220. }
  221. return $info;
  222. }
  223. /**
  224. * 生成普通参数二维码
  225. * @param $str 参数
  226. * @param bool $refresh 是否重新生成
  227. * @return bool
  228. */
  229. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  230. {
  231. $basePath = base_path() . '/public';
  232. $qrFile = '/images/qrcode/';
  233. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  234. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  235. }
  236. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  237. $qrFile = $qrFile . "C_{$key}.png";
  238. $cacheKey = "caches:qrcodes:member_" . $key;
  239. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  240. return $qrFile;
  241. }
  242. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  243. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  244. return false;
  245. }
  246. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  247. return $qrFile;
  248. }
  249. /**
  250. * 获取团队用户数量
  251. * @param $userId 当前用户ID
  252. * @param int $type 层级:1-直推,2-团队
  253. * @param int $isPoint 节点:1-滑落推荐,0-直接推荐
  254. * @return array|mixed
  255. */
  256. public function getUserCountByType($userId, $type = 1, $isPoint=0)
  257. {
  258. $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}";
  259. $data = RedisService::get($cacheKey);
  260. if ($data) {
  261. return $data;
  262. }
  263. $where = ['status' => 1, 'mark' => 1];
  264. $data = $this->model->where($where)
  265. ->where(function ($query) use ($type, $isPoint, $userId) {
  266. if($isPoint){
  267. if ($type == 1) { // 滑落推荐
  268. $query->where('point_id', $userId);
  269. } else if($type == 2){ // 滑落团队人数
  270. $query->whereRaw('FIND_IN_SET(?,points)', $userId);
  271. }
  272. }else{
  273. if ($type == 1) { // 直推人数
  274. $query->where('parent_id', $userId);
  275. } else if($type == 2){ // 团队人数
  276. $query->whereRaw("FIND_IN_SET({$userId},parents)");
  277. } else if($type == 3){ // 滑落人数
  278. $query->where('parent_id', $userId)->where('point_id','!=', $userId);
  279. }
  280. }
  281. })->count('id');
  282. if ($data) {
  283. RedisService::set($cacheKey, $data, rand(3, 5));
  284. }
  285. return $data;
  286. }
  287. /**
  288. * 分销用户列表
  289. * @param $userId
  290. * @param $params
  291. * @param int $pageSize
  292. * @return array
  293. */
  294. public function getTeamList($userId, $params, $pageSize=15)
  295. {
  296. $page = request()->post('page',1);
  297. $cacheKey = "caches:teams:list_{$userId}_{$page}";
  298. $datas = RedisService::get($cacheKey);
  299. if ($datas) {
  300. return [
  301. 'pageSize' => $pageSize,
  302. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  303. 'list' => isset($datas['data']) ? $datas['data'] : []
  304. ];
  305. }
  306. $where = ['status' => 1, 'mark' => 1];
  307. $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status'];
  308. $datas = $this->model->with(['level'])->where($where)
  309. ->where(function ($query) use ($userId) {
  310. $query->where('parent_id', $userId);
  311. })
  312. ->where(function($query) use($params){
  313. $kw = isset($params['kw'])? trim($params['kw']) : '';
  314. if($kw){
  315. $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%");
  316. }
  317. })
  318. ->select($field)
  319. ->orderBy('create_time', 'desc')
  320. ->orderBy('id', 'desc')
  321. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  322. $datas = $datas ? $datas->toArray() : [];
  323. if ($datas) {
  324. foreach ($datas['data'] as &$item) {
  325. $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
  326. $item['avatar'] = get_image_url($item['avatar']);
  327. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : '';
  328. $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0;
  329. }
  330. unset($item);
  331. RedisService::set($cacheKey, $datas, rand(5, 10));
  332. }
  333. return [
  334. 'pageSize' => $pageSize,
  335. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  336. 'list' => isset($datas['data']) ? $datas['data'] : []
  337. ];
  338. }
  339. /**
  340. * 手机号是否已注册
  341. * @param $mobile
  342. * @return mixed
  343. */
  344. public function checkPhoneExists($mobile)
  345. {
  346. return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub
  347. }
  348. /**
  349. * 账号注册
  350. * @param $params
  351. * @return array|false
  352. */
  353. public function register($params)
  354. {
  355. // 授权
  356. $email = isset($params['email']) ? trim($params['email']) : '';
  357. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  358. $registerType = isset($params['type']) ? intval($params['type']) : 1;
  359. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  360. $code = isset($params['code']) ? trim($params['code']) : '';
  361. $scene = isset($params['scene']) ? $params['scene'] : '';
  362. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  363. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  364. if (empty($params) || $code <= 0 || !in_array($registerType,[1,2])) {
  365. $this->error = 2014;
  366. return false;
  367. }
  368. // 邮箱注册
  369. if($registerType == 1){
  370. if(empty($email)){
  371. $this->error = 2014;
  372. return false;
  373. }
  374. // 验证码
  375. if (!EmailService::make()->check($email, $code, $scene)) {
  376. $this->error = EmailService::make()->getError();
  377. return false;
  378. }
  379. // 验证是否注册
  380. if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){
  381. $this->error = 2009;
  382. return false;
  383. }
  384. }else if($registerType == 2){
  385. if(empty($mobile)){
  386. $this->error = 2014;
  387. return false;
  388. }
  389. // 验证码
  390. if (!SmsService::make()->check($mobile, $code, $scene)) {
  391. $this->error = SmsService::make()->getError();
  392. return false;
  393. }
  394. // 验证是否注册
  395. if($this->model->where(['mobile'=> $mobile,'mark'=>1])->value('id')){
  396. $this->error = 1058;
  397. return false;
  398. }
  399. }
  400. // 推荐人
  401. $parentId = 0;
  402. $pointId = 0;
  403. $parents = '';
  404. $points = '';
  405. if ($inviteCode) {
  406. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  407. ->select(['id', 'parents', 'parent_id'])
  408. ->first();
  409. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  410. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  411. // 挂靠节点
  412. if($parentId>0){
  413. $pointId = $this->getPointParentId($parentId);
  414. if($pointId){
  415. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  416. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  417. }
  418. }
  419. }
  420. // 注册
  421. $id = $this->model->max('id') + 1;
  422. $system = isset($params['system'])? $params['system'] : [];
  423. $ip = get_client_ip();
  424. $ipData = ToolService::make()->getIpAddress($ip,'');
  425. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  426. $city = isset($ipData['city'])? $ipData['city'] : '';
  427. $emailName = explode('@', $email)[0];
  428. $password = isset($params['password']) ? $params['password'] : 'xl123456';
  429. // 钱包
  430. $data = [
  431. 'parent_id' => $parentId,
  432. 'point_id' => $pointId,
  433. 'points' => $points,
  434. 'openid' => '',
  435. 'avatar' => '',
  436. 'nickname' => $nickname ? $nickname : 'XL'.substr($emailName?$emailName:substr($mobile,-8,8),-8,8),
  437. 'username' => $registerType==1? $email : $mobile,
  438. 'password' => get_password($password),
  439. 'code' => strtoupper(get_random_code(9, 'X', "{$id}")),
  440. 'email' => $email,
  441. 'mobile' => $mobile,
  442. 'recharge_trc_url' => '',
  443. 'parents' => $parents,
  444. 'province_id' => CityService::make()->getFieldByName($province),
  445. 'city_id' => CityService::make()->getFieldByName($city),
  446. 'city' => $city,
  447. 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '',
  448. 'device' => $appSources == 'android' ? 2 : 1,
  449. 'status' => 1,
  450. 'balance' => 0,
  451. 'score' => 0,
  452. 'mark' => 1,
  453. 'login_ip' => $ip,
  454. 'create_time' => time(),
  455. ];
  456. $userId = $this->model->insertGetId($data);
  457. $this->error = 2008;
  458. return [
  459. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  460. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']],
  461. ];
  462. }
  463. /**
  464. * 邮箱登录
  465. * @param $params
  466. * @return array|false
  467. */
  468. public function loginByEmail($params)
  469. {
  470. // 授权
  471. $email = isset($params['email']) ? $params['email'] : '';
  472. $code = isset($params['code']) ? $params['code'] : '';
  473. $scene = isset($params['scene']) ? $params['scene'] : '';
  474. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  475. $password = isset($params['password']) ? $params['password'] : '';
  476. if (empty($params) || empty($email) || empty($scene) ) {
  477. $this->error = 2014;
  478. return false;
  479. }
  480. // 验证是否注册,没有则注册
  481. $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status'])->first();
  482. $data = $data ? $data->toArray() : [];
  483. if(!empty($data)){
  484. $this->error = 1003;
  485. return $data;
  486. }
  487. if(!empty($password)){
  488. if(get_password($password) != $data['password']){
  489. $this->error = 3108;
  490. return false;
  491. }
  492. }else{
  493. // 验证码
  494. if (!EmailService::make()->check($email, $code, $scene)) {
  495. $this->error = EmailService::make()->getError();
  496. return false;
  497. }
  498. }
  499. $userId = isset($data['id']) ? $data['id'] : 0;
  500. $status = isset($data['status']) ? $data['status'] : 0;
  501. if(empty($data) || $userId<=0){
  502. $this->error = 2001;
  503. return false;
  504. }
  505. if ($status != 1) {
  506. $this->error = 2015;
  507. return false;
  508. }
  509. // 获取登录授权token
  510. $jwt = new Jwt('jwt_dys_app');
  511. $token = $jwt->getToken($userId);
  512. // 结果返回
  513. $result = [
  514. 'access_token' => $token,
  515. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  516. ];
  517. // 用户信息
  518. $ip = get_client_ip();
  519. $updateData = [
  520. 'login_time' => time(),
  521. 'login_ip' => $ip,
  522. ];
  523. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  524. $ipData = ToolService::make()->getIpAddress($ip,'');
  525. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  526. $city = isset($ipData['city'])? $ipData['city'] : '';
  527. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  528. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  529. }
  530. $this->model->where(['id'=> $userId])->update($updateData);
  531. $this->error = 2004;
  532. $data['token'] = $token;
  533. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  534. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  535. return $result;
  536. }
  537. /**
  538. * 手机号登录
  539. * @param $params
  540. * @return array|false
  541. */
  542. public function loginByMobile($params)
  543. {
  544. // 授权
  545. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  546. $code = isset($params['code']) ? $params['code'] : '';
  547. $scene = isset($params['scene']) ? $params['scene'] : '';
  548. $password = isset($params['password']) ? $params['password'] : '';
  549. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  550. if (empty($params) || empty($mobile) || empty($scene) ) {
  551. $this->error = 2014;
  552. return false;
  553. }
  554. // 验证是否注册,没有则注册
  555. $data = $this->model->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'username','point_id','mobile', 'parent_id', 'code', 'status'])->first();
  556. $data = $data ? $data->toArray() : [];
  557. if(!empty($password)){
  558. if(get_password($password) != $data['password']){
  559. $this->error = 3108;
  560. return false;
  561. }
  562. }else{
  563. // 验证码
  564. if (!SmsService::make()->check($mobile, $code, $scene)) {
  565. $this->error = SmsService::make()->getError();
  566. return false;
  567. }
  568. }
  569. $userId = isset($data['id']) ? $data['id'] : 0;
  570. $status = isset($data['status']) ? $data['status'] : 0;
  571. if(empty($data) || $userId<=0){
  572. $this->error = 2001;
  573. return false;
  574. }
  575. if ($status != 1) {
  576. $this->error = 2015;
  577. return false;
  578. }
  579. // 获取登录授权token
  580. $jwt = new Jwt('jwt_dys_app');
  581. $token = $jwt->getToken($userId);
  582. // 结果返回
  583. $result = [
  584. 'access_token' => $token,
  585. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  586. ];
  587. // 用户信息
  588. $ip = get_client_ip();
  589. $updateData = [
  590. 'login_time' => time(),
  591. 'login_ip' => $ip,
  592. ];
  593. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  594. $ipData = ToolService::make()->getIpAddress($ip,'');
  595. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  596. $city = isset($ipData['city'])? $ipData['city'] : '';
  597. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  598. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  599. }
  600. $this->model->where(['id'=> $userId])->update($updateData);
  601. $this->error = 2004;
  602. $data['token'] = $token;
  603. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  604. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  605. return $result;
  606. }
  607. /**
  608. * 修改头像/商家logo/技师头像
  609. * @param $userId
  610. * @param $avatar
  611. * @return mixed
  612. */
  613. public function saveAvatar($userId, $avatar)
  614. {
  615. $type = request()->post('type', 1);
  616. if($type == 1){
  617. $oldAvatar = $this->model->where(['id' => $userId])->value('avatar');
  618. if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  619. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  620. @unlink(ATTACHMENT_PATH . $oldAvatar);
  621. }
  622. return true;
  623. }
  624. }else if($type == 2){
  625. $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo');
  626. if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) {
  627. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  628. @unlink(ATTACHMENT_PATH . $oldAvatar);
  629. }
  630. return true;
  631. }
  632. }
  633. return false;
  634. }
  635. /**
  636. * 修改账号
  637. * @param $userId
  638. * @param $params
  639. * @return bool
  640. */
  641. public function modify($userId, $params)
  642. {
  643. $email = isset($params['email']) ? $params['email'] : '';
  644. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  645. $password = isset($params['password']) ? $params['password'] : '';
  646. $payPassword = isset($params['pay_password']) ? $params['pay_password'] : '';
  647. $type = isset($params['type'])? trim($params['type']) : '';
  648. $scene = isset($params['scene'])? trim($params['scene']) : '';
  649. if($type != 'profile' && empty($email) && empty($mobile)){
  650. $this->error = 1064;
  651. return false;
  652. }
  653. // 用户验证
  654. $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
  655. if (!$info) {
  656. $this->error = 2001;
  657. return false;
  658. }
  659. // 使用状态校验
  660. if ($info['status'] != 1) {
  661. $this->error = 2009;
  662. return false;
  663. }
  664. // 密码校验
  665. $data = ['update_time' => time()];
  666. // 验证交易密码
  667. if(isset($params['pay_password']) && $scene != 'trade'){
  668. $userPayPassword = isset($info['pay_password'])? $info['pay_password'] : '';
  669. if(empty($userPayPassword)){
  670. $this->error = 1040;
  671. return false;
  672. }
  673. if($userPayPassword != get_password($payPassword)){
  674. $this->error = 2038;
  675. return false;
  676. }
  677. }
  678. // 邀请人绑定
  679. $parent = isset($info['parent'])? $info['parent'] : [];
  680. $userParentCode = isset($parent['code'])? $parent['code'] : '';
  681. $userCode = isset($info['code'])? $info['code'] : '';
  682. $parentCode = isset($params['parent_code'])? trim($params['parent_code']) : '';
  683. if(isset($params['parent_code']) && $parentCode){
  684. //
  685. if($userParentCode){
  686. $this->error = 2451;
  687. return false;
  688. }
  689. if(($userCode == $parentCode)){
  690. $this->error = 2452;
  691. return false;
  692. }
  693. // 推荐人验证
  694. $inviteInfo = $this->model->where(['code' => $parentCode, 'mark' => 1])
  695. ->select(['id', 'parents', 'parent_id','trc_url'])
  696. ->first();
  697. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  698. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  699. if(!$parentId){
  700. $this->error = 2453;
  701. return false;
  702. }
  703. // 验证是否绑定用户为自己线下用户
  704. if(preg_match("/{$userId},/", $parents)){
  705. $this->error = 2454;
  706. return false;
  707. }
  708. // 推荐人
  709. $data['parent_id'] = $parentId;
  710. $data['parents'] = $parents;
  711. // 挂靠节点
  712. if($parentId>0){
  713. $pointId = $this->getPointParentId($parentId);
  714. if($pointId){
  715. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  716. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  717. $data['point_id'] = $pointId;
  718. $data['points'] = $points;
  719. }
  720. }
  721. }
  722. // 邮箱验证
  723. if (isset($params['email']) && $email) {
  724. // 修改邮箱
  725. $newEmail = isset($params['new_email'])? trim($params['new_email']) : '';
  726. if(isset($params['new_email']) && $newEmail){
  727. $data['email'] = $newEmail;
  728. $data['username'] = $newEmail;
  729. $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first();
  730. if ($checkInfo && $checkInfo['id'] != $userId) {
  731. $this->error = 2005;
  732. return false;
  733. }
  734. }
  735. // 邮箱验证码
  736. $code = isset($params['code'])? trim($params['code']) : '';
  737. $checkEmail = $scene == 'modify_email'? $newEmail : $email;
  738. if (!EmailService::make()->check($checkEmail, $code, $scene)) {
  739. $this->error = EmailService::make()->getError();
  740. return false;
  741. }
  742. }
  743. // 手机号验证
  744. if (isset($params['mobile']) && $mobile) {
  745. // 修改手机号
  746. $newMobile = isset($params['new_mobile'])? trim($params['new_mobile']) : '';
  747. if(isset($params['new_mobile']) && $newMobile){
  748. $data['mobile'] = $newMobile;
  749. $data['username'] = $newMobile;
  750. $checkInfo = $this->model->where(['mobile' => $newMobile, 'mark' => 1])->select(['id', 'status'])->first();
  751. if ($checkInfo && $checkInfo['id'] != $userId) {
  752. $this->error = 2005;
  753. return false;
  754. }
  755. }
  756. // 手机验证码
  757. $code = isset($params['code'])? trim($params['code']) : '';
  758. $checkMobile = $scene == 'modify_mobile'? $newMobile : $mobile;
  759. if (!SmsService::make()->check($checkMobile, $code, $scene)) {
  760. $this->error = SmsService::make()->getError();
  761. return false;
  762. }
  763. }
  764. $trcUrl = isset($params['trc_url'])? trim($params['trc_url']) : '';
  765. $userTrcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  766. if(isset($params['trc_url']) && $trcUrl){
  767. if($trcUrl != $userTrcUrl){
  768. if($this->model->where(['trc_url'=> $trcUrl,'mark'=>1])->whereNotIn('id',[$userId])->value('id')){
  769. $this->error = 1048;
  770. return false;
  771. }
  772. if(!WalletService::make()->checkAddress($trcUrl)){
  773. $this->error = 1049;
  774. return false;
  775. }
  776. $data['trc_url'] = $trcUrl;
  777. }
  778. }
  779. // 修改数据
  780. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  781. if (isset($params['nickname']) && $nickname) {
  782. $data['nickname'] = $nickname;
  783. }
  784. $gender = isset($params['gender']) ? intval($params['gender']) : 3;
  785. if (isset($params['gender']) && $gender) {
  786. $data['gender'] = $gender;
  787. }
  788. $intro = isset($params['intro']) ? $params['intro'] : '';
  789. if (isset($params['intro']) && $intro) {
  790. $data['intro'] = $intro;
  791. }
  792. $birthday = isset($params['birthday_text']) ? $params['birthday_text'] : '';
  793. if (isset($params['birthday_text']) && $birthday) {
  794. $data['birthday'] = strtotime($birthday);
  795. }
  796. if (isset($params['pay_password']) && $payPassword) {
  797. $payPassword = get_password($payPassword);
  798. $data['pay_password'] = $payPassword;
  799. }
  800. if($this->model->where(['id' => $userId])->update($data)){
  801. // 更新绑定上级后,团队用户全部更新
  802. if(isset($data['parent_id']) && $data['parent_id']){
  803. $updateData = ['parents'=>DB::raw("concat(parents,'{$data['parent_id']},')"),'update_time'=>time()];
  804. $this->model->where('parents','like',"%{$userId},")->update($updateData);
  805. }
  806. // 更新团队节点关系
  807. if(isset($data['point_id']) && $data['point_id']){
  808. $updateData = ['points'=>DB::raw("concat(points,'{$data['point_id']},')"),'update_time'=>time()];
  809. $this->model->where('points','like',"%{$userId},")->update($updateData);
  810. }
  811. $this->error = 1008;
  812. return true;
  813. }
  814. $this->error = 1008;
  815. return true;
  816. }
  817. /**
  818. * 身份认证
  819. * @param $userId
  820. * @param $params
  821. * @return bool
  822. */
  823. public function auth($userId, $params)
  824. {
  825. // 用户验证
  826. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first();
  827. if (!$info) {
  828. $this->error = 2001;
  829. return false;
  830. }
  831. // 使用状态校验
  832. if ($info['status'] != 1) {
  833. $this->error = 2009;
  834. return false;
  835. }
  836. // 密码校验
  837. $data = ['update_time' => time(),'idcard_check'=>1];
  838. if (isset($params['realname']) && $params['realname']) {
  839. $data['realname'] = trim($params['realname']);
  840. }
  841. $idcard = isset($params['idcard']) && $params['idcard'];
  842. if ($idcard) {
  843. $data['idcard'] = trim($params['idcard']);
  844. }
  845. if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) {
  846. $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']);
  847. }
  848. if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) {
  849. $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']);
  850. }
  851. $this->model->where(['id' => $userId])->update($data);
  852. // 发送消息
  853. $this->error = 2036;
  854. return true;
  855. }
  856. /**
  857. * 转账
  858. * @param $userId
  859. * @param $params
  860. * @return bool
  861. */
  862. public function transfer($userId, $params)
  863. {
  864. $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0;
  865. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  866. $money = isset($params['money'])? floatval($params['money']) : 0;
  867. if(empty($toUserId) || $money<=0){
  868. $this->error = 2420;
  869. return false;
  870. }
  871. $cacheKey = "caches:members:transfer:{$userId}";
  872. if(RedisService::get($cacheKey)){
  873. $this->error = 1034;
  874. return false;
  875. }
  876. // 验证账户
  877. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  878. ->select(['id','nickname','username','usdt','pay_password','balance','status'])
  879. ->first();
  880. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  881. $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  882. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  883. $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : '';
  884. if(empty($userInfo) || $status != 1){
  885. $this->error = 2024;
  886. return false;
  887. }
  888. // 余额支付支付密码验证
  889. if(empty($userPayPassword)){
  890. $this->error = 1040;
  891. return false;
  892. }
  893. $payPassword = get_password($payPassword);
  894. if($payPassword != $userPayPassword){
  895. $this->error = 2038;
  896. return false;
  897. }
  898. // 验证账户
  899. $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1])
  900. ->select(['id','nickname','usdt','username','balance','status'])
  901. ->first();
  902. $status = isset($accountInfo['status'])? $accountInfo['status'] : 0;
  903. $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0;
  904. $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : '';
  905. if(empty($accountInfo) || $status != 1){
  906. $this->error = 2421;
  907. return false;
  908. }
  909. if($money > $usdt){
  910. $this->error = 2422;
  911. return false;
  912. }
  913. // 用户余额转账到用户
  914. DB::beginTransaction();
  915. RedisService::set($cacheKey, $params, rand(2,5));
  916. $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()];
  917. if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){
  918. DB::rollBack();
  919. $this->error = 2028;
  920. RedisService::clear($cacheKey);
  921. return false;
  922. }
  923. // 明细
  924. $orderNo = get_order_num('TR');
  925. $log = [
  926. 'user_id' => $userId,
  927. 'source_id' => $toUserId,
  928. 'source_order_no' => $orderNo,
  929. 'type' => 6,
  930. 'coin_type' => 1,
  931. 'user_type'=> 1,
  932. 'money' => -$money,
  933. 'actual_money' => -$money,
  934. 'balance' => $usdt,
  935. 'create_time' => time(),
  936. 'update_time' => time(),
  937. 'remark' => "USDT转账",
  938. 'status' => 1,
  939. 'mark' => 1,
  940. ];
  941. if(!AccountLogModel::insertGetId($log)){
  942. DB::rollBack();
  943. $this->error = 2423;
  944. RedisService::clear($cacheKey);
  945. return false;
  946. }
  947. // 到账
  948. $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5);
  949. $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0;
  950. $feeUsdt = round($money * $fee,2);
  951. $realUsdt = moneyFormat($money - $feeUsdt,2);
  952. $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()];
  953. if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){
  954. DB::rollBack();
  955. $this->error = 2424;
  956. RedisService::clear($cacheKey);
  957. return false;
  958. }
  959. // 明细
  960. $log = [
  961. 'user_id' => $toUserId,
  962. 'source_id' => $userId,
  963. 'source_order_no' => $orderNo,
  964. 'type' => 6,
  965. 'coin_type' => 1,
  966. 'user_type'=> 1,
  967. 'money' => $realUsdt,
  968. 'actual_money' => $realUsdt,
  969. 'balance' => $accountUsdt,
  970. 'create_time' => time(),
  971. 'update_time' => time(),
  972. 'remark' => "USDT转账",
  973. 'status' => 1,
  974. 'mark' => 1,
  975. ];
  976. if(!AccountLogModel::insertGetId($log)){
  977. DB::rollBack();
  978. $this->error = 2029;
  979. RedisService::clear($cacheKey);
  980. return false;
  981. }
  982. // 平台明细
  983. $log = [
  984. 'user_id' => 0,
  985. 'source_id' => $userId,
  986. 'source_order_no' => $orderNo,
  987. 'type' => 6,
  988. 'coin_type' => 1,
  989. 'user_type'=> 4,
  990. 'money' => $feeUsdt,
  991. 'actual_money' => $feeUsdt,
  992. 'balance' => 0,
  993. 'create_time' => time(),
  994. 'update_time' => time(),
  995. 'remark' => "USDT转账",
  996. 'status' => 1,
  997. 'mark' => 1,
  998. ];
  999. if(!AccountLogModel::insertGetId($log)){
  1000. DB::rollBack();
  1001. $this->error = 2029;
  1002. RedisService::clear($cacheKey);
  1003. return false;
  1004. }
  1005. // 平台
  1006. FinanceService::make()->saveLog(0, $feeUsdt,1);
  1007. // 消息
  1008. $dateTime = date('Y-m-d H:i:s');
  1009. MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3);
  1010. $dateTime = date('Y-m-d H:i:s');
  1011. MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3);
  1012. DB::commit();
  1013. RedisService::clear($cacheKey);
  1014. $this->error = 2425;
  1015. return true;
  1016. }
  1017. /**
  1018. * 余额充值
  1019. * @param $userId
  1020. * @param $params
  1021. * @return array|false
  1022. */
  1023. public function recharge($userId, $params)
  1024. {
  1025. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1026. $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0;
  1027. $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
  1028. $payType = 10;
  1029. if($usdt<=0){
  1030. $this->error = 2031;
  1031. return false;
  1032. }
  1033. $cacheKey = "caches:member:recharge:lock_{$userId}";
  1034. if(RedisService::get($cacheKey)){
  1035. $this->error = 1034;
  1036. return false;
  1037. }
  1038. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  1039. ->select(['id','nickname','usdt','pay_password','balance','status'])
  1040. ->first();
  1041. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1042. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  1043. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1044. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1045. if(empty($userInfo) || $status != 1){
  1046. $this->error = 2024;
  1047. return false;
  1048. }
  1049. if($userPayPassword != get_password($payPassword)){
  1050. $this->error = 2038;
  1051. return false;
  1052. }
  1053. // 充值订单
  1054. $orderNo = get_order_num('DR');
  1055. $money = $usdt;
  1056. // 星豆
  1057. DB::beginTransaction();
  1058. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1059. if($coinType == 2){
  1060. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  1061. $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100;
  1062. $money = round($xdPrice * $usdt,2);
  1063. if($usdt > $userUsdt){
  1064. $this->error = 2035;
  1065. RedisService::clear($cacheKey);
  1066. return false;
  1067. }
  1068. // 扣除usdt余额
  1069. $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()];
  1070. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  1071. RedisService::clear($cacheKey);
  1072. $this->error = 2036;
  1073. DB::rollBack();
  1074. return false;
  1075. }
  1076. }
  1077. $data = [
  1078. 'order_no'=> $orderNo,
  1079. 'user_id'=> $userId,
  1080. 'type'=> 1,
  1081. 'user_type'=> 1,
  1082. 'coin_type'=> 2,
  1083. 'money'=> $usdt,
  1084. 'actual_money'=> $money,
  1085. 'pay_type'=> $payType,
  1086. 'pay_status'=> 20,
  1087. 'pay_at'=> date('Y-m-d H:i:s'),
  1088. 'create_time'=> time(),
  1089. 'update_time'=> time(),
  1090. 'status'=> 2,
  1091. 'mark'=> 1,
  1092. ];
  1093. if(!$orderId = BalanceLogModel::insertGetId($data)){
  1094. RedisService::clear($cacheKey);
  1095. $this->error = 2033;
  1096. DB::rollBack();
  1097. return false;
  1098. }
  1099. // 扣除USDT
  1100. $log = [
  1101. 'user_id'=> $userId,
  1102. 'source_order_no'=> $data['order_no'],
  1103. 'user_type'=> 1,
  1104. 'type'=> 5,
  1105. 'coin_type'=> 1,
  1106. 'money'=> -$usdt,
  1107. 'actual_money'=> -$usdt,
  1108. 'balance'=> $userUsdt,
  1109. 'date'=> date('Y-m-d'),
  1110. 'create_time'=> time(),
  1111. 'remark'=> '星豆余额充值扣除',
  1112. 'status'=>1,
  1113. 'mark'=>1
  1114. ];
  1115. if(!AccountLogModel::insertGetId($log)){
  1116. RedisService::clear($cacheKey);
  1117. $this->error = 2029;
  1118. DB::rollBack();
  1119. return false;
  1120. }
  1121. // 增加星豆余额
  1122. $log = [
  1123. 'user_id'=> $userId,
  1124. 'source_order_no'=> $data['order_no'],
  1125. 'user_type'=> 1,
  1126. 'type'=> 5,
  1127. 'coin_type'=> 2,
  1128. 'money'=> $usdt,
  1129. 'actual_money'=> $money,
  1130. 'balance'=> $balance,
  1131. 'date'=> date('Y-m-d'),
  1132. 'create_time'=> time(),
  1133. 'remark'=> '星豆余额充值',
  1134. 'status'=>1,
  1135. 'mark'=>1
  1136. ];
  1137. if(!AccountLogModel::insertGetId($log)){
  1138. RedisService::clear($cacheKey);
  1139. $this->error = 2029;
  1140. DB::rollBack();
  1141. return false;
  1142. }
  1143. // 消息
  1144. $dateTime = date('Y-m-d H:i:s');
  1145. MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3);
  1146. DB::commit();
  1147. // 充值星豆任务
  1148. TaskService::make()->updateTask($userId,9, 0);
  1149. $this->error = 2037;
  1150. RedisService::clear($cacheKey);
  1151. return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)];
  1152. }
  1153. /**
  1154. * 余额提现
  1155. * @param $userId
  1156. * @param $params
  1157. * @return array|false
  1158. */
  1159. public function withdraw($userId, $params)
  1160. {
  1161. $money = isset($params['money'])? floatval($params['money']) : 0;
  1162. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1163. $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1;
  1164. if($money<=0){
  1165. $this->error = 2401;
  1166. return false;
  1167. }
  1168. if(!in_array($userType,[1,2])){
  1169. $this->error = 2404;
  1170. return false;
  1171. }
  1172. $userInfo = $this->model->with(['merchant'])
  1173. ->where(['id'=> $userId,'mark'=>1])
  1174. ->select(['id','nickname','usdt','trc_url','pay_password','status'])
  1175. ->first();
  1176. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1177. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1178. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1179. $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : [];
  1180. $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0;
  1181. $merchantId = isset($merchant['id'])? $merchant['id'] : 0;
  1182. $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0;
  1183. if(empty($userInfo) || $status != 1){
  1184. $this->error = 2024;
  1185. return false;
  1186. }
  1187. if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){
  1188. $this->error = 2024;
  1189. return false;
  1190. }
  1191. // 提现金额验证
  1192. $accountUsdt = $userType==1? $userUsdt : $merchantUsdt;
  1193. if ($money > $accountUsdt) {
  1194. $this->error = web_lang(2402, ['money' => $accountUsdt]);
  1195. return false;
  1196. }
  1197. // 提现账户
  1198. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1199. if (empty($trcUrl)) {
  1200. $this->error = 2403;
  1201. return false;
  1202. }
  1203. if($userPayPassword != get_password($payPassword)){
  1204. $this->error = 2038;
  1205. return false;
  1206. }
  1207. $cacheKey = "caches:member:withdraw:lock_{$userId}";
  1208. if(RedisService::get($cacheKey)){
  1209. $this->error = 1034;
  1210. return false;
  1211. }
  1212. DB::beginTransaction();
  1213. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1214. // 提现记录
  1215. $orderNo = get_order_num('DW');
  1216. $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5);
  1217. $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0;
  1218. $fee = round($money*$feeRate, 2);
  1219. $realUsdt = moneyFormat($money - $fee, 2);
  1220. $data = [
  1221. 'order_no'=> $orderNo,
  1222. 'user_id'=> $userType==1? $userId : $merchantId,
  1223. 'type'=> 2,
  1224. 'user_type'=> $userType,
  1225. 'coin_type'=> 1,
  1226. 'money'=> $money,
  1227. 'actual_money'=> $realUsdt,
  1228. 'fee'=> $fee,
  1229. 'trc_url'=> $trcUrl,
  1230. 'pay_type'=> 20,
  1231. 'date'=> date('Y-m-d'),
  1232. 'create_time'=> time(),
  1233. 'update_time'=> time(),
  1234. 'status'=> 1,
  1235. 'mark'=> 1,
  1236. ];
  1237. if(!$id = BalanceLogModel::insertGetId($data)){
  1238. DB::rollBack();
  1239. $this->error = 2405;
  1240. RedisService::clear($cacheKey);
  1241. return false;
  1242. }
  1243. // 商户扣款
  1244. if($userType == 2){
  1245. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1246. if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){
  1247. DB::rollBack();
  1248. $this->error = 2406;
  1249. RedisService::clear($cacheKey);
  1250. return false;
  1251. }
  1252. // 明细
  1253. $log = [
  1254. 'user_id' => $merchantId,
  1255. 'source_id' => $userId,
  1256. 'source_order_no' => $orderNo,
  1257. 'type' => 5,
  1258. 'coin_type' => 1,
  1259. 'user_type'=> 2,
  1260. 'money' => -$money,
  1261. 'actual_money' => -$money,
  1262. 'balance' => $merchantUsdt,
  1263. 'create_time' => time(),
  1264. 'update_time' => time(),
  1265. 'remark' => "商户账户余额提现",
  1266. 'status' => 1,
  1267. 'mark' => 1,
  1268. ];
  1269. if (!AccountLogModel::insertGetId($log)) {
  1270. $this->error = 2407;
  1271. DB::rollBack();
  1272. RedisService::clear($cacheKey);
  1273. return false;
  1274. }
  1275. }
  1276. // 用户扣款
  1277. else{
  1278. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1279. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1280. DB::rollBack();
  1281. $this->error = 2406;
  1282. RedisService::clear($cacheKey);
  1283. return false;
  1284. }
  1285. // 明细
  1286. $log = [
  1287. 'user_id' => $userId,
  1288. 'source_id' => 0,
  1289. 'source_order_no' => $orderNo,
  1290. 'type' => 5,
  1291. 'coin_type' => 1,
  1292. 'user_type'=> 1,
  1293. 'money' => -$money,
  1294. 'actual_money' => -$money,
  1295. 'balance' => $userUsdt,
  1296. 'create_time' => time(),
  1297. 'update_time' => time(),
  1298. 'remark' => "USDT余额提现",
  1299. 'status' => 1,
  1300. 'mark' => 1,
  1301. ];
  1302. if (!AccountLogModel::insertGetId($log)) {
  1303. $this->error = 2407;
  1304. DB::rollBack();
  1305. RedisService::clear($cacheKey);
  1306. return false;
  1307. }
  1308. }
  1309. DB::commit();
  1310. // 站内消息
  1311. $dateTime = date('Y-m-d H:i:s');
  1312. $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功';
  1313. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!";
  1314. MessageService::make()->pushMessage($userId, $title, $message);
  1315. // 提现自动审核,低于该金额自动审核
  1316. $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300);
  1317. $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0;
  1318. if ($money <= $autoCheckUsdt) {
  1319. // 打款处理
  1320. $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realUsdt);
  1321. $txID = isset($result['txId']) ? $result['txId'] : '';
  1322. $payAddress = isset($result['address']) ? $result['address'] : '';
  1323. if ($txID && $payAddress) {
  1324. $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()];
  1325. if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){
  1326. $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功';
  1327. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!";
  1328. MessageService::make()->pushMessage($userId, $title, $message);
  1329. AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]);
  1330. // 平台明细
  1331. $log = [
  1332. 'user_id' => 0,
  1333. 'source_id' => $userId,
  1334. 'source_order_no' => $orderNo,
  1335. 'type' => 5,
  1336. 'coin_type' => 1,
  1337. 'user_type'=> 4,
  1338. 'money' => $fee,
  1339. 'actual_money' => $fee,
  1340. 'balance' => 0,
  1341. 'create_time' => time(),
  1342. 'update_time' => time(),
  1343. 'hash' => $txID,
  1344. 'remark' => "USDT余额提现",
  1345. 'status' => 1,
  1346. 'mark' => 1,
  1347. ];
  1348. AccountLogModel::insertGetId($log);
  1349. // 平台流水
  1350. FinanceService::make()->saveLog(0, $fee, 1);
  1351. }
  1352. }
  1353. }
  1354. $this->error = $title;
  1355. RedisService::clear($cacheKey);
  1356. return [
  1357. 'id'=> $id,
  1358. 'money'=> $money,
  1359. 'user_type'=> $userType,
  1360. ];
  1361. }
  1362. /**
  1363. * 获取点对点上级节点
  1364. * @param $userId 推荐人ID
  1365. * @return int|mixed
  1366. */
  1367. public function getPointParentId($userId)
  1368. {
  1369. if($userId<=0){
  1370. return 0;
  1371. }
  1372. $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get();
  1373. $userList = $userList? $userList->toArray() : [];
  1374. if(count($userList) < 3){
  1375. return $userId;
  1376. }
  1377. $users = [];
  1378. foreach($userList as $item){
  1379. $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
  1380. $points = array_filter($points);
  1381. $users[$item['id']]['pointLen'] = count($points);
  1382. $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
  1383. $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
  1384. }
  1385. //var_dump($users);
  1386. $pointId = 0;
  1387. $tempPointLen = 0;
  1388. $tempChildren = 0;
  1389. foreach ($userList as $item) {
  1390. $id = isset($item['id'])? $item['id'] : 0;
  1391. $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
  1392. $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
  1393. //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren);
  1394. if($pointLen<=$tempPointLen || $pointId == 0){
  1395. //var_dump($id.'++'.$pointLen.'--'.$children."\n\n");
  1396. if($children <$tempChildren || $pointId == 0){
  1397. $pointId = $id;
  1398. $tempPointLen = $pointLen;
  1399. $tempChildren = $children;
  1400. }
  1401. }
  1402. }
  1403. return $pointId;
  1404. }
  1405. /**
  1406. * DAO升级购买
  1407. * @param $userId 用户ID
  1408. * @param $params 参数:level-等级,pay_password-交易密码
  1409. * @return bool
  1410. */
  1411. public function upgrade($userId, $params)
  1412. {
  1413. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1414. $level = isset($params['level'])? intval($params['level']) : 0;
  1415. if($level<=0 || empty($payPassword)){
  1416. $this->error = 2014;
  1417. return false;
  1418. }
  1419. $cacheKey = "caches:members:upgrade:buy_{$userId}_{$level}";
  1420. if(RedisService::get($cacheKey.'_lock')){
  1421. $this->error = 1034;
  1422. return false;
  1423. }
  1424. $levelInfo = MemberLevelModel::from('member_level as a')
  1425. ->where(['a.id'=> $level,'a.status'=>1,'a.mark'=>1])
  1426. ->select(['a.*'])
  1427. ->first();
  1428. $upgradeUsdt = isset($levelInfo['upgrade_usdt'])? floatval($levelInfo['upgrade_usdt']) : 0;
  1429. $upgradeProfit = isset($levelInfo['upgrade_profit'])? floatval($levelInfo['upgrade_profit']) : 0;
  1430. $boxNum = isset($levelInfo['box_num'])? intval($levelInfo['box_num']) : 0;
  1431. $levelName = isset($levelInfo['name'])? $levelInfo['name'] : '';
  1432. if(empty($levelInfo)){
  1433. $this->error = 2511;
  1434. return false;
  1435. }
  1436. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  1437. ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','trc_url','pay_password','status'])
  1438. ->first();
  1439. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1440. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1441. $userTotalProfit = isset($userInfo['upgrade_profit_total'])? $userInfo['upgrade_profit_total'] : 0;
  1442. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1443. $userWaitScore = isset($userInfo['wait_score'])? $userInfo['wait_score'] : 0;
  1444. $userPowerNum = isset($userInfo['power_num'])? $userInfo['power_num'] : 0;
  1445. $userLevel = isset($userInfo['member_level'])? intval($userInfo['member_level']) : 0;
  1446. if(empty($userInfo) || $status != 1){
  1447. $this->error = 2024;
  1448. return false;
  1449. }
  1450. if($userLevel>= $level){
  1451. $this->error = 2512;
  1452. return false;
  1453. }
  1454. if($level >= 30){
  1455. $this->error = 2513;
  1456. return false;
  1457. }
  1458. // 收益是否满足条件
  1459. if($upgradeProfit>0 && $userTotalProfit < $upgradeProfit){
  1460. $this->error = 2514;
  1461. return false;
  1462. }
  1463. if(AccountLogModel::where(['user_id'=> $userId,'source_id'=> $level,'type'=>2,'coin_type'=>1,'status'=>1,'mark'=>1])->value('id')){
  1464. $this->error = 2512;
  1465. return false;
  1466. }
  1467. // USDT余额是否足够
  1468. if($userUsdt < $upgradeUsdt){
  1469. $this->error = 2035;
  1470. return false;
  1471. }
  1472. // 交易密码
  1473. if(empty($userPayPassword)){
  1474. $this->error = 1040;
  1475. return false;
  1476. }
  1477. if($userPayPassword != get_password($payPassword)){
  1478. $this->error = 2038;
  1479. return false;
  1480. }
  1481. // 购买明细
  1482. RedisService::set($cacheKey, $params, rand(2,3));
  1483. $orderNo = get_order_num('UP');
  1484. DB::beginTransaction();
  1485. $log = [
  1486. 'user_id' => $userId,
  1487. 'source_id' => $level,
  1488. 'source_order_no' => $orderNo,
  1489. 'type' => 2,
  1490. 'coin_type' => 1,
  1491. 'user_type'=> 1,
  1492. 'money' => -$upgradeUsdt,
  1493. 'actual_money' => -$upgradeUsdt,
  1494. 'balance' => $userUsdt,
  1495. 'create_time' => time(),
  1496. 'update_time' => time(),
  1497. 'remark' => "购买{$levelName}升级",
  1498. 'status' => 1,
  1499. 'mark' => 1,
  1500. ];
  1501. if(!AccountLogModel::insertGetId($log)){
  1502. DB::rollBack();
  1503. $this->error = 2029;
  1504. RedisService::clear($cacheKey);
  1505. return false;
  1506. }
  1507. // 待返积分
  1508. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  1509. $xdPrice = $xdPrice>0 && $xdPrice<=10000? $xdPrice : 100;
  1510. $waitScoreRate = ConfigService::make()->getConfigByCode('upgrade_award_score_rate', 200);
  1511. $waitScoreRate = $waitScoreRate>0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  1512. $waitScore = moneyFormat($upgradeUsdt * $xdPrice * $waitScoreRate/100, 2);
  1513. if($waitScore>0){
  1514. $log = [
  1515. 'user_id' => $userId,
  1516. 'source_id' => $level,
  1517. 'source_order_no' => $orderNo,
  1518. 'type' => 9,
  1519. 'coin_type' => 5,
  1520. 'user_type'=> 1,
  1521. 'money' => $waitScore,
  1522. 'actual_money' => $waitScore,
  1523. 'balance' => $userWaitScore,
  1524. 'create_time' => time(),
  1525. 'update_time' => time(),
  1526. 'remark' => "购买{$levelName}升级",
  1527. 'status' => 1,
  1528. 'mark' => 1,
  1529. ];
  1530. if(!AccountLogModel::insertGetId($log)){
  1531. DB::rollBack();
  1532. $this->error = 2029;
  1533. RedisService::clear($cacheKey);
  1534. return false;
  1535. }
  1536. }
  1537. // 算力明细
  1538. $powerNum = $upgradeUsdt;
  1539. $log = [
  1540. 'user_id' => $userId,
  1541. 'source_id' => $level,
  1542. 'source_order_no' => $orderNo,
  1543. 'type' => 9,
  1544. 'coin_type' => 3,
  1545. 'user_type'=> 1,
  1546. 'money' => $powerNum,
  1547. 'actual_money' => $powerNum,
  1548. 'balance' => $userPowerNum,
  1549. 'create_time' => time(),
  1550. 'update_time' => time(),
  1551. 'remark' => "购买{$levelName}升级",
  1552. 'status' => 1,
  1553. 'mark' => 1,
  1554. ];
  1555. if(!AccountLogModel::insertGetId($log)){
  1556. DB::rollBack();
  1557. $this->error = 2029;
  1558. RedisService::clear($cacheKey);
  1559. return false;
  1560. }
  1561. // 账户
  1562. $updateData = [
  1563. 'usdt'=> DB::raw("usdt - {$upgradeUsdt}"), // 扣除USDT
  1564. 'member_level'=> $level, // 升级等级
  1565. 'box_num'=>DB::raw("box_num + {$boxNum}"), // 奖励盲盒数量
  1566. 'wait_score'=>DB::raw("wait_score + {$waitScore}"), // 待返积分奖励
  1567. 'power_num'=>DB::raw("power_num + {$powerNum}"), // 算力奖励
  1568. 'update_time'=>time()
  1569. ];
  1570. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  1571. DB::rollBack();
  1572. $this->error = 2036;
  1573. RedisService::clear($cacheKey);
  1574. return false;
  1575. }
  1576. // 消息
  1577. $dateTime = date('Y-m-d H:i:s');
  1578. MessageService::make()->pushMessage($userId,"购买{$levelName}升级成功","您在{$dateTime}(UTC+8)成功支付{$upgradeUsdt}USDT购买【{$levelName}】升级成功。",3);
  1579. DB::commit();
  1580. // 算力统计
  1581. AccountLogService::make()->saveCount($userId, $powerNum, 1);
  1582. // 业绩统计
  1583. AccountLogService::make()->saveCount($userId, $upgradeUsdt, 2);
  1584. // 结算收益奖励
  1585. FinanceService::make()->settleBonus($userId, $userInfo, $upgradeUsdt, $orderNo, "购买{$levelName}");
  1586. $this->error = 2503;
  1587. RedisService::clear($cacheKey);
  1588. return true;
  1589. }
  1590. /**
  1591. * 盲盒抽奖
  1592. * @param $userId 抽奖用户ID
  1593. * @param $params
  1594. * @return bool
  1595. */
  1596. public function draw($userId, $params)
  1597. {
  1598. $cacheKey="caches:members:draw_{$userId}";
  1599. if(RedisService::get($cacheKey.'_lock')){
  1600. $this->error = 1034;
  1601. return false;
  1602. }
  1603. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  1604. ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','box_num','trc_url','pay_password','status'])
  1605. ->first();
  1606. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1607. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1608. $boxNum = isset($userInfo['box_num'])? $userInfo['box_num'] : 0;
  1609. if(empty($userInfo) || $status != 1){
  1610. $this->error = 2024;
  1611. return false;
  1612. }
  1613. if($boxNum <= 0){
  1614. $this->error = 3101;
  1615. return false;
  1616. }
  1617. // 中奖结果
  1618. $drawRate = ConfigService::make()->getConfigByCode('box_award_rate',20);
  1619. $drawRate = $drawRate>0 && $drawRate<100? $drawRate : 20;
  1620. $drawMachineExpireDay = ConfigService::make()->getConfigByCode('draw_machine_time',30);
  1621. $drawMachineExpireDay = $drawMachineExpireDay>0 && $drawMachineExpireDay<360? $drawMachineExpireDay : 30;
  1622. DB::beginTransaction();
  1623. // 扣除次数
  1624. $updateData = ['box_num'=> DB::raw("box_num -1"),'update_time'=>time()];
  1625. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  1626. DB::rollBack();
  1627. $this->error = 3102;
  1628. return false;
  1629. }
  1630. // 是否中奖
  1631. $isAward = false;
  1632. $randNum = rand(1000,9999);
  1633. if($randNum > $drawRate * 10000/100){
  1634. $isAward = true;
  1635. }
  1636. // 未中奖,直接推送消息
  1637. if(!$isAward){
  1638. DB::commit();
  1639. // 消息
  1640. $dateTime = date('Y-m-d H:i:s');
  1641. MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【未中奖】,请继续加油。",3);
  1642. $this->error = 3107;
  1643. return ['id'=>0,'num'=>$randNum];
  1644. }
  1645. // 随机获取算力机
  1646. $machineInfo = MachineModel::where(['is_draw'=>1,'status'=>1,'mark'=>1])
  1647. ->select(['id as machine_id','name','price','power','month_rate','sl','day_wait_score','day_xd','day_score'])
  1648. ->orderBy(DB::raw('RAND()'))
  1649. ->first();
  1650. $machineInfo = $machineInfo? $machineInfo->toArray() : [];
  1651. $machineName = isset($machineInfo['name'])? $machineInfo['name'] : '';
  1652. if(empty($machineInfo)){
  1653. DB::rollBack();
  1654. $this->error = 3103;
  1655. return false;
  1656. }
  1657. $orderNo = get_order_num('DM');
  1658. $machineInfo['user_id'] = $userId;
  1659. $machineInfo['order_no'] = $orderNo;
  1660. $machineInfo['create_time'] = time();
  1661. $machineInfo['status'] = 1;
  1662. $machineInfo['mark'] = 1;
  1663. // 有效期
  1664. if($drawMachineExpireDay>0){
  1665. $machineInfo['expired_at'] = date('Y-m-d H:i:s', time() + $drawMachineExpireDay * 86400);
  1666. }
  1667. unset($machineInfo['name']);
  1668. if(!$id = DrawLogModel::insertGetId($machineInfo)){
  1669. DB::rollBack();
  1670. $this->error = 3102;
  1671. return false;
  1672. }
  1673. // 抽奖完成
  1674. DB::commit();
  1675. // 消息
  1676. $dateTime = date('Y-m-d H:i:s');
  1677. $machineName = $machineName? $machineName : '算力矿机';
  1678. MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【已中奖】一台{$machineName},请查看您的矿机列表查收。",3);
  1679. $this->error = web_lang('3106',['name'=>$machineName]);
  1680. return ['id'=> $id,'name'=> $machineName,'num'=> $randNum];
  1681. }
  1682. }