MemberService.php 77 KB

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