MemberService.php 77 KB

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