MemberService.php 77 KB

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