| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services\Api;
- use App\Helpers\Jwt;
- use App\Models\AccountLogModel;
- use App\Models\BalanceLogModel;
- use App\Models\CartsModel;
- use App\Models\DrawLogModel;
- use App\Models\LiveModel;
- use App\Models\MachineModel;
- use App\Models\MemberBankModel;
- use App\Models\MemberLevelModel;
- use App\Models\MemberModel;
- use App\Models\MerchantModel;
- use App\Models\VideoModel;
- use App\Services\BaseService;
- use App\Services\CityService;
- use App\Services\ConfigService;
- use App\Services\EmailService;
- use App\Services\RedisService;
- use App\Services\SmsService;
- use App\Services\ToolService;
- use App\Services\UdunpayService;
- use App\Services\WalletService;
- use Illuminate\Support\Facades\DB;
- use phpQrcode\QRcode;
- /**
- * 会员管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class MemberService
- * @package App\Services\Api
- */
- class MemberService extends BaseService
- {
- // 静态对象
- protected static $instance = null;
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- * MemberService constructor.
- */
- public function __construct()
- {
- $this->model = new MemberModel();
- }
- /**
- * 静态入口
- * @return MemberService|static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 获取资料详情
- * @param $where
- * @param array $field
- */
- public function getInfo($where, $type = 'detail', array $field = [], $userId=0)
- {
- $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'];
- $withs = ['merchant','acceptor','parent','point','level'];
- if ($type == 'team') {
- $defaultField = ['id', 'username','email','member_level', 'nickname','usdt', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar'];
- }else if($type == 'share'){
- $withs = ['parent','level'];
- $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar'];
- }else if($type == 'check'){
- $withs = ['parent','level'];
- $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar'];
- }else if ($type == 'info'){
- $withs = ['parent','level'];
- }else if ($type == 'chat'){
- $withs = [];
- }
- $field = $field ? $field : $defaultField;
- if (is_array($where)) {
- $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first();
- } else {
- $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first();
- }
- $info = $info ? $info->toArray() : [];
- if ($info && !in_array($type, ['auth', 'check','login','chat'])) {
- $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
- $info['balance'] = moneyFormat($info['balance'], 2);
- $info['usdt'] = isset($info['usdt'])?moneyFormat($info['usdt'], 2):'0.00';
- $info['score'] = moneyFormat($info['score'], 2);
- $info['merchant'] = isset($info['merchant']) && $info['merchant']? $info['merchant'] : ['id'=>0];
- $info['acceptor'] = isset($info['acceptor']) && $info['acceptor']? $info['acceptor'] : ['id'=>0];
- $info['level'] = isset($info['level']) && $info['level']? $info['level'] : ['id'=>0,'name'=>'普通用户'];
- $info['custom_phone'] = ConfigService::make()->getConfigByCode('custom_phone');
- $info['custom_telegram'] = ConfigService::make()->getConfigByCode('custom_telegram');
- $info['custom_email'] = ConfigService::make()->getConfigByCode('custom_email');
- if(isset($info['birthday'])){
- $info['birthday_text'] = $info['birthday']? date('Y-m-d',$info['birthday']) : '';
- }
- // 二维码
- if (in_array($type, ['detail'])) {
- $info['parent_code'] = '';
- $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无'];
- if($info['parent']['id']>0){
- $info['parent_code'] = isset($info['parent']['code'])? $info['parent']['code'] :'';
- }
- $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
- $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
- $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
- if($userId != $info['id']){
- $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
- }else{
- $info['is_follow'] = 1;
- }
- $info['app_version'] = ConfigService::make()->getConfigByCode('app_version');
- $info['chat_token'] = MemberService::make()->getChatToken($info['id'].'@1@'.date('His'), 1);
- }
- else if ($type == 'info') {
- $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0);
- $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0;
- $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0;
- $info['chat_token'] = MemberService::make()->getChatToken($info['id'].'@1@'.date('His'), 1);
- }else if($type == 'buy'){
- $address = MemberAddressService::make()->getBindInfo($userId);
- $info['address'] = $address;
- $streetCode = isset($address['street_code'])? $address['street_code'] : '';
- $info['freight_address_id'] = $streetCode? $streetCode : (isset($address['district_code'])? $address['district_code'] : '');
- $info['address_id'] = isset($address['id'])? $address['id'] : 0;
- $info['cart_num'] = GoodsService::make()->getCartCount($info['id']);
- }else if($type == 'upgrade'){
- $level = isset($info['level'])? $info['level'] : [];
- $nextLevel = MemberLevelModel::where('id','>', $info['member_level'])->orderBy('id','asc')->first();
- $info['next_level'] = isset($nextLevel['id']) && $nextLevel['id']? $nextLevel['id'] : $info['member_level'];
- $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);
- $info['next_level_usdt'] = isset($nextLevel['upgrade_usdt']) && $nextLevel['upgrade_usdt']? $nextLevel['upgrade_usdt'] : (isset($level['upgrade_usdt'])? $level['upgrade_usdt']:0);
- $info['next_level_name'] = isset($nextLevel['name'])? $nextLevel['name'] : (isset($level['name'])? $level['name']:'');
- }
- else if ($type == 'recharge') {
- $wallet = WalletService::make()->getWallet(1);
- $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : '';
- $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100);
- if($info['recharge_trc_url']){
- $qrcode = $this->makeQrcode($info['recharge_trc_url']);
- $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : '';
- }else{
- $info['trc_qrcode'] = '';
- }
- }
- else if ($type == 'team' || $type == 'share') {
- $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']);
- $qrcode = $this->makeQrcode($inviteUrl);
- $info['qrcode'] = $qrcode ? get_image_url($qrcode) : '';
- $info['invite_url'] = $inviteUrl;
- $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):'';
- $info['qrcode_header'] = get_image_url('/images/qrcode/qrcode-header.png');
- $info['qrcode_header_base64'] = getImageContent('/images/qrcode/qrcode-header.png');
- $info['qrcode_bg'] = get_image_url('/images/qrcode/qrcode-bg.png');
- $info['qrcode_bg_base64'] = getImageContent('/images/qrcode/qrcode-bg.png');
- $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数
- $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数
- $info['team_count'] = $this->getUserCountByType($info['id'], 2, 0); // 团队人数
- }else {
- // 默认地址
- $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']);
- }
- }
- return $info;
- }
- /**
- * 获取主页信息
- * @param $where
- * @param array $field
- */
- public function getHomeInfo($id, $userId=0)
- {
- $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'];
- $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first();
- $info = $info ? $info->toArray() : [];
- if ($info) {
- $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
- $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
- $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
- $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
- $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
- $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝
- $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播
- }
- return $info;
- }
- /**
- * 获取聊天TOKEN或者解码用户ID
- * @param $key
- * @param $type
- * @return false|string|string[]
- */
- public function getChatToken($key, $type)
- {
- // 加密
- $salt = 'starLink';
- if ($type == 1) {
- $baseStr = base64_encode($salt.'-'.$key);
- $str = substr($baseStr, -6, 7) . substr(md5($salt), 2, 6) . substr($baseStr, 0, -6);
- return str_replace(['==', '='], ['-2', '-1'], $str);
- } // 解密
- else {
- $str1 = substr($key, 12) . substr($key, 0, 6);
- $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
- $str = base64_decode($str1);
- $str = str_replace("{$salt}-",'', $str);
- $data = explode('@', $str);
- return [
- 'user_id'=> isset($data[0])? $data[0] : 0,
- 'user_type'=> isset($data[1]) && $data[1]? $data[1] : 1,
- ];
- }
- }
- /**
- * 获取用户缓存信息
- * @param $where
- * @param array $field
- * @param int $expired
- * @return array|mixed
- */
- public function getCacheInfo($where, $field = [], $expired = 0)
- {
- $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired);
- $info = RedisService::get($cacheKey);
- if ($info) {
- return $info;
- }
- $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar'];
- $field = $field ? $field : $defaultField;
- $info = $this->model->where($where)->where('mark', 1)->select($field)->first();
- $info = $info ? $info->toArray() : [];
- if ($info) {
- if (isset($info['avatar'])) {
- $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png';
- $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : '';
- }
- RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5));
- }
- return $info;
- }
- /**
- * 生成普通参数二维码
- * @param $str 参数
- * @param bool $refresh 是否重新生成
- * @return bool
- */
- public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
- {
- $basePath = base_path() . '/public';
- $qrFile = '/images/qrcode/';
- if (!is_dir($basePath . '/uploads' . $qrFile)) {
- @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
- }
- $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
- $qrFile = $qrFile . "C_{$key}.png";
- $cacheKey = "caches:qrcodes:member_" . $key;
- if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
- return $qrFile;
- }
- QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
- if (!file_exists($basePath . '/uploads' . $qrFile)) {
- return false;
- }
- RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
- return $qrFile;
- }
- /**
- * 获取团队用户数量
- * @param $userId 当前用户ID
- * @param int $type 层级:1-直推,2-团队
- * @param int $isPoint 节点:1-滑落推荐,0-直接推荐
- * @return array|mixed
- */
- public function getUserCountByType($userId, $type = 1, $isPoint=0)
- {
- $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}";
- $data = RedisService::get($cacheKey);
- if ($data) {
- return $data;
- }
- $where = ['status' => 1, 'mark' => 1];
- $data = $this->model->where($where)
- ->where(function ($query) use ($type, $isPoint, $userId) {
- if($isPoint){
- if ($type == 1) { // 滑落推荐
- $query->where('point_id', $userId);
- } else if($type == 2){ // 滑落团队人数
- $query->whereRaw('FIND_IN_SET(?,points)', $userId);
- }
- }else{
- if ($type == 1) { // 直推人数
- $query->where('parent_id', $userId);
- } else if($type == 2){ // 团队人数
- $query->whereRaw("FIND_IN_SET({$userId},parents)");
- } else if($type == 3){ // 滑落人数
- $query->where('parent_id', $userId)->where('point_id','!=', $userId);
- }
- }
- })->count('id');
- if ($data) {
- RedisService::set($cacheKey, $data, rand(3, 5));
- }
- return $data;
- }
- /**
- * 分销用户列表
- * @param $userId
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getTeamList($userId, $params, $pageSize=15)
- {
- $page = request()->post('page',1);
- $cacheKey = "caches:teams:list_{$userId}_{$page}";
- $datas = RedisService::get($cacheKey);
- if ($datas) {
- return [
- 'pageSize' => $pageSize,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => isset($datas['data']) ? $datas['data'] : []
- ];
- }
- $where = ['status' => 1, 'mark' => 1];
- $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status'];
- $datas = $this->model->with(['level'])->where($where)
- ->where(function ($query) use ($userId) {
- $query->where('parent_id', $userId);
- })
- ->where(function($query) use($params){
- $kw = isset($params['kw'])? trim($params['kw']) : '';
- if($kw){
- $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%");
- }
- })
- ->select($field)
- ->orderBy('create_time', 'desc')
- ->orderBy('id', 'desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $datas = $datas ? $datas->toArray() : [];
- if ($datas) {
- foreach ($datas['data'] as &$item) {
- $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
- $item['avatar'] = get_image_url($item['avatar']);
- $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : '';
- $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0;
- }
- unset($item);
- RedisService::set($cacheKey, $datas, rand(5, 10));
- }
- return [
- 'pageSize' => $pageSize,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => isset($datas['data']) ? $datas['data'] : []
- ];
- }
- /**
- * 手机号是否已注册
- * @param $mobile
- * @return mixed
- */
- public function checkPhoneExists($mobile)
- {
- return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub
- }
- /**
- * 账号注册
- * @param $params
- * @return array|false
- */
- public function register($params)
- {
- // 授权
- $email = isset($params['email']) ? trim($params['email']) : '';
- $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
- $registerType = isset($params['type']) ? intval($params['type']) : 1;
- $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
- $code = isset($params['code']) ? trim($params['code']) : '';
- $scene = isset($params['scene']) ? $params['scene'] : '';
- $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
- $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
- if (empty($params) || $code <= 0 || !in_array($registerType,[1,2])) {
- $this->error = 2014;
- return false;
- }
- // 邮箱注册
- if($registerType == 1){
- if(empty($email)){
- $this->error = 2014;
- return false;
- }
- // 验证码
- if (!EmailService::make()->check($email, $code, $scene)) {
- $this->error = EmailService::make()->getError();
- return false;
- }
- // 验证是否注册
- if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){
- $this->error = 2009;
- return false;
- }
- }else if($registerType == 2){
- if(empty($mobile)){
- $this->error = 2014;
- return false;
- }
- // 验证码
- if (!SmsService::make()->check($mobile, $code, $scene)) {
- $this->error = SmsService::make()->getError();
- return false;
- }
- // 验证是否注册
- if($this->model->where(['mobile'=> $mobile,'mark'=>1])->value('id')){
- $this->error = 1058;
- return false;
- }
- }
- // 推荐人
- $parentId = 0;
- $pointId = 0;
- $parents = '';
- $points = '';
- if ($inviteCode) {
- $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
- ->select(['id', 'parents', 'parent_id'])
- ->first();
- $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
- $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
- // 挂靠节点
- if($parentId>0){
- $pointId = $this->getPointParentId($parentId);
- if($pointId){
- $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
- $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
- }
- }
- }
- // 注册
- $id = $this->model->max('id') + 1;
- $system = isset($params['system'])? $params['system'] : [];
- $ip = get_client_ip();
- $ipData = ToolService::make()->getIpAddress($ip,'');
- $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
- $city = isset($ipData['city'])? $ipData['city'] : '';
- $emailName = explode('@', $email)[0];
- $password = isset($params['password']) ? $params['password'] : 'xl123456';
- // 钱包
- $data = [
- 'parent_id' => $parentId,
- 'point_id' => $pointId,
- 'points' => $points,
- 'openid' => '',
- 'avatar' => '',
- 'nickname' => $nickname ? $nickname : 'XL'.substr($emailName?$emailName:substr($mobile,-8,8),-8,8),
- 'username' => $registerType==1? $email : $mobile,
- 'password' => get_password($password),
- 'code' => strtoupper(get_random_code(9, 'X', "{$id}")),
- 'email' => $email,
- 'mobile' => $mobile,
- 'recharge_trc_url' => '',
- 'parents' => $parents,
- 'province_id' => CityService::make()->getFieldByName($province),
- 'city_id' => CityService::make()->getFieldByName($city),
- 'city' => $city,
- 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '',
- 'device' => $appSources == 'android' ? 2 : 1,
- 'status' => 1,
- 'balance' => 0,
- 'score' => 0,
- 'mark' => 1,
- 'login_ip' => $ip,
- 'create_time' => time(),
- ];
- $userId = $this->model->insertGetId($data);
- $this->error = 2008;
- return [
- 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
- 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']],
- ];
- }
- /**
- * 邮箱登录
- * @param $params
- * @return array|false
- */
- public function loginByEmail($params)
- {
- // 授权
- $email = isset($params['email']) ? $params['email'] : '';
- $code = isset($params['code']) ? $params['code'] : '';
- $scene = isset($params['scene']) ? $params['scene'] : '';
- $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
- $password = isset($params['password']) ? $params['password'] : '';
- if (empty($params) || empty($email) || empty($scene) ) {
- $this->error = 2014;
- return false;
- }
- // 验证是否注册,没有则注册
- $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status','password'])->first();
- $data = $data ? $data->toArray() : [];
- if(!empty($password)){
- if(get_password($password) != $data['password']){
- $this->error = 3108;
- return false;
- }
- }else{
- // 验证码
- if (!EmailService::make()->check($email, $code, $scene)) {
- $this->error = EmailService::make()->getError();
- return false;
- }
- }
- $userId = isset($data['id']) ? $data['id'] : 0;
- $status = isset($data['status']) ? $data['status'] : 0;
- if(empty($data) || $userId<=0){
- $this->error = 2001;
- return false;
- }
- if ($status != 1) {
- $this->error = 2015;
- return false;
- }
- // 获取登录授权token
- $jwt = new Jwt('jwt_dys_app');
- $token = $jwt->getToken($userId);
- // 结果返回
- $result = [
- 'access_token' => $token,
- 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
- ];
- // 用户信息
- $ip = get_client_ip();
- $updateData = [
- 'login_time' => time(),
- 'login_ip' => $ip,
- ];
- if(!RedisService::get("caches:member:updateArea:{$userId}")){
- $ipData = ToolService::make()->getIpAddress($ip,'');
- $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
- $city = isset($ipData['city'])? $ipData['city'] : '';
- $updateData['province_id'] = CityService::make()->getFieldByName($province);
- $updateData['city_id'] = CityService::make()->getFieldByName($city);
- }
- $this->model->where(['id'=> $userId])->update($updateData);
- $this->error = 2004;
- $data['token'] = $token;
- RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
- RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
- return $result;
- }
- /**
- * 手机号登录
- * @param $params
- * @return array|false
- */
- public function loginByMobile($params)
- {
- // 授权
- $mobile = isset($params['mobile']) ? $params['mobile'] : '';
- $code = isset($params['code']) ? $params['code'] : '';
- $scene = isset($params['scene']) ? $params['scene'] : '';
- $password = isset($params['password']) ? $params['password'] : '';
- $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
- if (empty($params) || empty($mobile) || empty($scene) ) {
- $this->error = 2014;
- return false;
- }
- // 验证是否注册,没有则注册
- $data = $this->model->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'username','point_id','mobile', 'parent_id', 'code', 'status','password'])->first();
- $data = $data ? $data->toArray() : [];
- if(!empty($password)){
- if(get_password($password) != $data['password']){
- $this->error = 3108;
- return false;
- }
- }else{
- // 验证码
- if (!SmsService::make()->check($mobile, $code, $scene)) {
- $this->error = SmsService::make()->getError();
- return false;
- }
- }
- $userId = isset($data['id']) ? $data['id'] : 0;
- $status = isset($data['status']) ? $data['status'] : 0;
- if(empty($data) || $userId<=0){
- $this->error = 2001;
- return false;
- }
- if ($status != 1) {
- $this->error = 2015;
- return false;
- }
- // 获取登录授权token
- $jwt = new Jwt('jwt_dys_app');
- $token = $jwt->getToken($userId);
- // 结果返回
- $result = [
- 'access_token' => $token,
- 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
- ];
- // 用户信息
- $ip = get_client_ip();
- $updateData = [
- 'login_time' => time(),
- 'login_ip' => $ip,
- ];
- if(!RedisService::get("caches:member:updateArea:{$userId}")){
- $ipData = ToolService::make()->getIpAddress($ip,'');
- $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
- $city = isset($ipData['city'])? $ipData['city'] : '';
- $updateData['province_id'] = CityService::make()->getFieldByName($province);
- $updateData['city_id'] = CityService::make()->getFieldByName($city);
- }
- $this->model->where(['id'=> $userId])->update($updateData);
- $this->error = 2004;
- $data['token'] = $token;
- RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
- RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
- return $result;
- }
- /**
- * 修改头像/商家logo/技师头像
- * @param $userId
- * @param $avatar
- * @return mixed
- */
- public function saveAvatar($userId, $avatar)
- {
- $type = request()->post('type', 1);
- if($type == 1){
- $oldAvatar = $this->model->where(['id' => $userId])->value('avatar');
- if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
- if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
- @unlink(ATTACHMENT_PATH . $oldAvatar);
- }
- return true;
- }
- }else if($type == 2){
- $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo');
- if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) {
- if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
- @unlink(ATTACHMENT_PATH . $oldAvatar);
- }
- return true;
- }
- }
- return false;
- }
- /**
- * 修改账号
- * @param $userId
- * @param $params
- * @return bool
- */
- public function modify($userId, $params)
- {
- $email = isset($params['email']) ? $params['email'] : '';
- $mobile = isset($params['mobile']) ? $params['mobile'] : '';
- $password = isset($params['password']) ? $params['password'] : '';
- $payPassword = isset($params['pay_password']) ? $params['pay_password'] : '';
- $type = isset($params['type'])? trim($params['type']) : '';
- $scene = isset($params['scene'])? trim($params['scene']) : '';
- if($type != 'profile' && empty($email) && empty($mobile)){
- $this->error = 1064;
- return false;
- }
- // 用户验证
- $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
- if (!$info) {
- $this->error = 2001;
- return false;
- }
- // 使用状态校验
- if ($info['status'] != 1) {
- $this->error = 2009;
- return false;
- }
- // 密码校验
- $data = ['update_time' => time()];
- // 验证交易密码
- if(isset($params['pay_password']) && $scene != 'trade'){
- $userPayPassword = isset($info['pay_password'])? $info['pay_password'] : '';
- if(empty($userPayPassword)){
- $this->error = 1040;
- return false;
- }
- if($userPayPassword != get_password($payPassword)){
- $this->error = 2038;
- return false;
- }
- }
- // 邀请人绑定
- $parent = isset($info['parent'])? $info['parent'] : [];
- $userParentCode = isset($parent['code'])? $parent['code'] : '';
- $userCode = isset($info['code'])? $info['code'] : '';
- $parentCode = isset($params['parent_code'])? trim($params['parent_code']) : '';
- if(isset($params['parent_code']) && $parentCode){
- //
- if($userParentCode){
- $this->error = 2451;
- return false;
- }
- if(($userCode == $parentCode)){
- $this->error = 2452;
- return false;
- }
- // 推荐人验证
- $inviteInfo = $this->model->where(['code' => $parentCode, 'mark' => 1])
- ->select(['id', 'parents', 'parent_id','trc_url'])
- ->first();
- $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
- $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
- if(!$parentId){
- $this->error = 2453;
- return false;
- }
- // 验证是否绑定用户为自己线下用户
- if(preg_match("/{$userId},/", $parents)){
- $this->error = 2454;
- return false;
- }
- // 推荐人
- $data['parent_id'] = $parentId;
- $data['parents'] = $parents;
- // 挂靠节点
- if($parentId>0){
- $pointId = $this->getPointParentId($parentId);
- if($pointId){
- $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
- $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
- $data['point_id'] = $pointId;
- $data['points'] = $points;
- }
- }
- }
- // 邮箱验证
- if (isset($params['email']) && $email) {
- // 修改邮箱
- $newEmail = isset($params['new_email'])? trim($params['new_email']) : '';
- if(isset($params['new_email']) && $newEmail){
- $data['email'] = $newEmail;
- $data['username'] = $newEmail;
- $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first();
- if ($checkInfo && $checkInfo['id'] != $userId) {
- $this->error = 2005;
- return false;
- }
- }
- // 邮箱验证码
- $code = isset($params['code'])? trim($params['code']) : '';
- $checkEmail = $scene == 'modify_email'? $newEmail : $email;
- if (!EmailService::make()->check($checkEmail, $code, $scene)) {
- $this->error = EmailService::make()->getError();
- return false;
- }
- }
- // 手机号验证
- if (isset($params['mobile']) && $mobile) {
- // 修改手机号
- $newMobile = isset($params['new_mobile'])? trim($params['new_mobile']) : '';
- if(isset($params['new_mobile']) && $newMobile){
- $data['mobile'] = $newMobile;
- $data['username'] = $newMobile;
- $checkInfo = $this->model->where(['mobile' => $newMobile, 'mark' => 1])->select(['id', 'status'])->first();
- if ($checkInfo && $checkInfo['id'] != $userId) {
- $this->error = 2005;
- return false;
- }
- }
- // 手机验证码
- $code = isset($params['code'])? trim($params['code']) : '';
- $checkMobile = $scene == 'modify_mobile'? $newMobile : $mobile;
- if (!SmsService::make()->check($checkMobile, $code, $scene)) {
- $this->error = SmsService::make()->getError();
- return false;
- }
- }
- $trcUrl = isset($params['trc_url'])? trim($params['trc_url']) : '';
- $userTrcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
- if(isset($params['trc_url']) && $trcUrl){
- if($trcUrl != $userTrcUrl){
- if($this->model->where(['trc_url'=> $trcUrl,'mark'=>1])->whereNotIn('id',[$userId])->value('id')){
- $this->error = 1048;
- return false;
- }
- if(!WalletService::make()->checkAddress($trcUrl)){
- $this->error = 1049;
- return false;
- }
- $data['trc_url'] = $trcUrl;
- }
- }
- // 修改数据
- $nickname = isset($params['nickname']) ? $params['nickname'] : '';
- if (isset($params['nickname']) && $nickname) {
- $data['nickname'] = $nickname;
- }
- $gender = isset($params['gender']) ? intval($params['gender']) : 3;
- if (isset($params['gender']) && $gender) {
- $data['gender'] = $gender;
- }
- $intro = isset($params['intro']) ? $params['intro'] : '';
- if (isset($params['intro']) && $intro) {
- $data['intro'] = $intro;
- }
- $birthday = isset($params['birthday_text']) ? $params['birthday_text'] : '';
- if (isset($params['birthday_text']) && $birthday) {
- $data['birthday'] = strtotime($birthday);
- }
- if (isset($params['pay_password']) && $payPassword) {
- $payPassword = get_password($payPassword);
- $data['pay_password'] = $payPassword;
- }
- if (isset($params['password']) && $password) {
- $password = get_password($password);
- $data['password'] = $password;
- }
- if($this->model->where(['id' => $userId])->update($data)){
- // 更新绑定上级后,团队用户全部更新
- if(isset($data['parent_id']) && $data['parent_id']){
- $updateData = ['parents'=>DB::raw("concat(parents,'{$data['parent_id']},')"),'update_time'=>time()];
- $this->model->where('parents','like',"%{$userId},")->update($updateData);
- }
- // 更新团队节点关系
- if(isset($data['point_id']) && $data['point_id']){
- $updateData = ['points'=>DB::raw("concat(points,'{$data['point_id']},')"),'update_time'=>time()];
- $this->model->where('points','like',"%{$userId},")->update($updateData);
- }
- $this->error = 1008;
- return true;
- }
- $this->error = 1008;
- return true;
- }
- /**
- * 找回密码
- * @param $userId
- * @param $params
- * @return bool
- */
- public function forget($params)
- {
- $email = isset($params['email']) ? $params['email'] : '';
- $mobile = isset($params['mobile']) ? $params['mobile'] : '';
- $password = isset($params['password']) ? $params['password'] : '';
- $type = isset($params['type'])? trim($params['type']) : '';
- $scene = isset($params['scene'])? trim($params['scene']) : '';
- if(empty($email) && empty($mobile)){
- $this->error = 1064;
- return false;
- }
- if (empty($password)){
- $this->error = 1065;
- return false;
- }
- // 用户验证
- if($mobile){
- $info = $this->model->with(['parent'])->where(['mobile' => $mobile, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
- }else{
- $info = $this->model->with(['parent'])->where(['email' => $email, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
- }
- if (!$info) {
- $this->error = 2001;
- return false;
- }
- // 使用状态校验
- if ($info['status'] != 1) {
- $this->error = 2009;
- return false;
- }
- // 邮箱验证
- if (isset($params['email']) && $email) {
- // 邮箱验证码
- $code = isset($params['code'])? trim($params['code']) : '';
- if (!EmailService::make()->check($email, $code, $scene)) {
- $this->error = EmailService::make()->getError();
- return false;
- }
- }
- // 手机号验证
- if (isset($params['mobile']) && $mobile) {
- // 手机验证码
- $code = isset($params['code'])? trim($params['code']) : '';
- if (!SmsService::make()->check($mobile, $code, $scene)) {
- $this->error = SmsService::make()->getError();
- return false;
- }
- }
- // 密码校验
- $data = ['update_time' => time()];
- if (isset($params['password']) && $password) {
- $password = get_password($password);
- $data['password'] = $password;
- }
- if($this->model->where(['id' => $info['id']])->update($data)){
- $this->error = 1013;
- return true;
- }
- $this->error = 1014;
- return true;
- }
- /**
- * 身份认证
- * @param $userId
- * @param $params
- * @return bool
- */
- public function auth($userId, $params)
- {
- // 用户验证
- $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first();
- if (!$info) {
- $this->error = 2001;
- return false;
- }
- // 使用状态校验
- if ($info['status'] != 1) {
- $this->error = 2009;
- return false;
- }
- // 密码校验
- $data = ['update_time' => time(),'idcard_check'=>1];
- if (isset($params['realname']) && $params['realname']) {
- $data['realname'] = trim($params['realname']);
- }
- $idcard = isset($params['idcard']) && $params['idcard'];
- if ($idcard) {
- $data['idcard'] = trim($params['idcard']);
- }
- if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) {
- $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']);
- }
- if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) {
- $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']);
- }
- $this->model->where(['id' => $userId])->update($data);
- // 发送消息
- $this->error = 2036;
- return true;
- }
- /**
- * 转账
- * @param $userId
- * @param $params
- * @return bool
- */
- public function transfer($userId, $params)
- {
- $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0;
- $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
- $money = isset($params['money'])? floatval($params['money']) : 0;
- if(empty($toUserId) || $money<=0){
- $this->error = 2420;
- return false;
- }
- $cacheKey = "caches:members:transfer:{$userId}";
- if(RedisService::get($cacheKey)){
- $this->error = 1034;
- return false;
- }
- // 验证账户
- $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','username','usdt','pay_password','balance','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
- $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
- $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : '';
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- // 余额支付支付密码验证
- if(empty($userPayPassword)){
- $this->error = 1040;
- return false;
- }
- $payPassword = get_password($payPassword);
- if($payPassword != $userPayPassword){
- $this->error = 2038;
- return false;
- }
- // 验证账户
- $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1])
- ->select(['id','nickname','usdt','username','balance','status'])
- ->first();
- $status = isset($accountInfo['status'])? $accountInfo['status'] : 0;
- $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0;
- $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : '';
- if(empty($accountInfo) || $status != 1){
- $this->error = 2421;
- return false;
- }
- if($money > $usdt){
- $this->error = 2422;
- return false;
- }
- // 用户余额转账到用户
- DB::beginTransaction();
- RedisService::set($cacheKey, $params, rand(2,5));
- $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()];
- if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){
- DB::rollBack();
- $this->error = 2028;
- RedisService::clear($cacheKey);
- return false;
- }
- // 明细
- $orderNo = get_order_num('TR');
- $log = [
- 'user_id' => $userId,
- 'source_id' => $toUserId,
- 'source_order_no' => $orderNo,
- 'type' => 6,
- 'coin_type' => 1,
- 'user_type'=> 1,
- 'money' => -$money,
- 'actual_money' => -$money,
- 'balance' => $usdt,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "USDT转账",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2423;
- RedisService::clear($cacheKey);
- return false;
- }
- // 到账
- $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5);
- $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0;
- $feeUsdt = round($money * $fee,2);
- $realUsdt = moneyFormat($money - $feeUsdt,2);
- $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()];
- if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){
- DB::rollBack();
- $this->error = 2424;
- RedisService::clear($cacheKey);
- return false;
- }
- // 明细
- $log = [
- 'user_id' => $toUserId,
- 'source_id' => $userId,
- 'source_order_no' => $orderNo,
- 'type' => 6,
- 'coin_type' => 1,
- 'user_type'=> 1,
- 'money' => $realUsdt,
- 'actual_money' => $realUsdt,
- 'balance' => $accountUsdt,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "USDT转账",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2029;
- RedisService::clear($cacheKey);
- return false;
- }
- // 平台明细
- $log = [
- 'user_id' => 0,
- 'source_id' => $userId,
- 'source_order_no' => $orderNo,
- 'type' => 6,
- 'coin_type' => 1,
- 'user_type'=> 4,
- 'money' => $feeUsdt,
- 'actual_money' => $feeUsdt,
- 'balance' => 0,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "USDT转账",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2029;
- RedisService::clear($cacheKey);
- return false;
- }
- // 平台
- FinanceService::make()->saveLog(0, $feeUsdt,1);
- // 消息
- $dateTime = date('Y-m-d H:i:s');
- MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3);
- $dateTime = date('Y-m-d H:i:s');
- MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3);
- DB::commit();
- RedisService::clear($cacheKey);
- $this->error = 2425;
- return true;
- }
- /**
- * 余额充值
- * @param $userId
- * @param $params
- * @return array|false
- */
- public function recharge($userId, $params)
- {
- $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
- $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0;
- $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
- $payType = 10;
- if($usdt<=0){
- $this->error = 2031;
- return false;
- }
- $cacheKey = "caches:member:recharge:lock_{$userId}";
- if(RedisService::get($cacheKey)){
- $this->error = 1034;
- return false;
- }
- $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','usdt','pay_password','balance','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
- $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
- $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- if($userPayPassword != get_password($payPassword)){
- $this->error = 2038;
- return false;
- }
- // 充值订单
- $orderNo = get_order_num('DR');
- $money = $usdt;
- // 星豆
- DB::beginTransaction();
- RedisService::set($cacheKey, $userInfo, rand(2,3));
- if($coinType == 2){
- $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
- $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100;
- $money = round($xdPrice * $usdt,2);
- if($usdt > $userUsdt){
- $this->error = 2035;
- RedisService::clear($cacheKey);
- return false;
- }
- // 扣除usdt余额
- $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()];
- if(!$this->model->where(['id'=> $userId])->update($updateData)){
- RedisService::clear($cacheKey);
- $this->error = 2036;
- DB::rollBack();
- return false;
- }
- }
- $data = [
- 'order_no'=> $orderNo,
- 'user_id'=> $userId,
- 'type'=> 1,
- 'user_type'=> 1,
- 'coin_type'=> 2,
- 'money'=> $usdt,
- 'actual_money'=> $money,
- 'pay_type'=> $payType,
- 'pay_status'=> 20,
- 'pay_at'=> date('Y-m-d H:i:s'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'status'=> 2,
- 'mark'=> 1,
- ];
- if(!$orderId = BalanceLogModel::insertGetId($data)){
- RedisService::clear($cacheKey);
- $this->error = 2033;
- DB::rollBack();
- return false;
- }
- // 扣除USDT
- $log = [
- 'user_id'=> $userId,
- 'source_order_no'=> $data['order_no'],
- 'user_type'=> 1,
- 'type'=> 5,
- 'coin_type'=> 1,
- 'money'=> -$usdt,
- 'actual_money'=> -$usdt,
- 'balance'=> $userUsdt,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'remark'=> '星豆余额充值扣除',
- 'status'=>1,
- 'mark'=>1
- ];
- if(!AccountLogModel::insertGetId($log)){
- RedisService::clear($cacheKey);
- $this->error = 2029;
- DB::rollBack();
- return false;
- }
- // 增加星豆余额
- $log = [
- 'user_id'=> $userId,
- 'source_order_no'=> $data['order_no'],
- 'user_type'=> 1,
- 'type'=> 5,
- 'coin_type'=> 2,
- 'money'=> $usdt,
- 'actual_money'=> $money,
- 'balance'=> $balance,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'remark'=> '星豆余额充值',
- 'status'=>1,
- 'mark'=>1
- ];
- if(!AccountLogModel::insertGetId($log)){
- RedisService::clear($cacheKey);
- $this->error = 2029;
- DB::rollBack();
- return false;
- }
- // 消息
- $dateTime = date('Y-m-d H:i:s');
- MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3);
- DB::commit();
- // 充值星豆任务
- TaskService::make()->updateTask($userId,9, 0);
- $this->error = 2037;
- RedisService::clear($cacheKey);
- return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)];
- }
- /**
- * 余额提现
- * @param $userId
- * @param $params
- * @return array|false
- */
- public function withdraw($userId, $params)
- {
- $money = isset($params['money'])? floatval($params['money']) : 0;
- $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
- $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1;
- if($money<=0){
- $this->error = 2401;
- return false;
- }
- if(!in_array($userType,[1,2])){
- $this->error = 2404;
- return false;
- }
- $userInfo = $this->model->with(['merchant'])
- ->where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','usdt','trc_url','pay_password','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
- $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
- $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : [];
- $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0;
- $merchantId = isset($merchant['id'])? $merchant['id'] : 0;
- $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0;
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){
- $this->error = 2024;
- return false;
- }
- // 提现金额验证
- $accountUsdt = $userType==1? $userUsdt : $merchantUsdt;
- if ($money > $accountUsdt) {
- $this->error = web_lang(2402, ['money' => $accountUsdt]);
- return false;
- }
- // 提现账户
- $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
- if (empty($trcUrl)) {
- $this->error = 2403;
- return false;
- }
- // 提现验证usdt钱包余额
- $balance = (new \App\Services\WalletService)->getTrcUsdtBalance($userInfo['trc_url']);
- if($balance < $money){
- $this->error = web_lang(2402, ['trcUsdtBalance' => $balance]);
- return false;
- }
- if($userPayPassword != get_password($payPassword)){
- $this->error = 2038;
- return false;
- }
- $cacheKey = "caches:member:withdraw:lock_{$userId}";
- if(RedisService::get($cacheKey)){
- $this->error = 1034;
- return false;
- }
- DB::beginTransaction();
- RedisService::set($cacheKey, $userInfo, rand(2,3));
- // 提现记录
- $orderNo = get_order_num('DW');
- $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5);
- $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0;
- $fee = round($money*$feeRate, 2);
- $realUsdt = moneyFormat($money - $fee, 2);
- $data = [
- 'order_no'=> $orderNo,
- 'user_id'=> $userType==1? $userId : $merchantId,
- 'type'=> 2,
- 'user_type'=> $userType,
- 'coin_type'=> 1,
- 'money'=> $money,
- 'actual_money'=> $realUsdt,
- 'fee'=> $fee,
- 'trc_url'=> $trcUrl,
- 'pay_type'=> 20,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'status'=> 1,
- 'mark'=> 1,
- ];
- if(!$id = BalanceLogModel::insertGetId($data)){
- DB::rollBack();
- $this->error = 2405;
- RedisService::clear($cacheKey);
- return false;
- }
- // 商户扣款
- if($userType == 2){
- $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
- if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){
- DB::rollBack();
- $this->error = 2406;
- RedisService::clear($cacheKey);
- return false;
- }
- // 明细
- $log = [
- 'user_id' => $merchantId,
- 'source_id' => $userId,
- 'source_order_no' => $orderNo,
- 'type' => 5,
- 'coin_type' => 1,
- 'user_type'=> 2,
- 'money' => -$money,
- 'actual_money' => -$money,
- 'balance' => $merchantUsdt,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "商户账户余额提现",
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($log)) {
- $this->error = 2407;
- DB::rollBack();
- RedisService::clear($cacheKey);
- return false;
- }
- }
- // 用户扣款
- else{
- $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
- if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
- DB::rollBack();
- $this->error = 2406;
- RedisService::clear($cacheKey);
- return false;
- }
- // 明细
- $log = [
- 'user_id' => $userId,
- 'source_id' => 0,
- 'source_order_no' => $orderNo,
- 'type' => 5,
- 'coin_type' => 1,
- 'user_type'=> 1,
- 'money' => -$money,
- 'actual_money' => -$money,
- 'balance' => $userUsdt,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "USDT余额提现",
- 'status' => 1,
- 'mark' => 1,
- ];
- if (!AccountLogModel::insertGetId($log)) {
- $this->error = 2407;
- DB::rollBack();
- RedisService::clear($cacheKey);
- return false;
- }
- }
- DB::commit();
- // 站内消息
- $dateTime = date('Y-m-d H:i:s');
- $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功';
- $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!";
- MessageService::make()->pushMessage($userId, $title, $message);
- // 提现自动审核,低于该金额自动审核
- $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300);
- $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0;
- if ($money <= $autoCheckUsdt) {
- // 打款处理
- $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realUsdt);
- $txID = isset($result['txId']) ? $result['txId'] : '';
- $payAddress = isset($result['address']) ? $result['address'] : '';
- if ($txID && $payAddress) {
- $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()];
- if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){
- $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功';
- $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!";
- MessageService::make()->pushMessage($userId, $title, $message);
- AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]);
- // 平台明细
- $log = [
- 'user_id' => 0,
- 'source_id' => $userId,
- 'source_order_no' => $orderNo,
- 'type' => 5,
- 'coin_type' => 1,
- 'user_type'=> 4,
- 'money' => $fee,
- 'actual_money' => $fee,
- 'balance' => 0,
- 'create_time' => time(),
- 'update_time' => time(),
- 'hash' => $txID,
- 'remark' => "USDT余额提现",
- 'status' => 1,
- 'mark' => 1,
- ];
- AccountLogModel::insertGetId($log);
- // 平台流水
- FinanceService::make()->saveLog(0, $fee, 1);
- }
- }
- }
- $this->error = $title;
- RedisService::clear($cacheKey);
- return [
- 'id'=> $id,
- 'money'=> $money,
- 'user_type'=> $userType,
- ];
- }
- /**
- * 获取点对点上级节点
- * @param $userId 推荐人ID
- * @return int|mixed
- */
- public function getPointParentId($userId)
- {
- if($userId<=0){
- return 0;
- }
- $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get();
- $userList = $userList? $userList->toArray() : [];
- if(count($userList) < 3){
- return $userId;
- }
- $users = [];
- foreach($userList as $item){
- $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
- $points = array_filter($points);
- $users[$item['id']]['pointLen'] = count($points);
- $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
- $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
- }
- //var_dump($users);
- $pointId = 0;
- $tempPointLen = 0;
- $tempChildren = 0;
- foreach ($userList as $item) {
- $id = isset($item['id'])? $item['id'] : 0;
- $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
- $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
- //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren);
- if($pointLen<=$tempPointLen || $pointId == 0){
- //var_dump($id.'++'.$pointLen.'--'.$children."\n\n");
- if($children <$tempChildren || $pointId == 0){
- $pointId = $id;
- $tempPointLen = $pointLen;
- $tempChildren = $children;
- }
- }
- }
- return $pointId;
- }
- /**
- * DAO升级购买
- * @param $userId 用户ID
- * @param $params 参数:level-等级,pay_password-交易密码
- * @return bool
- */
- public function upgrade($userId, $params)
- {
- $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
- $level = isset($params['level'])? intval($params['level']) : 0;
- if($level<=0 || empty($payPassword)){
- $this->error = 2014;
- return false;
- }
- $cacheKey = "caches:members:upgrade:buy_{$userId}_{$level}";
- if(RedisService::get($cacheKey.'_lock')){
- $this->error = 1034;
- return false;
- }
- $levelInfo = MemberLevelModel::from('member_level as a')
- ->where(['a.id'=> $level,'a.status'=>1,'a.mark'=>1])
- ->select(['a.*'])
- ->first();
- $upgradeUsdt = isset($levelInfo['upgrade_usdt'])? floatval($levelInfo['upgrade_usdt']) : 0;
- $upgradeProfit = isset($levelInfo['upgrade_profit'])? floatval($levelInfo['upgrade_profit']) : 0;
- $boxNum = isset($levelInfo['box_num'])? intval($levelInfo['box_num']) : 0;
- $levelName = isset($levelInfo['name'])? $levelInfo['name'] : '';
- if(empty($levelInfo)){
- $this->error = 2511;
- return false;
- }
- $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','trc_url','pay_password','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
- $userTotalProfit = isset($userInfo['upgrade_profit_total'])? $userInfo['upgrade_profit_total'] : 0;
- $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
- $userWaitScore = isset($userInfo['wait_score'])? $userInfo['wait_score'] : 0;
- $userPowerNum = isset($userInfo['power_num'])? $userInfo['power_num'] : 0;
- $userLevel = isset($userInfo['member_level'])? intval($userInfo['member_level']) : 0;
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- if($userLevel>= $level){
- $this->error = 2512;
- return false;
- }
- if($level >= 30){
- $this->error = 2513;
- return false;
- }
- // 收益是否满足条件
- if($upgradeProfit>0 && $userTotalProfit < $upgradeProfit){
- $this->error = 2514;
- return false;
- }
- if(AccountLogModel::where(['user_id'=> $userId,'source_id'=> $level,'type'=>2,'coin_type'=>1,'status'=>1,'mark'=>1])->value('id')){
- $this->error = 2512;
- return false;
- }
- // USDT余额是否足够
- if($userUsdt < $upgradeUsdt){
- $this->error = 2035;
- return false;
- }
- // 交易密码
- if(empty($userPayPassword)){
- $this->error = 1040;
- return false;
- }
- if($userPayPassword != get_password($payPassword)){
- $this->error = 2038;
- return false;
- }
- // 购买明细
- RedisService::set($cacheKey, $params, rand(2,3));
- $orderNo = get_order_num('UP');
- DB::beginTransaction();
- $log = [
- 'user_id' => $userId,
- 'source_id' => $level,
- 'source_order_no' => $orderNo,
- 'type' => 2,
- 'coin_type' => 1,
- 'user_type'=> 1,
- 'money' => -$upgradeUsdt,
- 'actual_money' => -$upgradeUsdt,
- 'balance' => $userUsdt,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "购买{$levelName}升级",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2029;
- RedisService::clear($cacheKey);
- return false;
- }
- // 待返积分
- $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
- $xdPrice = $xdPrice>0 && $xdPrice<=10000? $xdPrice : 100;
- $waitScoreRate = ConfigService::make()->getConfigByCode('upgrade_award_score_rate', 200);
- $waitScoreRate = $waitScoreRate>0 && $waitScoreRate<=1000? $waitScoreRate : 0;
- $waitScore = moneyFormat($upgradeUsdt * $xdPrice * $waitScoreRate/100, 2);
- if($waitScore>0){
- $log = [
- 'user_id' => $userId,
- 'source_id' => $level,
- 'source_order_no' => $orderNo,
- 'type' => 9,
- 'coin_type' => 5,
- 'user_type'=> 1,
- 'money' => $waitScore,
- 'actual_money' => $waitScore,
- 'balance' => $userWaitScore,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "购买{$levelName}升级",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2029;
- RedisService::clear($cacheKey);
- return false;
- }
- }
- // 算力明细
- $powerNum = $upgradeUsdt;
- $log = [
- 'user_id' => $userId,
- 'source_id' => $level,
- 'source_order_no' => $orderNo,
- 'type' => 9,
- 'coin_type' => 3,
- 'user_type'=> 1,
- 'money' => $powerNum,
- 'actual_money' => $powerNum,
- 'balance' => $userPowerNum,
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => "购买{$levelName}升级",
- 'status' => 1,
- 'mark' => 1,
- ];
- if(!AccountLogModel::insertGetId($log)){
- DB::rollBack();
- $this->error = 2029;
- RedisService::clear($cacheKey);
- return false;
- }
- // 账户
- $updateData = [
- 'usdt'=> DB::raw("usdt - {$upgradeUsdt}"), // 扣除USDT
- 'member_level'=> $level, // 升级等级
- 'box_num'=>DB::raw("box_num + {$boxNum}"), // 奖励盲盒数量
- 'wait_score'=>DB::raw("wait_score + {$waitScore}"), // 待返积分奖励
- 'power_num'=>DB::raw("power_num + {$powerNum}"), // 算力奖励
- 'update_time'=>time()
- ];
- if(!MemberModel::where(['id'=> $userId])->update($updateData)){
- DB::rollBack();
- $this->error = 2036;
- RedisService::clear($cacheKey);
- return false;
- }
- // 消息
- $dateTime = date('Y-m-d H:i:s');
- MessageService::make()->pushMessage($userId,"购买{$levelName}升级成功","您在{$dateTime}(UTC+8)成功支付{$upgradeUsdt}USDT购买【{$levelName}】升级成功。",3);
- DB::commit();
- // 算力统计
- AccountLogService::make()->saveCount($userId, $powerNum, 1);
- // 业绩统计
- AccountLogService::make()->saveCount($userId, $upgradeUsdt, 2);
- // 结算收益奖励
- FinanceService::make()->settleBonus($userId, $userInfo, $upgradeUsdt, $orderNo, "购买{$levelName}");
- $this->error = 2503;
- RedisService::clear($cacheKey);
- return true;
- }
- /**
- * 盲盒抽奖
- * @param $userId 抽奖用户ID
- * @param $params
- * @return bool
- */
- public function draw($userId, $params)
- {
- $cacheKey="caches:members:draw_{$userId}";
- if(RedisService::get($cacheKey.'_lock')){
- $this->error = 1034;
- return false;
- }
- $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
- ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','box_num','trc_url','pay_password','status'])
- ->first();
- $status = isset($userInfo['status'])? $userInfo['status'] : 0;
- $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
- $boxNum = isset($userInfo['box_num'])? $userInfo['box_num'] : 0;
- if(empty($userInfo) || $status != 1){
- $this->error = 2024;
- return false;
- }
- if($boxNum <= 0){
- $this->error = 3101;
- return false;
- }
- // 中奖结果
- $drawRate = ConfigService::make()->getConfigByCode('box_award_rate',20);
- $drawRate = $drawRate>0 && $drawRate<100? $drawRate : 20;
- $drawMachineExpireDay = ConfigService::make()->getConfigByCode('draw_machine_time',30);
- $drawMachineExpireDay = $drawMachineExpireDay>0 && $drawMachineExpireDay<360? $drawMachineExpireDay : 30;
- DB::beginTransaction();
- // 扣除次数
- $updateData = ['box_num'=> DB::raw("box_num -1"),'update_time'=>time()];
- if(!$this->model->where(['id'=> $userId])->update($updateData)){
- DB::rollBack();
- $this->error = 3102;
- return false;
- }
- // 是否中奖
- $isAward = false;
- $randNum = rand(1000,9999);
- if($randNum > $drawRate * 10000/100){
- $isAward = true;
- }
- // 未中奖,直接推送消息
- if(!$isAward){
- DB::commit();
- // 消息
- $dateTime = date('Y-m-d H:i:s');
- MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【未中奖】,请继续加油。",3);
- $this->error = 3107;
- return ['id'=>0,'num'=>$randNum];
- }
- // 随机获取算力机
- $machineInfo = MachineModel::where(['is_draw'=>1,'status'=>1,'mark'=>1])
- ->select(['id as machine_id','name','price','power','month_rate','sl','day_wait_score','day_xd','day_score'])
- ->orderBy(DB::raw('RAND()'))
- ->first();
- $machineInfo = $machineInfo? $machineInfo->toArray() : [];
- $machineName = isset($machineInfo['name'])? $machineInfo['name'] : '';
- if(empty($machineInfo)){
- DB::rollBack();
- $this->error = 3103;
- return false;
- }
- $orderNo = get_order_num('DM');
- $machineInfo['user_id'] = $userId;
- $machineInfo['order_no'] = $orderNo;
- $machineInfo['create_time'] = time();
- $machineInfo['status'] = 1;
- $machineInfo['mark'] = 1;
- // 有效期
- if($drawMachineExpireDay>0){
- $machineInfo['expired_at'] = date('Y-m-d H:i:s', time() + $drawMachineExpireDay * 86400);
- }
- unset($machineInfo['name']);
- if(!$id = DrawLogModel::insertGetId($machineInfo)){
- DB::rollBack();
- $this->error = 3102;
- return false;
- }
- // 抽奖完成
- DB::commit();
- // 消息
- $dateTime = date('Y-m-d H:i:s');
- $machineName = $machineName? $machineName : '算力矿机';
- MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【已中奖】一台{$machineName},请查看您的矿机列表查收。",3);
- $this->error = web_lang('3106',['name'=>$machineName]);
- return ['id'=> $id,'name'=> $machineName,'num'=> $randNum];
- }
- /**
- * 我的矿机(中奖记录)
- * @param $userId
- * @param $params
- * @param int $pageSize
- * @return array
- */
- public function getMachineList($userId, $params, $pageSize=15)
- {
- $page = request()->post('page',1);
- $cacheKey = "caches:machine:list_{$userId}_{$page}_".md5(json_encode($params,256));
- $datas = RedisService::get($cacheKey);
- if ($datas) {
- return [
- 'pageSize' => $pageSize,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => isset($datas['data']) ? $datas['data'] : []
- ];
- }
- $where = ['a.status' => 1,'a.user_id'=> $userId, 'a.mark' => 1,'b.mark'=>1];
- $field = ['a.*','b.name'];
- $datas = DrawLogModel::from('draw_logs as a')
- ->leftjoin('machine as b','b.id','=','a.machine_id')
- ->where($where)
- ->where(function($query) use($params){
- $type = isset($params['type'])? $params['type'] : 0;
- if($type == 1){
- $query->where('a.expired_at','>=', date('Y-m-d H:i:s'));
- }else if ($type == 2){
- $query->where('a.expired_at','<', date('Y-m-d H:i:s'));
- }
- })
- ->select($field)
- ->orderBy('a.create_time', 'desc')
- ->orderBy('a.expired_at', 'desc')
- ->paginate($pageSize > 0 ? $pageSize : 9999999);
- $datas = $datas ? $datas->toArray() : [];
- if ($datas) {
- RedisService::set($cacheKey, $datas, rand(3, 5));
- }
- return [
- 'pageSize' => $pageSize,
- 'total' => isset($datas['total']) ? $datas['total'] : 0,
- 'list' => isset($datas['data']) ? $datas['data'] : []
- ];
- }
- }
|