MemberService.php 77 KB

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