MemberService.php 75 KB

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