| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062 |
- <?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('YmdHis'), 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('YmdHis'), 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);
- var_dump($str);
- $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,
- 'auth_time'=> isset($data[2]) && $data[2]? $data[2] : 0,
- ];
- }
- }
- /**
- * 获取用户缓存信息
- * @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'] : []
- ];
- }
- }
|