MemberService.php 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  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\MemberCollectModel;
  21. use App\Models\MemberLevelModel;
  22. use App\Models\MemberModel;
  23. use App\Models\MerchantModel;
  24. use App\Models\MessageModel;
  25. use App\Models\VideoModel;
  26. use App\Services\BaseService;
  27. use App\Services\CityService;
  28. use App\Services\ConfigService;
  29. use App\Services\EmailService;
  30. use App\Services\RedisService;
  31. use App\Services\SmsService;
  32. use App\Services\ToolService;
  33. use App\Services\UdunpayService;
  34. use App\Services\WalletService;
  35. use Illuminate\Support\Facades\DB;
  36. use phpQrcode\QRcode;
  37. /**
  38. * 会员管理-服务类
  39. * @author laravel开发员
  40. * @since 2020/11/11
  41. * Class MemberService
  42. * @package App\Services\Api
  43. */
  44. class MemberService extends BaseService
  45. {
  46. // 静态对象
  47. protected static $instance = null;
  48. /**
  49. * 构造函数
  50. * @author laravel开发员
  51. * @since 2020/11/11
  52. * MemberService constructor.
  53. */
  54. public function __construct()
  55. {
  56. $this->model = new MemberModel();
  57. }
  58. /**
  59. * 静态入口
  60. * @return MemberService|static|null
  61. */
  62. public static function make()
  63. {
  64. if (!self::$instance) {
  65. self::$instance = new static();
  66. }
  67. return self::$instance;
  68. }
  69. /**
  70. * 获取资料详情
  71. * @param $where
  72. * @param array $field
  73. */
  74. public function getInfo($where, $type = 'detail', array $field = [], $userId=0)
  75. {
  76. $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'];
  77. $withs = ['merchant','acceptor','parent','point','level'];
  78. if ($type == 'team') {
  79. $defaultField = ['id', 'username','email','member_level', 'nickname','usdt', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar'];
  80. }else if($type == 'share'){
  81. $withs = ['parent','level'];
  82. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar'];
  83. }else if($type == 'check'){
  84. $withs = ['parent','level'];
  85. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar'];
  86. }else if ($type == 'info'){
  87. $withs = ['parent','level'];
  88. }else if ($type == 'chat'){
  89. $withs = [];
  90. }
  91. $field = $field ? $field : $defaultField;
  92. if (is_array($where)) {
  93. $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first();
  94. } else {
  95. $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first();
  96. }
  97. $info = $info ? $info->toArray() : [];
  98. if ($info && !in_array($type, ['auth', 'check','login','chat'])) {
  99. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  100. $info['balance'] = moneyFormat($info['balance'], 2);
  101. $info['usdt'] = isset($info['usdt'])?moneyFormat($info['usdt'], 2):'0.00';
  102. $info['score'] = moneyFormat($info['score'], 2);
  103. $info['merchant'] = isset($info['merchant']) && $info['merchant']? $info['merchant'] : ['id'=>0];
  104. $info['acceptor'] = isset($info['acceptor']) && $info['acceptor']? $info['acceptor'] : ['id'=>0];
  105. $info['level'] = isset($info['level']) && $info['level']? $info['level'] : ['id'=>0,'name'=>'普通用户'];
  106. $info['custom_phone'] = ConfigService::make()->getConfigByCode('custom_phone');
  107. $info['custom_url'] = ConfigService::make()->getConfigByCode('custom_url');
  108. $info['custom_email'] = ConfigService::make()->getConfigByCode('custom_email');
  109. if(isset($info['birthday'])){
  110. $info['birthday_text'] = $info['birthday']? date('Y-m-d',$info['birthday']) : '';
  111. }
  112. // 二维码
  113. if (in_array($type, ['detail'])) {
  114. $info['parent_code'] = '';
  115. $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无'];
  116. if($info['parent']['id']>0){
  117. $info['parent_code'] = isset($info['parent']['code'])? $info['parent']['code'] :'';
  118. }
  119. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  120. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  121. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  122. if($userId != $info['id']){
  123. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  124. }else{
  125. $info['is_follow'] = 1;
  126. }
  127. $info['app_version'] = ConfigService::make()->getConfigByCode('app_version');
  128. $info['chat_token'] = MemberService::make()->getChatToken($info['id'].'@1@'.date('YmdHis'), 1);
  129. }
  130. else if ($type == 'info') {
  131. $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0);
  132. $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0;
  133. $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0;
  134. $info['chat_token'] = MemberService::make()->getChatToken($info['id'].'@1@'.date('YmdHis'), 1);
  135. }else if($type == 'buy'){
  136. $address = MemberAddressService::make()->getBindInfo($userId);
  137. $info['address'] = $address;
  138. $streetCode = isset($address['street_code'])? $address['street_code'] : '';
  139. $info['freight_address_id'] = $streetCode? $streetCode : (isset($address['district_code'])? $address['district_code'] : '');
  140. $info['address_id'] = isset($address['id'])? $address['id'] : 0;
  141. $info['cart_num'] = GoodsService::make()->getCartCount($info['id']);
  142. }else if($type == 'upgrade'){
  143. $level = isset($info['level'])? $info['level'] : [];
  144. $nextLevel = MemberLevelModel::where('id','>', $info['member_level'])->orderBy('id','asc')->first();
  145. $info['next_level'] = isset($nextLevel['id']) && $nextLevel['id']? $nextLevel['id'] : $info['member_level'];
  146. $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);
  147. $info['next_level_usdt'] = isset($nextLevel['upgrade_usdt']) && $nextLevel['upgrade_usdt']? $nextLevel['upgrade_usdt'] : (isset($level['upgrade_usdt'])? $level['upgrade_usdt']:0);
  148. $info['next_level_name'] = isset($nextLevel['name'])? $nextLevel['name'] : (isset($level['name'])? $level['name']:'');
  149. }
  150. else if ($type == 'recharge') {
  151. $wallet = WalletService::make()->getWallet(1);
  152. $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : '';
  153. $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100);
  154. if($info['recharge_trc_url']){
  155. $qrcode = $this->makeQrcode($info['recharge_trc_url']);
  156. $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  157. }else{
  158. $info['trc_qrcode'] = '';
  159. }
  160. }
  161. else if ($type == 'team' || $type == 'share') {
  162. $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']);
  163. $qrcode = $this->makeQrcode($inviteUrl);
  164. $info['qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  165. $info['invite_url'] = $inviteUrl;
  166. $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):'';
  167. $info['qrcode_header'] = get_image_url('/images/qrcode/qrcode-header.png');
  168. $info['qrcode_header_base64'] = getImageContent('/images/qrcode/qrcode-header.png');
  169. $info['qrcode_bg'] = get_image_url('/images/qrcode/qrcode-bg.png');
  170. $info['qrcode_bg_base64'] = getImageContent('/images/qrcode/qrcode-bg.png');
  171. $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数
  172. $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数
  173. $info['team_count'] = $this->getUserCountByType($info['id'], 2, 0); // 团队人数
  174. }else {
  175. // 默认地址
  176. $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']);
  177. }
  178. }
  179. return $info;
  180. }
  181. /**
  182. * 获取主页信息
  183. * @param $where
  184. * @param array $field
  185. */
  186. public function getHomeInfo($id, $userId=0)
  187. {
  188. $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'];
  189. $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first();
  190. $info = $info ? $info->toArray() : [];
  191. if ($info) {
  192. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  193. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  194. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  195. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  196. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  197. $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝
  198. $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播
  199. }
  200. return $info;
  201. }
  202. /**
  203. * 获取聊天TOKEN或者解码用户ID
  204. * @param $key
  205. * @param $type
  206. * @return false|string|string[]
  207. */
  208. public function getChatToken($key, $type)
  209. {
  210. // 加密
  211. $salt = 'starLink';
  212. if ($type == 1) {
  213. $baseStr = base64_encode($salt.'|'.$key);
  214. $baseStr = str_replace(['==', '='], ['-2', '-1'], $baseStr);
  215. $str = substr($baseStr, -10) . substr(md5($salt), 2, 6) . substr($baseStr, 0, -10);
  216. return $str;
  217. } // 解密
  218. else {
  219. $str1 = substr($key, 16) . substr($key, 0, 10);
  220. $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
  221. $str = base64_decode($str1);
  222. $str = str_replace("{$salt}|",'', $str);
  223. $data = explode('@', $str);
  224. return [
  225. 'user_id'=> isset($data[0])? $data[0] : 0,
  226. 'user_type'=> isset($data[1]) && $data[1]? $data[1] : 1,
  227. 'auth_time'=> isset($data[2]) && $data[2]? $data[2] : 0,
  228. ];
  229. }
  230. }
  231. /**
  232. * 获取用户缓存信息
  233. * @param $where
  234. * @param array $field
  235. * @param int $expired
  236. * @return array|mixed
  237. */
  238. public function getCacheInfo($where, $field = [], $expired = 0)
  239. {
  240. $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired);
  241. $info = RedisService::get($cacheKey);
  242. if ($info) {
  243. return $info;
  244. }
  245. $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar'];
  246. $field = $field ? $field : $defaultField;
  247. $info = $this->model->where($where)->where('mark', 1)->select($field)->first();
  248. $info = $info ? $info->toArray() : [];
  249. if ($info) {
  250. if (isset($info['avatar'])) {
  251. $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png';
  252. $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : '';
  253. }
  254. RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5));
  255. }
  256. return $info;
  257. }
  258. /**
  259. * 生成普通参数二维码
  260. * @param $str 参数
  261. * @param bool $refresh 是否重新生成
  262. * @return bool
  263. */
  264. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  265. {
  266. $basePath = base_path() . '/public';
  267. $qrFile = '/images/qrcode/';
  268. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  269. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  270. }
  271. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  272. $qrFile = $qrFile . "C_{$key}.png";
  273. $cacheKey = "caches:qrcodes:member_" . $key;
  274. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  275. return $qrFile;
  276. }
  277. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  278. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  279. return false;
  280. }
  281. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  282. return $qrFile;
  283. }
  284. /**
  285. * 获取团队用户数量
  286. * @param $userId 当前用户ID
  287. * @param int $type 层级:1-直推,2-团队
  288. * @param int $isPoint 节点:1-滑落推荐,0-直接推荐
  289. * @return array|mixed
  290. */
  291. public function getUserCountByType($userId, $type = 1, $isPoint=0)
  292. {
  293. $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}";
  294. $data = RedisService::get($cacheKey);
  295. if ($data) {
  296. return $data;
  297. }
  298. $where = ['status' => 1, 'mark' => 1];
  299. $data = $this->model->where($where)
  300. ->where(function ($query) use ($type, $isPoint, $userId) {
  301. if($isPoint){
  302. if ($type == 1) { // 滑落推荐
  303. $query->where('point_id', $userId);
  304. } else if($type == 2){ // 滑落团队人数
  305. $query->whereRaw('FIND_IN_SET(?,points)', $userId);
  306. }
  307. }else{
  308. if ($type == 1) { // 直推人数
  309. $query->where('parent_id', $userId);
  310. } else if($type == 2){ // 团队人数
  311. $query->whereRaw("FIND_IN_SET({$userId},parents)");
  312. } else if($type == 3){ // 滑落人数
  313. $query->where('parent_id', $userId)->where('point_id','!=', $userId);
  314. }
  315. }
  316. })->count('id');
  317. if ($data) {
  318. RedisService::set($cacheKey, $data, rand(3, 5));
  319. }
  320. return $data;
  321. }
  322. /**
  323. * 分销用户列表
  324. * @param $userId
  325. * @param $params
  326. * @param int $pageSize
  327. * @return array
  328. */
  329. public function getTeamList($userId, $params, $pageSize=15)
  330. {
  331. $page = request()->post('page',1);
  332. $cacheKey = "caches:teams:list_{$userId}_{$page}";
  333. $datas = RedisService::get($cacheKey);
  334. if ($datas) {
  335. return [
  336. 'pageSize' => $pageSize,
  337. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  338. 'list' => isset($datas['data']) ? $datas['data'] : []
  339. ];
  340. }
  341. $where = ['status' => 1, 'mark' => 1];
  342. $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status'];
  343. $datas = $this->model->with(['level'])->where($where)
  344. ->where(function ($query) use ($userId) {
  345. $query->where('parent_id', $userId);
  346. })
  347. ->where(function($query) use($params){
  348. $kw = isset($params['kw'])? trim($params['kw']) : '';
  349. if($kw){
  350. $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%");
  351. }
  352. })
  353. ->select($field)
  354. ->orderBy('create_time', 'desc')
  355. ->orderBy('id', 'desc')
  356. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  357. $datas = $datas ? $datas->toArray() : [];
  358. if ($datas) {
  359. foreach ($datas['data'] as &$item) {
  360. $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
  361. $item['avatar'] = get_image_url($item['avatar']);
  362. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : '';
  363. $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0;
  364. }
  365. unset($item);
  366. RedisService::set($cacheKey, $datas, rand(5, 10));
  367. }
  368. return [
  369. 'pageSize' => $pageSize,
  370. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  371. 'list' => isset($datas['data']) ? $datas['data'] : []
  372. ];
  373. }
  374. /**
  375. * 手机号是否已注册
  376. * @param $mobile
  377. * @return mixed
  378. */
  379. public function checkPhoneExists($mobile)
  380. {
  381. return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub
  382. }
  383. /**
  384. * 账号注册
  385. * @param $params
  386. * @return array|false
  387. */
  388. public function register($params)
  389. {
  390. // 授权
  391. $email = isset($params['email']) ? trim($params['email']) : '';
  392. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  393. $registerType = isset($params['type']) ? intval($params['type']) : 1;
  394. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  395. $code = isset($params['code']) ? trim($params['code']) : '';
  396. $scene = isset($params['scene']) ? $params['scene'] : '';
  397. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  398. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  399. if (empty($params) || $code <= 0 || !in_array($registerType,[1,2])) {
  400. $this->error = 2014;
  401. return false;
  402. }
  403. // 邮箱注册
  404. if($registerType == 1){
  405. if(empty($email)){
  406. $this->error = 2014;
  407. return false;
  408. }
  409. // 验证码
  410. if (!EmailService::make()->check($email, $code, $scene)) {
  411. $this->error = EmailService::make()->getError();
  412. return false;
  413. }
  414. // 验证是否注册
  415. if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){
  416. $this->error = 2009;
  417. return false;
  418. }
  419. }else if($registerType == 2){
  420. if(empty($mobile)){
  421. $this->error = 2014;
  422. return false;
  423. }
  424. // 验证码
  425. if (!SmsService::make()->check($mobile, $code, $scene)) {
  426. $this->error = SmsService::make()->getError();
  427. return false;
  428. }
  429. // 验证是否注册
  430. if($this->model->where(['mobile'=> $mobile,'mark'=>1])->value('id')){
  431. $this->error = 1058;
  432. return false;
  433. }
  434. }
  435. // 推荐人
  436. $parentId = 0;
  437. $pointId = 0;
  438. $parents = '';
  439. $points = '';
  440. if ($inviteCode) {
  441. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  442. ->select(['id', 'parents', 'parent_id'])
  443. ->first();
  444. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  445. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  446. // 挂靠节点
  447. if($parentId>0){
  448. $pointId = $this->getPointParentId($parentId);
  449. if($pointId){
  450. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  451. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  452. }
  453. }
  454. }
  455. // 注册
  456. $id = $this->model->max('id') + 1;
  457. $system = isset($params['system'])? $params['system'] : [];
  458. $ip = get_client_ip();
  459. $ipData = ToolService::make()->getIpAddress($ip,'');
  460. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  461. $city = isset($ipData['city'])? $ipData['city'] : '';
  462. $emailName = explode('@', $email)[0];
  463. $password = isset($params['password']) ? $params['password'] : 'xl123456';
  464. // 钱包
  465. $data = [
  466. 'parent_id' => $parentId,
  467. 'point_id' => $pointId,
  468. 'points' => $points,
  469. 'openid' => '',
  470. 'avatar' => '',
  471. 'nickname' => $nickname ? $nickname : 'XL'.substr($emailName?$emailName:substr($mobile,-8,8),-8,8),
  472. 'username' => $registerType==1? $email : $mobile,
  473. 'password' => get_password($password),
  474. 'code' => strtoupper(get_random_code(9, 'X', "{$id}")),
  475. 'email' => $email,
  476. 'mobile' => $mobile,
  477. 'recharge_trc_url' => '',
  478. 'parents' => $parents,
  479. 'province_id' => CityService::make()->getFieldByName($province),
  480. 'city_id' => CityService::make()->getFieldByName($city),
  481. 'city' => $city,
  482. 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '',
  483. 'device' => $appSources == 'android' ? 2 : 1,
  484. 'status' => 1,
  485. 'balance' => 0,
  486. 'score' => 0,
  487. 'mark' => 1,
  488. 'login_ip' => $ip,
  489. 'create_time' => time(),
  490. ];
  491. $userId = $this->model->insertGetId($data);
  492. $this->error = 2008;
  493. return [
  494. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  495. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']],
  496. ];
  497. }
  498. /**
  499. * 邮箱登录
  500. * @param $params
  501. * @return array|false
  502. */
  503. public function loginByEmail($params)
  504. {
  505. // 授权
  506. $email = isset($params['email']) ? $params['email'] : '';
  507. $code = isset($params['code']) ? $params['code'] : '';
  508. $scene = isset($params['scene']) ? $params['scene'] : '';
  509. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  510. $password = isset($params['password']) ? $params['password'] : '';
  511. if (empty($params) || empty($email) || empty($scene) ) {
  512. $this->error = 2014;
  513. return false;
  514. }
  515. // 验证是否注册,没有则注册
  516. $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status','password'])->first();
  517. $data = $data ? $data->toArray() : [];
  518. $userId = isset($data['id']) ? $data['id'] : 0;
  519. $status = isset($data['status']) ? $data['status'] : 0;
  520. if(empty($data) || $userId<=0){
  521. $this->error = 2001;
  522. return false;
  523. }
  524. if ($status != 1) {
  525. $this->error = 2015;
  526. return false;
  527. }
  528. if(!empty($password)){
  529. if(get_password($password) != $data['password']){
  530. $this->error = 3108;
  531. return false;
  532. }
  533. }else{
  534. // 验证码
  535. if (!EmailService::make()->check($email, $code, $scene)) {
  536. $this->error = EmailService::make()->getError();
  537. return false;
  538. }
  539. }
  540. // 获取登录授权token
  541. $jwt = new Jwt('jwt_dys_app');
  542. $token = $jwt->getToken($userId);
  543. // 结果返回
  544. $result = [
  545. 'access_token' => $token,
  546. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  547. ];
  548. // 用户信息
  549. $ip = get_client_ip();
  550. $updateData = [
  551. 'login_time' => time(),
  552. 'login_ip' => $ip,
  553. ];
  554. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  555. $ipData = ToolService::make()->getIpAddress($ip,'');
  556. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  557. $city = isset($ipData['city'])? $ipData['city'] : '';
  558. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  559. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  560. }
  561. $this->model->where(['id'=> $userId])->update($updateData);
  562. $this->error = 2004;
  563. $data['token'] = $token;
  564. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  565. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  566. return $result;
  567. }
  568. /**
  569. * 手机号登录
  570. * @param $params
  571. * @return array|false
  572. */
  573. public function loginByMobile($params)
  574. {
  575. // 授权
  576. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  577. $code = isset($params['code']) ? $params['code'] : '';
  578. $scene = isset($params['scene']) ? $params['scene'] : '';
  579. $password = isset($params['password']) ? $params['password'] : '';
  580. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  581. if (empty($params) || empty($mobile) || empty($scene) ) {
  582. $this->error = 2014;
  583. return false;
  584. }
  585. // 验证是否注册,没有则注册
  586. $data = $this->model->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'username','point_id','mobile', 'parent_id', 'code', 'status','password'])->first();
  587. $data = $data ? $data->toArray() : [];
  588. $userId = isset($data['id']) ? $data['id'] : 0;
  589. $status = isset($data['status']) ? $data['status'] : 0;
  590. if(empty($data) || $userId<=0){
  591. $this->error = 2001;
  592. return false;
  593. }
  594. if ($status != 1) {
  595. $this->error = 2015;
  596. return false;
  597. }
  598. if(!empty($password)){
  599. if(get_password($password) != $data['password']){
  600. $this->error = 3108;
  601. return false;
  602. }
  603. }else{
  604. // 验证码
  605. if (!SmsService::make()->check($mobile, $code, $scene)) {
  606. $this->error = SmsService::make()->getError();
  607. return false;
  608. }
  609. }
  610. // 获取登录授权token
  611. $jwt = new Jwt('jwt_dys_app');
  612. $token = $jwt->getToken($userId);
  613. // 结果返回
  614. $result = [
  615. 'access_token' => $token,
  616. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  617. ];
  618. // 用户信息
  619. $ip = get_client_ip();
  620. $updateData = [
  621. 'login_time' => time(),
  622. 'login_ip' => $ip,
  623. ];
  624. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  625. $ipData = ToolService::make()->getIpAddress($ip,'');
  626. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  627. $city = isset($ipData['city'])? $ipData['city'] : '';
  628. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  629. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  630. }
  631. $this->model->where(['id'=> $userId])->update($updateData);
  632. $this->error = 2004;
  633. $data['token'] = $token;
  634. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  635. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  636. return $result;
  637. }
  638. /**
  639. * 修改头像/商家logo/技师头像
  640. * @param $userId
  641. * @param $avatar
  642. * @return mixed
  643. */
  644. public function saveAvatar($userId, $avatar)
  645. {
  646. $type = request()->post('type', 1);
  647. if($type == 1){
  648. $oldAvatar = $this->model->where(['id' => $userId])->value('avatar');
  649. if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  650. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  651. @unlink(ATTACHMENT_PATH . $oldAvatar);
  652. }
  653. return true;
  654. }
  655. }else if($type == 2){
  656. $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo');
  657. if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) {
  658. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  659. @unlink(ATTACHMENT_PATH . $oldAvatar);
  660. }
  661. return true;
  662. }
  663. }
  664. return false;
  665. }
  666. /**
  667. * 修改账号
  668. * @param $userId
  669. * @param $params
  670. * @return bool
  671. */
  672. public function modify($userId, $params)
  673. {
  674. $email = isset($params['email']) ? $params['email'] : '';
  675. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  676. $password = isset($params['password']) ? $params['password'] : '';
  677. $payPassword = isset($params['pay_password']) ? $params['pay_password'] : '';
  678. $type = isset($params['type'])? trim($params['type']) : '';
  679. $scene = isset($params['scene'])? trim($params['scene']) : '';
  680. if($type != 'profile' && empty($email) && empty($mobile)){
  681. $this->error = 1064;
  682. return false;
  683. }
  684. // 用户验证
  685. $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
  686. if (!$info) {
  687. $this->error = 2001;
  688. return false;
  689. }
  690. // 使用状态校验
  691. if ($info['status'] != 1) {
  692. $this->error = 2009;
  693. return false;
  694. }
  695. // 密码校验
  696. $data = ['update_time' => time()];
  697. // 验证交易密码
  698. if(isset($params['pay_password']) && $scene != 'trade'){
  699. $userPayPassword = isset($info['pay_password'])? $info['pay_password'] : '';
  700. if(empty($userPayPassword)){
  701. $this->error = 1040;
  702. return false;
  703. }
  704. if($userPayPassword != get_password($payPassword)){
  705. $this->error = 2038;
  706. return false;
  707. }
  708. }
  709. // 邀请人绑定
  710. $parent = isset($info['parent'])? $info['parent'] : [];
  711. $userParentCode = isset($parent['code'])? $parent['code'] : '';
  712. $userCode = isset($info['code'])? $info['code'] : '';
  713. $parentCode = isset($params['parent_code'])? trim($params['parent_code']) : '';
  714. if(isset($params['parent_code']) && $parentCode){
  715. //
  716. if($userParentCode){
  717. $this->error = 2451;
  718. return false;
  719. }
  720. if(($userCode == $parentCode)){
  721. $this->error = 2452;
  722. return false;
  723. }
  724. // 推荐人验证
  725. $inviteInfo = $this->model->where(['code' => $parentCode, 'mark' => 1])
  726. ->select(['id', 'parents', 'parent_id','trc_url'])
  727. ->first();
  728. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  729. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  730. if(!$parentId){
  731. $this->error = 2453;
  732. return false;
  733. }
  734. // 验证是否绑定用户为自己线下用户
  735. if(preg_match("/{$userId},/", $parents)){
  736. $this->error = 2454;
  737. return false;
  738. }
  739. // 推荐人
  740. $data['parent_id'] = $parentId;
  741. $data['parents'] = $parents;
  742. // 挂靠节点
  743. if($parentId>0){
  744. $pointId = $this->getPointParentId($parentId);
  745. if($pointId){
  746. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  747. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  748. $data['point_id'] = $pointId;
  749. $data['points'] = $points;
  750. }
  751. }
  752. }
  753. // 邮箱验证
  754. if (isset($params['email']) && $email) {
  755. // 修改邮箱
  756. $newEmail = isset($params['new_email'])? trim($params['new_email']) : '';
  757. if(isset($params['new_email']) && $newEmail){
  758. $data['email'] = $newEmail;
  759. $data['username'] = $newEmail;
  760. $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first();
  761. if ($checkInfo && $checkInfo['id'] != $userId) {
  762. $this->error = 2005;
  763. return false;
  764. }
  765. }
  766. // 邮箱验证码
  767. $code = isset($params['code'])? trim($params['code']) : '';
  768. $checkEmail = $scene == 'modify_email'? $newEmail : $email;
  769. if (!EmailService::make()->check($checkEmail, $code, $scene)) {
  770. $this->error = EmailService::make()->getError();
  771. return false;
  772. }
  773. }
  774. // 手机号验证
  775. if (isset($params['mobile']) && $mobile) {
  776. // 修改手机号
  777. $newMobile = isset($params['new_mobile'])? trim($params['new_mobile']) : '';
  778. if(isset($params['new_mobile']) && $newMobile){
  779. $data['mobile'] = $newMobile;
  780. $data['username'] = $newMobile;
  781. $checkInfo = $this->model->where(['mobile' => $newMobile, 'mark' => 1])->select(['id', 'status'])->first();
  782. if ($checkInfo && $checkInfo['id'] != $userId) {
  783. $this->error = 2005;
  784. return false;
  785. }
  786. }
  787. // 手机验证码
  788. $code = isset($params['code'])? trim($params['code']) : '';
  789. $checkMobile = $scene == 'modify_mobile'? $newMobile : $mobile;
  790. if (!SmsService::make()->check($checkMobile, $code, $scene)) {
  791. $this->error = SmsService::make()->getError();
  792. return false;
  793. }
  794. }
  795. $trcUrl = isset($params['trc_url'])? trim($params['trc_url']) : '';
  796. $userTrcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  797. if(isset($params['trc_url']) && $trcUrl){
  798. if($trcUrl != $userTrcUrl){
  799. if($this->model->where(['trc_url'=> $trcUrl,'mark'=>1])->whereNotIn('id',[$userId])->value('id')){
  800. $this->error = 1048;
  801. return false;
  802. }
  803. if(!WalletService::make()->checkAddress($trcUrl)){
  804. $this->error = 1049;
  805. return false;
  806. }
  807. $data['trc_url'] = $trcUrl;
  808. }
  809. }
  810. // 修改数据
  811. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  812. if (isset($params['nickname']) && $nickname) {
  813. $data['nickname'] = $nickname;
  814. }
  815. $gender = isset($params['gender']) ? intval($params['gender']) : 3;
  816. if (isset($params['gender']) && $gender) {
  817. $data['gender'] = $gender;
  818. }
  819. $intro = isset($params['intro']) ? $params['intro'] : '';
  820. if (isset($params['intro']) && $intro) {
  821. $data['intro'] = $intro;
  822. }
  823. $birthday = isset($params['birthday_text']) ? $params['birthday_text'] : '';
  824. if (isset($params['birthday_text']) && $birthday) {
  825. $data['birthday'] = strtotime($birthday);
  826. }
  827. if (isset($params['pay_password']) && $payPassword) {
  828. $payPassword = get_password($payPassword);
  829. $data['pay_password'] = $payPassword;
  830. }
  831. if (isset($params['password']) && $password) {
  832. $password = get_password($password);
  833. $data['password'] = $password;
  834. }
  835. if($this->model->where(['id' => $userId])->update($data)){
  836. // 更新绑定上级后,团队用户全部更新
  837. if(isset($data['parent_id']) && $data['parent_id']){
  838. $updateData = ['parents'=>DB::raw("concat(parents,'{$data['parent_id']},')"),'update_time'=>time()];
  839. $this->model->where('parents','like',"%{$userId},")->update($updateData);
  840. }
  841. // 更新团队节点关系
  842. if(isset($data['point_id']) && $data['point_id']){
  843. $updateData = ['points'=>DB::raw("concat(points,'{$data['point_id']},')"),'update_time'=>time()];
  844. $this->model->where('points','like',"%{$userId},")->update($updateData);
  845. }
  846. $this->error = 1008;
  847. return true;
  848. }
  849. $this->error = 1008;
  850. return true;
  851. }
  852. /**
  853. * 找回密码
  854. * @param $userId
  855. * @param $params
  856. * @return bool
  857. */
  858. public function forget($params)
  859. {
  860. $email = isset($params['email']) ? $params['email'] : '';
  861. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  862. $password = isset($params['password']) ? $params['password'] : '';
  863. $type = isset($params['type'])? trim($params['type']) : '';
  864. $scene = isset($params['scene'])? trim($params['scene']) : '';
  865. if(empty($email) && empty($mobile)){
  866. $this->error = 1064;
  867. return false;
  868. }
  869. if (empty($password)){
  870. $this->error = 1065;
  871. return false;
  872. }
  873. // 用户验证
  874. if($mobile){
  875. $info = $this->model->with(['parent'])->where(['mobile' => $mobile, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
  876. }else{
  877. $info = $this->model->with(['parent'])->where(['email' => $email, 'mark' => 1])->select(['id','pay_password','parent_id','code', 'status'])->first();
  878. }
  879. if (!$info) {
  880. $this->error = 2001;
  881. return false;
  882. }
  883. // 使用状态校验
  884. if ($info['status'] != 1) {
  885. $this->error = 2009;
  886. return false;
  887. }
  888. // 邮箱验证
  889. if (isset($params['email']) && $email) {
  890. // 邮箱验证码
  891. $code = isset($params['code'])? trim($params['code']) : '';
  892. if (!EmailService::make()->check($email, $code, $scene)) {
  893. $this->error = EmailService::make()->getError();
  894. return false;
  895. }
  896. }
  897. // 手机号验证
  898. if (isset($params['mobile']) && $mobile) {
  899. // 手机验证码
  900. $code = isset($params['code'])? trim($params['code']) : '';
  901. if (!SmsService::make()->check($mobile, $code, $scene)) {
  902. $this->error = SmsService::make()->getError();
  903. return false;
  904. }
  905. }
  906. // 密码校验
  907. $data = ['update_time' => time()];
  908. if (isset($params['password']) && $password) {
  909. $password = get_password($password);
  910. $data['password'] = $password;
  911. }
  912. if($this->model->where(['id' => $info['id']])->update($data)){
  913. $this->error = 1013;
  914. return true;
  915. }
  916. $this->error = 1014;
  917. return true;
  918. }
  919. /**
  920. * 身份认证
  921. * @param $userId
  922. * @param $params
  923. * @return bool
  924. */
  925. public function auth($userId, $params)
  926. {
  927. // 用户验证
  928. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first();
  929. if (!$info) {
  930. $this->error = 2001;
  931. return false;
  932. }
  933. // 使用状态校验
  934. if ($info['status'] != 1) {
  935. $this->error = 2009;
  936. return false;
  937. }
  938. // 密码校验
  939. $data = ['update_time' => time(),'idcard_check'=>1];
  940. if (isset($params['realname']) && $params['realname']) {
  941. $data['realname'] = trim($params['realname']);
  942. }
  943. $idcard = isset($params['idcard']) && $params['idcard'];
  944. if ($idcard) {
  945. $data['idcard'] = trim($params['idcard']);
  946. }
  947. if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) {
  948. $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']);
  949. }
  950. if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) {
  951. $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']);
  952. }
  953. $this->model->where(['id' => $userId])->update($data);
  954. // 发送消息
  955. $this->error = 2036;
  956. return true;
  957. }
  958. /**
  959. * 转账
  960. * @param $userId
  961. * @param $params
  962. * @return bool
  963. */
  964. public function transfer($userId, $params)
  965. {
  966. $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0;
  967. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  968. $money = isset($params['money'])? floatval($params['money']) : 0;
  969. if(empty($toUserId) || $money<=0){
  970. $this->error = 2420;
  971. return false;
  972. }
  973. $cacheKey = "caches:members:transfer:{$userId}";
  974. if(RedisService::get($cacheKey)){
  975. $this->error = 1034;
  976. return false;
  977. }
  978. // 验证账户
  979. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  980. ->select(['id','nickname','username','usdt','pay_password','balance','status'])
  981. ->first();
  982. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  983. $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  984. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  985. $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : '';
  986. if(empty($userInfo) || $status != 1){
  987. $this->error = 2024;
  988. return false;
  989. }
  990. // 余额支付支付密码验证
  991. if(empty($userPayPassword)){
  992. $this->error = 1040;
  993. return false;
  994. }
  995. $payPassword = get_password($payPassword);
  996. if($payPassword != $userPayPassword){
  997. $this->error = 2038;
  998. return false;
  999. }
  1000. // 验证账户
  1001. $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1])
  1002. ->select(['id','nickname','usdt','username','balance','status'])
  1003. ->first();
  1004. $status = isset($accountInfo['status'])? $accountInfo['status'] : 0;
  1005. $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0;
  1006. $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : '';
  1007. if(empty($accountInfo) || $status != 1){
  1008. $this->error = 2421;
  1009. return false;
  1010. }
  1011. if($money > $usdt){
  1012. $this->error = 2422;
  1013. return false;
  1014. }
  1015. // 用户余额转账到用户
  1016. DB::beginTransaction();
  1017. RedisService::set($cacheKey, $params, rand(2,5));
  1018. $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()];
  1019. if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1020. DB::rollBack();
  1021. $this->error = 2028;
  1022. RedisService::clear($cacheKey);
  1023. return false;
  1024. }
  1025. // 明细
  1026. $orderNo = get_order_num('TR');
  1027. $log = [
  1028. 'user_id' => $userId,
  1029. 'source_id' => $toUserId,
  1030. 'source_order_no' => $orderNo,
  1031. 'type' => 6,
  1032. 'coin_type' => 1,
  1033. 'user_type'=> 1,
  1034. 'money' => -$money,
  1035. 'actual_money' => -$money,
  1036. 'balance' => $usdt,
  1037. 'create_time' => time(),
  1038. 'update_time' => time(),
  1039. 'remark' => "USDT转账",
  1040. 'status' => 1,
  1041. 'mark' => 1,
  1042. ];
  1043. if(!AccountLogModel::insertGetId($log)){
  1044. DB::rollBack();
  1045. $this->error = 2423;
  1046. RedisService::clear($cacheKey);
  1047. return false;
  1048. }
  1049. // 到账
  1050. $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5);
  1051. $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0;
  1052. $feeUsdt = round($money * $fee,2);
  1053. $realUsdt = moneyFormat($money - $feeUsdt,2);
  1054. $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()];
  1055. if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){
  1056. DB::rollBack();
  1057. $this->error = 2424;
  1058. RedisService::clear($cacheKey);
  1059. return false;
  1060. }
  1061. // 明细
  1062. $log = [
  1063. 'user_id' => $toUserId,
  1064. 'source_id' => $userId,
  1065. 'source_order_no' => $orderNo,
  1066. 'type' => 6,
  1067. 'coin_type' => 1,
  1068. 'user_type'=> 1,
  1069. 'money' => $realUsdt,
  1070. 'actual_money' => $realUsdt,
  1071. 'balance' => $accountUsdt,
  1072. 'create_time' => time(),
  1073. 'update_time' => time(),
  1074. 'remark' => "USDT转账",
  1075. 'status' => 1,
  1076. 'mark' => 1,
  1077. ];
  1078. if(!AccountLogModel::insertGetId($log)){
  1079. DB::rollBack();
  1080. $this->error = 2029;
  1081. RedisService::clear($cacheKey);
  1082. return false;
  1083. }
  1084. // 平台明细
  1085. $log = [
  1086. 'user_id' => 0,
  1087. 'source_id' => $userId,
  1088. 'source_order_no' => $orderNo,
  1089. 'type' => 6,
  1090. 'coin_type' => 1,
  1091. 'user_type'=> 4,
  1092. 'money' => $feeUsdt,
  1093. 'actual_money' => $feeUsdt,
  1094. 'balance' => 0,
  1095. 'create_time' => time(),
  1096. 'update_time' => time(),
  1097. 'remark' => "USDT转账",
  1098. 'status' => 1,
  1099. 'mark' => 1,
  1100. ];
  1101. if(!AccountLogModel::insertGetId($log)){
  1102. DB::rollBack();
  1103. $this->error = 2029;
  1104. RedisService::clear($cacheKey);
  1105. return false;
  1106. }
  1107. // 平台
  1108. FinanceService::make()->saveLog(0, $feeUsdt,1);
  1109. // 消息
  1110. $dateTime = date('Y-m-d H:i:s');
  1111. MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3);
  1112. $dateTime = date('Y-m-d H:i:s');
  1113. MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3);
  1114. DB::commit();
  1115. RedisService::clear($cacheKey);
  1116. $this->error = 2425;
  1117. return true;
  1118. }
  1119. /**
  1120. * 余额充值
  1121. * @param $userId
  1122. * @param $params
  1123. * @return array|false
  1124. */
  1125. public function recharge($userId, $params)
  1126. {
  1127. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1128. $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0;
  1129. $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
  1130. $payType = 10;
  1131. if($usdt<=0){
  1132. $this->error = 2031;
  1133. return false;
  1134. }
  1135. $cacheKey = "caches:member:recharge:lock_{$userId}";
  1136. if(RedisService::get($cacheKey)){
  1137. $this->error = 1034;
  1138. return false;
  1139. }
  1140. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  1141. ->select(['id','nickname','usdt','pay_password','balance','status'])
  1142. ->first();
  1143. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1144. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  1145. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1146. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1147. if(empty($userInfo) || $status != 1){
  1148. $this->error = 2024;
  1149. return false;
  1150. }
  1151. if($userPayPassword != get_password($payPassword)){
  1152. $this->error = 2038;
  1153. return false;
  1154. }
  1155. // 充值订单
  1156. $orderNo = get_order_num('DR');
  1157. $money = $usdt;
  1158. // 星豆
  1159. DB::beginTransaction();
  1160. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1161. if($coinType == 2){
  1162. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  1163. $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100;
  1164. $money = round($xdPrice * $usdt,2);
  1165. if($usdt > $userUsdt){
  1166. $this->error = 2035;
  1167. RedisService::clear($cacheKey);
  1168. return false;
  1169. }
  1170. // 扣除usdt余额
  1171. $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()];
  1172. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  1173. RedisService::clear($cacheKey);
  1174. $this->error = 2036;
  1175. DB::rollBack();
  1176. return false;
  1177. }
  1178. }
  1179. $data = [
  1180. 'order_no'=> $orderNo,
  1181. 'user_id'=> $userId,
  1182. 'type'=> 1,
  1183. 'user_type'=> 1,
  1184. 'coin_type'=> 2,
  1185. 'money'=> $usdt,
  1186. 'actual_money'=> $money,
  1187. 'pay_type'=> $payType,
  1188. 'pay_status'=> 20,
  1189. 'pay_at'=> date('Y-m-d H:i:s'),
  1190. 'create_time'=> time(),
  1191. 'update_time'=> time(),
  1192. 'status'=> 2,
  1193. 'mark'=> 1,
  1194. ];
  1195. if(!$orderId = BalanceLogModel::insertGetId($data)){
  1196. RedisService::clear($cacheKey);
  1197. $this->error = 2033;
  1198. DB::rollBack();
  1199. return false;
  1200. }
  1201. // 扣除USDT
  1202. $log = [
  1203. 'user_id'=> $userId,
  1204. 'source_order_no'=> $data['order_no'],
  1205. 'user_type'=> 1,
  1206. 'type'=> 5,
  1207. 'coin_type'=> 1,
  1208. 'money'=> -$usdt,
  1209. 'actual_money'=> -$usdt,
  1210. 'balance'=> $userUsdt,
  1211. 'date'=> date('Y-m-d'),
  1212. 'create_time'=> time(),
  1213. 'remark'=> '星豆余额充值扣除',
  1214. 'status'=>1,
  1215. 'mark'=>1
  1216. ];
  1217. if(!AccountLogModel::insertGetId($log)){
  1218. RedisService::clear($cacheKey);
  1219. $this->error = 2029;
  1220. DB::rollBack();
  1221. return false;
  1222. }
  1223. // 增加星豆余额
  1224. $log = [
  1225. 'user_id'=> $userId,
  1226. 'source_order_no'=> $data['order_no'],
  1227. 'user_type'=> 1,
  1228. 'type'=> 5,
  1229. 'coin_type'=> 2,
  1230. 'money'=> $usdt,
  1231. 'actual_money'=> $money,
  1232. 'balance'=> $balance,
  1233. 'date'=> date('Y-m-d'),
  1234. 'create_time'=> time(),
  1235. 'remark'=> '星豆余额充值',
  1236. 'status'=>1,
  1237. 'mark'=>1
  1238. ];
  1239. if(!AccountLogModel::insertGetId($log)){
  1240. RedisService::clear($cacheKey);
  1241. $this->error = 2029;
  1242. DB::rollBack();
  1243. return false;
  1244. }
  1245. // 消息
  1246. $dateTime = date('Y-m-d H:i:s');
  1247. MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3);
  1248. DB::commit();
  1249. // 充值星豆任务
  1250. TaskService::make()->updateTask($userId,9, 0);
  1251. $this->error = 2037;
  1252. RedisService::clear($cacheKey);
  1253. return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)];
  1254. }
  1255. /**
  1256. * USDT 充值
  1257. * @param $userId
  1258. * @param $params
  1259. * @return array|false
  1260. */
  1261. public function rechargeUsdt($userId, $params)
  1262. {
  1263. $money = isset($params['money'])? moneyFormat($params['money'], 2) : 0;
  1264. $payType = isset($params['pay_type']) && $params['pay_type']? intval($params['pay_type']) : 20;
  1265. $payStyle = isset($params['pay_style']) && $params['pay_style']? trim($params['pay_style']) : 'usdt';
  1266. $payImg = isset($params['pay_img']) && $params['pay_img']? get_image_path($params['pay_img']) : '';
  1267. if($money<=0){
  1268. $this->error = 2051;
  1269. return false;
  1270. }
  1271. if(empty($payImg)){
  1272. $this->error = 2052;
  1273. return false;
  1274. }
  1275. $cacheKey = "caches:member:rechargeUsdt:lock_{$userId}";
  1276. if(RedisService::get($cacheKey)){
  1277. $this->error = 1034;
  1278. return false;
  1279. }
  1280. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  1281. ->select(['id','nickname','usdt','pay_password','balance','status'])
  1282. ->first();
  1283. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1284. if(empty($userInfo) || $status != 1){
  1285. $this->error = 2024;
  1286. return false;
  1287. }
  1288. // 充值订单
  1289. $orderNo = get_order_num('UR');
  1290. // 星豆
  1291. DB::beginTransaction();
  1292. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1293. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  1294. if ($usdtPrice <= 0) {
  1295. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  1296. $usdtPrice = $usdtCnyPrice > 0 && $usdtCnyPrice < 100 ? $usdtCnyPrice : 0;
  1297. }
  1298. $usdt = round($money / $usdtPrice,3);
  1299. $data = [
  1300. 'order_no'=> $orderNo,
  1301. 'user_id'=> $userId,
  1302. 'type'=> 1,
  1303. 'user_type'=> 1,
  1304. 'coin_type'=> 1,
  1305. 'money'=> $usdt,
  1306. 'usdt_price'=> $usdtPrice,
  1307. 'actual_money'=> $money,
  1308. 'pay_type'=> $payType,
  1309. 'pay_style'=> $payStyle,
  1310. 'pay_img'=> $payImg,
  1311. 'pay_status'=> 20,
  1312. 'pay_at'=> date('Y-m-d H:i:s'),
  1313. 'create_time'=> time(),
  1314. 'update_time'=> time(),
  1315. 'status'=> 1,
  1316. 'mark'=> 1,
  1317. ];
  1318. if(!$orderId = BalanceLogModel::insertGetId($data)){
  1319. RedisService::clear($cacheKey);
  1320. $this->error = 2054;
  1321. DB::rollBack();
  1322. return false;
  1323. }
  1324. // 消息
  1325. $dateTime = date('Y-m-d H:i:s');
  1326. MessageService::make()->pushMessage($userId,'USDT余额线下充值提交成功',"您在{$dateTime}(UTC+8)线下支付{$money}元,充值{$usdt}USDT余额申请提交成功,请耐心等候审核。",3);
  1327. DB::commit();
  1328. $this->error = 2053;
  1329. RedisService::clear($cacheKey);
  1330. return ['order_id'=> $orderId];
  1331. }
  1332. /**
  1333. * 积分兑换星豆
  1334. * @param $userId
  1335. * @param $params
  1336. * @return array|false
  1337. */
  1338. public function exchange($userId, $params)
  1339. {
  1340. $score = isset($params['score'])? floatval($params['score']) : 0;
  1341. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1342. if($score<=0){
  1343. $this->error = 3201;
  1344. return false;
  1345. }
  1346. $userInfo = $this->model->with(['merchant'])
  1347. ->where(['id'=> $userId,'mark'=>1])
  1348. ->select(['id','nickname','usdt','trc_url','balance','score','pay_password','status'])
  1349. ->first();
  1350. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1351. $userScore = isset($userInfo['score'])? $userInfo['score'] : 0;
  1352. $userXd = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  1353. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1354. if(empty($userInfo) || $status != 1){
  1355. $this->error = 2024;
  1356. return false;
  1357. }
  1358. // 兑换金额验证
  1359. if ($score > $userScore) {
  1360. $this->error = web_lang(3202, ['money' => $userScore]);
  1361. return false;
  1362. }
  1363. // 兑换账户
  1364. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1365. if (empty($trcUrl)) {
  1366. $this->error = 3203;
  1367. return false;
  1368. }
  1369. if($userPayPassword != get_password($payPassword)){
  1370. $this->error = 2038;
  1371. return false;
  1372. }
  1373. $cacheKey = "caches:member:exchange:lock_{$userId}";
  1374. if(RedisService::get($cacheKey)){
  1375. $this->error = 1034;
  1376. return false;
  1377. }
  1378. DB::beginTransaction();
  1379. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1380. // 提现记录
  1381. $orderNo = get_order_num('EX');
  1382. $exchangeFeeRate = ConfigService::make()->getConfigByCode('exchange_fee_rate',0);
  1383. $exchangeFeeRate = $exchangeFeeRate>0 && $exchangeFeeRate<100? $exchangeFeeRate : 0;
  1384. $exchangeRate = ConfigService::make()->getConfigByCode('score_exchange_xd_rate',5);
  1385. $exchangeRate = $exchangeRate>0 && $exchangeRate<10000? $exchangeRate : 0;
  1386. $xdTotal = round($score*$exchangeRate, 2);
  1387. $fee = moneyFormat($xdTotal * $exchangeFeeRate/100, 2);
  1388. $xd = round($xdTotal - $fee,2);
  1389. $updateData = ['score'=>DB::raw("score - {$score}"),'balance'=>DB::raw("balance + {$xd}"),'update_time'=> time()];
  1390. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1391. DB::rollBack();
  1392. $this->error = 2406;
  1393. RedisService::clear($cacheKey);
  1394. return false;
  1395. }
  1396. // 积分明细
  1397. $log = [
  1398. 'user_id' => $userId,
  1399. 'source_id' => 0,
  1400. 'source_order_no' => $orderNo,
  1401. 'type' => 26,
  1402. 'coin_type' => 4,
  1403. 'user_type'=> 1,
  1404. 'money' => -$score,
  1405. 'actual_money' => -$score,
  1406. 'balance' => $userScore,
  1407. 'create_time' => time(),
  1408. 'update_time' => time(),
  1409. 'remark' => "积分兑换星豆",
  1410. 'status' => 1,
  1411. 'mark' => 1,
  1412. ];
  1413. if (!AccountLogModel::insertGetId($log)) {
  1414. $this->error = 2407;
  1415. DB::rollBack();
  1416. RedisService::clear($cacheKey);
  1417. return false;
  1418. }
  1419. // 星豆明细
  1420. $log = [
  1421. 'user_id' => $userId,
  1422. 'source_id' => 0,
  1423. 'source_order_no' => $orderNo,
  1424. 'type' => 26,
  1425. 'coin_type' => 2,
  1426. 'user_type'=> 1,
  1427. 'money' => $xd,
  1428. 'actual_money' => $xd,
  1429. 'balance' => $userXd,
  1430. 'create_time' => time(),
  1431. 'update_time' => time(),
  1432. 'remark' => "积分兑换星豆",
  1433. 'status' => 1,
  1434. 'mark' => 1,
  1435. ];
  1436. if (!AccountLogModel::insertGetId($log)) {
  1437. $this->error = 2407;
  1438. DB::rollBack();
  1439. RedisService::clear($cacheKey);
  1440. return false;
  1441. }
  1442. DB::commit();
  1443. // 站内消息
  1444. $dateTime = date('Y-m-d H:i:s');
  1445. $title = '积分兑换星豆成功';
  1446. $message = "您在{$dateTime}(UTC+8)使用{$score}兑换{$xd}成功,扣除{$exchangeFeeRate}%手续费{$fee}星豆,请查看账户余额!!!";
  1447. MessageService::make()->pushMessage($userId, $title, $message);
  1448. $this->error = $title;
  1449. RedisService::clear($cacheKey);
  1450. return [
  1451. 'score'=> $score,
  1452. 'xd'=> $xd,
  1453. ];
  1454. }
  1455. /**
  1456. * 付款给商家
  1457. * @param $userId 用户ID
  1458. * @param $params
  1459. * @return array|false
  1460. */
  1461. public function payment($userId, $params)
  1462. {
  1463. $money = isset($params['money'])? floatval($params['money']) : 0;
  1464. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1465. $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
  1466. $mid = isset($params['mid']) && $params['mid']? intval($params['mid']) : 0;
  1467. if($money<=0){
  1468. $this->error = 3301;
  1469. return false;
  1470. }
  1471. if(!in_array($coinType,[1,2]) || $mid<=0){
  1472. $this->error = 3302;
  1473. return false;
  1474. }
  1475. // 商家
  1476. $merchInfo = MerchantModel::with(['member'])->where(['id'=> $mid,'mark'=>1])->first();
  1477. $tradeStatus = isset($merchInfo['trade_status'])? $merchInfo['trade_status'] : 0;
  1478. $status = isset($merchInfo['status'])? $merchInfo['status'] : 0;
  1479. $merchUserId = isset($merchInfo['user_id'])? $merchInfo['user_id'] : 0;
  1480. $shopUsdt = isset($merchInfo['usdt'])? $merchInfo['usdt'] : 0;
  1481. $shopUser = isset($merchInfo['member'])? $merchInfo['member'] : [];
  1482. $shopUserWaitScore = isset($shopUser['wait_score'])? $shopUser['wait_score'] : 0;
  1483. if(empty($merchInfo) || $merchUserId<=0){
  1484. $this->error = 3304;
  1485. return false;
  1486. }
  1487. if($merchUserId == $userId){
  1488. $this->error = 3307;
  1489. return false;
  1490. }
  1491. if($status != 2){
  1492. $this->error = 3306;
  1493. return false;
  1494. }
  1495. if($tradeStatus == 2){
  1496. $this->error = 3305;
  1497. return false;
  1498. }
  1499. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  1500. ->select(['id','nickname','usdt','trc_url','balance','score','wait_score','pay_password','status'])
  1501. ->first();
  1502. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1503. $userScore = isset($userInfo['score'])? $userInfo['score'] : 0;
  1504. $waitScore = isset($userInfo['wait_score'])? $userInfo['wait_score'] : 0;
  1505. $userXd = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  1506. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1507. if(empty($userInfo) || $status != 1){
  1508. $this->error = 2024;
  1509. return false;
  1510. }
  1511. // 付款验证
  1512. if ($money > $userXd) {
  1513. $this->error = web_lang(3303, ['money' => $userXd]);
  1514. return false;
  1515. }
  1516. // 用户账户
  1517. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1518. if (empty($trcUrl)) {
  1519. $this->error = 3302;
  1520. return false;
  1521. }
  1522. if(empty($userPayPassword)){
  1523. $this->error = 1040;
  1524. return false;
  1525. }
  1526. if($userPayPassword != get_password($payPassword)){
  1527. $this->error = 2038;
  1528. return false;
  1529. }
  1530. $cacheKey = "caches:member:payment:lock_{$userId}";
  1531. if(RedisService::get($cacheKey)){
  1532. $this->error = 1034;
  1533. return false;
  1534. }
  1535. DB::beginTransaction();
  1536. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1537. // 提现记录
  1538. $orderNo = get_order_num('PY');
  1539. $waitScoreRate = ConfigService::make()->getConfigByCode('shop_wait_score_rate',0);
  1540. $waitScoreRate = $waitScoreRate>0 && $waitScoreRate<100? $waitScoreRate : 0;
  1541. $userWaitScoreRate = ConfigService::make()->getConfigByCode('shop_user_wait_score_rate',5);
  1542. $userWaitScoreRate = $userWaitScoreRate>0 && $userWaitScoreRate<10000? $userWaitScoreRate : 0;
  1543. $shopWaitScore = round($money*$waitScoreRate/100, 2);
  1544. $userWaitScore = round($money*$userWaitScoreRate/100, 2);
  1545. // 用户账户更新
  1546. $updateData = ['wait_score'=>DB::raw("wait_score + {$userWaitScore}"),'balance'=>DB::raw("balance - {$money}"),'update_time'=> time()];
  1547. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1548. DB::rollBack();
  1549. $this->error = 2406;
  1550. RedisService::clear($cacheKey);
  1551. return false;
  1552. }
  1553. // 用户星豆账户明细
  1554. $log = [
  1555. 'user_id' => $userId,
  1556. 'source_id' => $mid,
  1557. 'source_order_no' => $orderNo,
  1558. 'type' => 25,
  1559. 'coin_type' => 2,
  1560. 'user_type'=> 1,
  1561. 'money' => -$money,
  1562. 'actual_money' => -$money,
  1563. 'balance' => $userXd,
  1564. 'create_time' => time(),
  1565. 'update_time' => time(),
  1566. 'remark' => "付款给商家扣除",
  1567. 'status' => 1,
  1568. 'mark' => 1,
  1569. ];
  1570. if (!AccountLogModel::insertGetId($log)) {
  1571. $this->error = 2407;
  1572. DB::rollBack();
  1573. RedisService::clear($cacheKey);
  1574. return false;
  1575. }
  1576. // 用户待返积分奖励
  1577. if($userWaitScore>0){
  1578. // 用户待返积分账户明细
  1579. $log = [
  1580. 'user_id' => $userId,
  1581. 'source_id' => $mid,
  1582. 'source_order_no' => $orderNo,
  1583. 'type' => 9,
  1584. 'coin_type' => 5,
  1585. 'user_type'=> 1,
  1586. 'money' => $userWaitScore,
  1587. 'actual_money' => $userWaitScore,
  1588. 'balance' => $waitScore,
  1589. 'create_time' => time(),
  1590. 'update_time' => time(),
  1591. 'remark' => "付款给商家奖励",
  1592. 'status' => 1,
  1593. 'mark' => 1,
  1594. ];
  1595. if (!AccountLogModel::insertGetId($log)) {
  1596. $this->error = 2407;
  1597. DB::rollBack();
  1598. RedisService::clear($cacheKey);
  1599. return false;
  1600. }
  1601. }
  1602. // 商家账户
  1603. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  1604. $xdPrice = $xdPrice>0 && $xdPrice<=10000? $xdPrice : 100;
  1605. $shopXd = moneyFormat($money - $shopWaitScore, 3); // 商家到账星豆
  1606. $shopTotalUsdt = moneyFormat($money/$xdPrice,3); // 付给商家的USDT
  1607. $shopPayUsdt = moneyFormat($shopXd/$xdPrice,3); // 商家到账USDT
  1608. $updateData = ['usdt'=>DB::raw("usdt + {$shopPayUsdt}"),'update_time'=> time()];
  1609. if(!MerchantModel::where(['id'=> $mid])->update($updateData)){
  1610. DB::rollBack();
  1611. $this->error = 2406;
  1612. RedisService::clear($cacheKey);
  1613. return false;
  1614. }
  1615. // 商家账户明细
  1616. $log = [
  1617. 'user_id' => $mid,
  1618. 'source_id' => $userId,
  1619. 'source_order_no' => $orderNo,
  1620. 'type' => 25,
  1621. 'coin_type' => 1,
  1622. 'user_type'=> 2,
  1623. 'money' => $money,
  1624. 'actual_money' => $shopPayUsdt,
  1625. 'balance' => $shopUsdt,
  1626. 'create_time' => time(),
  1627. 'update_time' => time(),
  1628. 'remark' => "收到用户付款",
  1629. 'status' => 1,
  1630. 'mark' => 1,
  1631. ];
  1632. if (!AccountLogModel::insertGetId($log)) {
  1633. $this->error = 2407;
  1634. DB::rollBack();
  1635. RedisService::clear($cacheKey);
  1636. return false;
  1637. }
  1638. // 商家待返积分奖励
  1639. if($shopWaitScore>0){
  1640. $updateData = ['wait_score'=>DB::raw("wait_score + {$shopWaitScore}"),'update_time'=> time()];
  1641. if(!MemberModel::where(['id'=> $merchUserId])->update($updateData)){
  1642. DB::rollBack();
  1643. $this->error = 2406;
  1644. RedisService::clear($cacheKey);
  1645. return false;
  1646. }
  1647. // 商家账户明细
  1648. $log = [
  1649. 'user_id' => $mid,
  1650. 'source_id' => $userId,
  1651. 'source_order_no' => $orderNo,
  1652. 'type' => 9,
  1653. 'coin_type' => 5,
  1654. 'user_type'=> 2,
  1655. 'money' => $money,
  1656. 'actual_money' => $shopWaitScore,
  1657. 'balance' => $shopUserWaitScore,
  1658. 'create_time' => time(),
  1659. 'update_time' => time(),
  1660. 'remark' => "商家收款奖励",
  1661. 'status' => 1,
  1662. 'mark' => 1,
  1663. ];
  1664. if (!AccountLogModel::insertGetId($log)) {
  1665. $this->error = 2407;
  1666. DB::rollBack();
  1667. RedisService::clear($cacheKey);
  1668. return false;
  1669. }
  1670. }
  1671. DB::commit();
  1672. // 站内消息
  1673. $dateTime = date('Y-m-d H:i:s');
  1674. $title = '付款给商家成功通知';
  1675. $message = "您在{$dateTime}(UTC+8)成功付款{$money}星豆给商家[$merchUserId],合计{$shopTotalUsdt} USDT,奖励待返积分{$userWaitScore},请留意账户!!!";
  1676. MessageService::make()->pushMessage($userId, $title, $message,3);
  1677. $title = '收到用户付款通知';
  1678. $message = "您在{$dateTime}(UTC+8)收到用户[{$userId}]付款{$money}星豆,合计{$shopTotalUsdt} USDT,奖励待返积分{$shopWaitScore},到账金额{$shopPayUsdt} USDT,请留意查收!!!";
  1679. MessageService::make()->pushMessage($merchUserId, $title, $message,3);
  1680. $this->error = 3308;
  1681. RedisService::clear($cacheKey);
  1682. return [
  1683. 'money'=> $money,
  1684. 'usdt'=> $shopTotalUsdt,
  1685. ];
  1686. }
  1687. /**
  1688. * 余额提现
  1689. * @param $userId
  1690. * @param $params
  1691. * @return array|false
  1692. */
  1693. public function withdraw($userId, $params)
  1694. {
  1695. $money = isset($params['money'])? floatval($params['money']) : 0;
  1696. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1697. $payType = isset($params['pay_type']) && $params['pay_type']? intval($params['pay_type']) : 20;
  1698. $paymentId = isset($params['payment_id']) && $params['payment_id']? intval($params['payment_id']) : 0;
  1699. $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1;
  1700. if($money<=0){
  1701. $this->error = 2401;
  1702. return false;
  1703. }
  1704. if(!in_array($userType,[1,2])){
  1705. $this->error = 2404;
  1706. return false;
  1707. }
  1708. if($payType != 20 && $paymentId<=0){
  1709. $this->error = 3204;
  1710. return false;
  1711. }
  1712. $userInfo = $this->model->with(['merchant'])
  1713. ->where(['id'=> $userId,'mark'=>1])
  1714. ->select(['id','nickname','usdt','trc_url','pay_password','status'])
  1715. ->first();
  1716. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1717. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1718. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1719. $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : [];
  1720. $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0;
  1721. $merchantId = isset($merchant['id'])? $merchant['id'] : 0;
  1722. $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0;
  1723. if(empty($userInfo) || $status != 1){
  1724. $this->error = 2024;
  1725. return false;
  1726. }
  1727. if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){
  1728. $this->error = 2024;
  1729. return false;
  1730. }
  1731. // 提现金额验证
  1732. $accountUsdt = $userType==1? $userUsdt : $merchantUsdt;
  1733. if ($money > $accountUsdt) {
  1734. $this->error = web_lang(2402, ['money' => $accountUsdt]);
  1735. return false;
  1736. }
  1737. // 提现账户
  1738. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1739. if (empty($trcUrl)) {
  1740. $this->error = 2403;
  1741. return false;
  1742. }
  1743. if($userPayPassword != get_password($payPassword)){
  1744. $this->error = 2038;
  1745. return false;
  1746. }
  1747. $cacheKey = "caches:member:withdraw:lock_{$userId}";
  1748. if(RedisService::get($cacheKey)){
  1749. $this->error = 1034;
  1750. return false;
  1751. }
  1752. DB::beginTransaction();
  1753. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1754. // 提现记录
  1755. $orderNo = get_order_num('DW');
  1756. $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5);
  1757. $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0;
  1758. $fee = round($money*$feeRate, 2);
  1759. $realAmount = moneyFormat($money - $fee, 2);
  1760. if($payType != 20){
  1761. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  1762. if ($usdtPrice <= 0) {
  1763. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  1764. $usdtPrice = $usdtCnyPrice > 0 && $usdtCnyPrice < 100 ? $usdtCnyPrice : 0;
  1765. }
  1766. $fee = round($fee * $usdtPrice, 2);
  1767. $realAmount = round($realAmount * $usdtPrice, 2);
  1768. }
  1769. $data = [
  1770. 'order_no'=> $orderNo,
  1771. 'user_id'=> $userType==1? $userId : $merchantId,
  1772. 'type'=> 2,
  1773. 'user_type'=> $userType,
  1774. 'coin_type'=> 1,
  1775. 'money'=> $money,
  1776. 'actual_money'=> $realAmount,
  1777. 'fee'=> $fee,
  1778. 'usdt_price'=> $payType!=20? $usdtPrice : 0,
  1779. 'trc_url'=> $trcUrl,
  1780. 'pay_type'=> $payType,
  1781. 'payment_id'=> $paymentId,
  1782. 'date'=> date('Y-m-d'),
  1783. 'create_time'=> time(),
  1784. 'update_time'=> time(),
  1785. 'status'=> 1,
  1786. 'mark'=> 1,
  1787. ];
  1788. if(!$id = BalanceLogModel::insertGetId($data)){
  1789. DB::rollBack();
  1790. $this->error = 2405;
  1791. RedisService::clear($cacheKey);
  1792. return false;
  1793. }
  1794. // 商户扣款
  1795. if($userType == 2){
  1796. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1797. if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){
  1798. DB::rollBack();
  1799. $this->error = 2406;
  1800. RedisService::clear($cacheKey);
  1801. return false;
  1802. }
  1803. // 明细
  1804. $log = [
  1805. 'user_id' => $merchantId,
  1806. 'source_id' => $userId,
  1807. 'source_order_no' => $orderNo,
  1808. 'type' => 5,
  1809. 'coin_type' => 1,
  1810. 'user_type'=> 2,
  1811. 'money' => -$money,
  1812. 'actual_money' => -$money,
  1813. 'balance' => $merchantUsdt,
  1814. 'create_time' => time(),
  1815. 'update_time' => time(),
  1816. 'remark' => "商户账户余额提现",
  1817. 'status' => 1,
  1818. 'mark' => 1,
  1819. ];
  1820. if (!AccountLogModel::insertGetId($log)) {
  1821. $this->error = 2407;
  1822. DB::rollBack();
  1823. RedisService::clear($cacheKey);
  1824. return false;
  1825. }
  1826. }
  1827. // 用户扣款
  1828. else{
  1829. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1830. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1831. DB::rollBack();
  1832. $this->error = 2406;
  1833. RedisService::clear($cacheKey);
  1834. return false;
  1835. }
  1836. // 明细
  1837. $log = [
  1838. 'user_id' => $userId,
  1839. 'source_id' => 0,
  1840. 'source_order_no' => $orderNo,
  1841. 'type' => 5,
  1842. 'coin_type' => 1,
  1843. 'user_type'=> 1,
  1844. 'money' => -$money,
  1845. 'actual_money' => -$money,
  1846. 'balance' => $userUsdt,
  1847. 'create_time' => time(),
  1848. 'update_time' => time(),
  1849. 'remark' => "USDT余额提现",
  1850. 'status' => 1,
  1851. 'mark' => 1,
  1852. ];
  1853. if (!AccountLogModel::insertGetId($log)) {
  1854. $this->error = 2407;
  1855. DB::rollBack();
  1856. RedisService::clear($cacheKey);
  1857. return false;
  1858. }
  1859. }
  1860. DB::commit();
  1861. // 站内消息
  1862. $dateTime = date('Y-m-d H:i:s');
  1863. $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功';
  1864. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!";
  1865. MessageService::make()->pushMessage($userId, $title, $message, 3);
  1866. // 提现自动审核,低于该金额自动审核
  1867. $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300);
  1868. $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0;
  1869. if ($money <= $autoCheckUsdt && $payType == 20) {
  1870. // 打款处理
  1871. $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realAmount);
  1872. $txID = isset($result['txId']) ? $result['txId'] : '';
  1873. $payAddress = isset($result['address']) ? $result['address'] : '';
  1874. if ($txID && $payAddress) {
  1875. $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()];
  1876. if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){
  1877. $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功';
  1878. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!";
  1879. MessageService::make()->pushMessage($userId, $title, $message);
  1880. AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]);
  1881. // 平台明细
  1882. $log = [
  1883. 'user_id' => 0,
  1884. 'source_id' => $userId,
  1885. 'source_order_no' => $orderNo,
  1886. 'type' => 5,
  1887. 'coin_type' => 1,
  1888. 'user_type'=> 4,
  1889. 'money' => $fee,
  1890. 'actual_money' => $fee,
  1891. 'balance' => 0,
  1892. 'create_time' => time(),
  1893. 'update_time' => time(),
  1894. 'hash' => $txID,
  1895. 'remark' => "USDT余额提现",
  1896. 'status' => 1,
  1897. 'mark' => 1,
  1898. ];
  1899. AccountLogModel::insertGetId($log);
  1900. // 平台流水
  1901. FinanceService::make()->saveLog(0, $fee, 1);
  1902. }
  1903. }
  1904. }
  1905. $this->error = $title;
  1906. RedisService::clear($cacheKey);
  1907. return [
  1908. 'id'=> $id,
  1909. 'money'=> $money,
  1910. 'user_type'=> $userType,
  1911. ];
  1912. }
  1913. /**
  1914. * 获取点对点上级节点
  1915. * @param $userId 推荐人ID
  1916. * @return int|mixed
  1917. */
  1918. public function getPointParentId($userId)
  1919. {
  1920. if($userId<=0){
  1921. return 0;
  1922. }
  1923. $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get();
  1924. $userList = $userList? $userList->toArray() : [];
  1925. if(count($userList) < 3){
  1926. return $userId;
  1927. }
  1928. $users = [];
  1929. foreach($userList as $item){
  1930. $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
  1931. $points = array_filter($points);
  1932. $users[$item['id']]['pointLen'] = count($points);
  1933. $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
  1934. $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
  1935. }
  1936. //var_dump($users);
  1937. $pointId = 0;
  1938. $tempPointLen = 0;
  1939. $tempChildren = 0;
  1940. foreach ($userList as $item) {
  1941. $id = isset($item['id'])? $item['id'] : 0;
  1942. $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
  1943. $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
  1944. //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren);
  1945. if($pointLen<=$tempPointLen || $pointId == 0){
  1946. //var_dump($id.'++'.$pointLen.'--'.$children."\n\n");
  1947. if($children <$tempChildren || $pointId == 0){
  1948. $pointId = $id;
  1949. $tempPointLen = $pointLen;
  1950. $tempChildren = $children;
  1951. }
  1952. }
  1953. }
  1954. return $pointId;
  1955. }
  1956. /**
  1957. * DAO升级购买
  1958. * @param $userId 用户ID
  1959. * @param $params 参数:level-等级,pay_password-交易密码
  1960. * @return bool
  1961. */
  1962. public function upgrade($userId, $params)
  1963. {
  1964. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1965. $level = isset($params['level'])? intval($params['level']) : 0;
  1966. if($level<=0 || empty($payPassword)){
  1967. $this->error = 2014;
  1968. return false;
  1969. }
  1970. $cacheKey = "caches:members:upgrade:buy_{$userId}_{$level}";
  1971. if(RedisService::get($cacheKey.'_lock')){
  1972. $this->error = 1034;
  1973. return false;
  1974. }
  1975. $levelInfo = MemberLevelModel::from('member_level as a')
  1976. ->where(['a.id'=> $level,'a.status'=>1,'a.mark'=>1])
  1977. ->select(['a.*'])
  1978. ->first();
  1979. $upgradeUsdt = isset($levelInfo['upgrade_usdt'])? floatval($levelInfo['upgrade_usdt']) : 0;
  1980. $upgradeProfit = isset($levelInfo['upgrade_profit'])? floatval($levelInfo['upgrade_profit']) : 0;
  1981. $boxNum = isset($levelInfo['box_num'])? intval($levelInfo['box_num']) : 0;
  1982. $levelName = isset($levelInfo['name'])? $levelInfo['name'] : '';
  1983. if(empty($levelInfo)){
  1984. $this->error = 2511;
  1985. return false;
  1986. }
  1987. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  1988. ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','trc_url','pay_password','status'])
  1989. ->first();
  1990. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1991. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1992. $userTotalProfit = isset($userInfo['upgrade_profit_total'])? $userInfo['upgrade_profit_total'] : 0;
  1993. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1994. $userWaitScore = isset($userInfo['wait_score'])? $userInfo['wait_score'] : 0;
  1995. $userPowerNum = isset($userInfo['power_num'])? $userInfo['power_num'] : 0;
  1996. $userLevel = isset($userInfo['member_level'])? intval($userInfo['member_level']) : 0;
  1997. if(empty($userInfo) || $status != 1){
  1998. $this->error = 2024;
  1999. return false;
  2000. }
  2001. if($userLevel>= $level){
  2002. $this->error = 2512;
  2003. return false;
  2004. }
  2005. if($level >= 30){
  2006. $this->error = 2513;
  2007. return false;
  2008. }
  2009. // 收益是否满足条件
  2010. if($upgradeProfit>0 && $userTotalProfit < $upgradeProfit){
  2011. $this->error = 2514;
  2012. return false;
  2013. }
  2014. if(AccountLogModel::where(['user_id'=> $userId,'source_id'=> $level,'type'=>2,'coin_type'=>1,'status'=>1,'mark'=>1])->value('id')){
  2015. $this->error = 2512;
  2016. return false;
  2017. }
  2018. // USDT余额是否足够
  2019. if($userUsdt < $upgradeUsdt){
  2020. $this->error = 2035;
  2021. return false;
  2022. }
  2023. // 交易密码
  2024. if(empty($userPayPassword)){
  2025. $this->error = 1040;
  2026. return false;
  2027. }
  2028. if($userPayPassword != get_password($payPassword)){
  2029. $this->error = 2038;
  2030. return false;
  2031. }
  2032. // 购买明细
  2033. RedisService::set($cacheKey, $params, rand(2,3));
  2034. $orderNo = get_order_num('UP');
  2035. DB::beginTransaction();
  2036. $log = [
  2037. 'user_id' => $userId,
  2038. 'source_id' => $level,
  2039. 'source_order_no' => $orderNo,
  2040. 'type' => 2,
  2041. 'coin_type' => 1,
  2042. 'user_type'=> 1,
  2043. 'money' => -$upgradeUsdt,
  2044. 'actual_money' => -$upgradeUsdt,
  2045. 'balance' => $userUsdt,
  2046. 'create_time' => time(),
  2047. 'update_time' => time(),
  2048. 'remark' => "购买{$levelName}升级",
  2049. 'status' => 1,
  2050. 'mark' => 1,
  2051. ];
  2052. if(!AccountLogModel::insertGetId($log)){
  2053. DB::rollBack();
  2054. $this->error = 2029;
  2055. RedisService::clear($cacheKey);
  2056. return false;
  2057. }
  2058. // 待返积分
  2059. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  2060. $xdPrice = $xdPrice>0 && $xdPrice<=10000? $xdPrice : 100;
  2061. $waitScoreRate = ConfigService::make()->getConfigByCode('upgrade_award_score_rate', 200);
  2062. $waitScoreRate = $waitScoreRate>0 && $waitScoreRate<=1000? $waitScoreRate : 0;
  2063. $waitScore = moneyFormat($upgradeUsdt * $xdPrice * $waitScoreRate/100, 2);
  2064. if($waitScore>0){
  2065. $log = [
  2066. 'user_id' => $userId,
  2067. 'source_id' => $level,
  2068. 'source_order_no' => $orderNo,
  2069. 'type' => 9,
  2070. 'coin_type' => 5,
  2071. 'user_type'=> 1,
  2072. 'money' => $waitScore,
  2073. 'actual_money' => $waitScore,
  2074. 'balance' => $userWaitScore,
  2075. 'create_time' => time(),
  2076. 'update_time' => time(),
  2077. 'remark' => "购买{$levelName}升级",
  2078. 'status' => 1,
  2079. 'mark' => 1,
  2080. ];
  2081. if(!AccountLogModel::insertGetId($log)){
  2082. DB::rollBack();
  2083. $this->error = 2029;
  2084. RedisService::clear($cacheKey);
  2085. return false;
  2086. }
  2087. }
  2088. // 算力明细
  2089. $powerNum = $upgradeUsdt;
  2090. $log = [
  2091. 'user_id' => $userId,
  2092. 'source_id' => $level,
  2093. 'source_order_no' => $orderNo,
  2094. 'type' => 9,
  2095. 'coin_type' => 3,
  2096. 'user_type'=> 1,
  2097. 'money' => $powerNum,
  2098. 'actual_money' => $powerNum,
  2099. 'balance' => $userPowerNum,
  2100. 'create_time' => time(),
  2101. 'update_time' => time(),
  2102. 'remark' => "购买{$levelName}升级",
  2103. 'status' => 1,
  2104. 'mark' => 1,
  2105. ];
  2106. if(!AccountLogModel::insertGetId($log)){
  2107. DB::rollBack();
  2108. $this->error = 2029;
  2109. RedisService::clear($cacheKey);
  2110. return false;
  2111. }
  2112. // 账户
  2113. $updateData = [
  2114. 'usdt'=> DB::raw("usdt - {$upgradeUsdt}"), // 扣除USDT
  2115. 'member_level'=> $level, // 升级等级
  2116. 'box_num'=>DB::raw("box_num + {$boxNum}"), // 奖励盲盒数量
  2117. 'wait_score'=>DB::raw("wait_score + {$waitScore}"), // 待返积分奖励
  2118. 'power_num'=>DB::raw("power_num + {$powerNum}"), // 算力奖励
  2119. 'update_time'=>time()
  2120. ];
  2121. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  2122. DB::rollBack();
  2123. $this->error = 2036;
  2124. RedisService::clear($cacheKey);
  2125. return false;
  2126. }
  2127. // 消息
  2128. $dateTime = date('Y-m-d H:i:s');
  2129. MessageService::make()->pushMessage($userId,"购买{$levelName}升级成功","您在{$dateTime}(UTC+8)成功支付{$upgradeUsdt}USDT购买【{$levelName}】升级成功。",3);
  2130. DB::commit();
  2131. // 算力统计
  2132. AccountLogService::make()->saveCount($userId, $powerNum, 1);
  2133. // 业绩统计
  2134. AccountLogService::make()->saveCount($userId, $upgradeUsdt, 2);
  2135. // 结算收益奖励
  2136. FinanceService::make()->settleBonus($userId, $userInfo, $upgradeUsdt, $orderNo, "购买{$levelName}");
  2137. $this->error = 2503;
  2138. RedisService::clear($cacheKey);
  2139. return true;
  2140. }
  2141. /**
  2142. * 盲盒抽奖
  2143. * @param $userId 抽奖用户ID
  2144. * @param $params
  2145. * @return bool
  2146. */
  2147. public function draw($userId, $params)
  2148. {
  2149. $cacheKey="caches:members:draw_{$userId}";
  2150. if(RedisService::get($cacheKey.'_lock')){
  2151. $this->error = 1034;
  2152. return false;
  2153. }
  2154. $userInfo = MemberModel::where(['id'=> $userId,'mark'=>1])
  2155. ->select(['id','nickname','usdt','wait_score','parents','points','parent_id','member_level','power_num','box_num','trc_url','pay_password','status'])
  2156. ->first();
  2157. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  2158. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  2159. $boxNum = isset($userInfo['box_num'])? $userInfo['box_num'] : 0;
  2160. if(empty($userInfo) || $status != 1){
  2161. $this->error = 2024;
  2162. return false;
  2163. }
  2164. if($boxNum <= 0){
  2165. $this->error = 3101;
  2166. return false;
  2167. }
  2168. // 中奖结果
  2169. $drawRate = ConfigService::make()->getConfigByCode('box_award_rate',20);
  2170. $drawRate = $drawRate>0 && $drawRate<100? $drawRate : 20;
  2171. $drawMachineExpireDay = ConfigService::make()->getConfigByCode('draw_machine_time',30);
  2172. $drawMachineExpireDay = $drawMachineExpireDay>0 && $drawMachineExpireDay<360? $drawMachineExpireDay : 30;
  2173. DB::beginTransaction();
  2174. // 扣除次数
  2175. $updateData = ['box_num'=> DB::raw("box_num -1"),'update_time'=>time()];
  2176. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  2177. DB::rollBack();
  2178. $this->error = 3102;
  2179. return false;
  2180. }
  2181. // 是否中奖
  2182. $isAward = false;
  2183. $randNum = rand(1000,9999);
  2184. if($randNum > $drawRate * 10000/100){
  2185. $isAward = true;
  2186. }
  2187. // 未中奖,直接推送消息
  2188. if(!$isAward){
  2189. DB::commit();
  2190. // 消息
  2191. $dateTime = date('Y-m-d H:i:s');
  2192. MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【未中奖】,请继续加油。",3);
  2193. $this->error = 3107;
  2194. return ['id'=>0,'num'=>$randNum];
  2195. }
  2196. // 随机获取算力机
  2197. $machineInfo = MachineModel::where(['is_draw'=>1,'status'=>1,'mark'=>1])
  2198. ->select(['id as machine_id','name','price','power','month_rate','sl','day_wait_score','day_xd','day_score'])
  2199. ->orderBy(DB::raw('RAND()'))
  2200. ->first();
  2201. $machineInfo = $machineInfo? $machineInfo->toArray() : [];
  2202. $machineName = isset($machineInfo['name'])? $machineInfo['name'] : '';
  2203. if(empty($machineInfo)){
  2204. DB::rollBack();
  2205. $this->error = 3103;
  2206. return false;
  2207. }
  2208. $orderNo = get_order_num('DM');
  2209. $machineInfo['user_id'] = $userId;
  2210. $machineInfo['order_no'] = $orderNo;
  2211. $machineInfo['create_time'] = time();
  2212. $machineInfo['status'] = 1;
  2213. $machineInfo['mark'] = 1;
  2214. // 有效期
  2215. if($drawMachineExpireDay>0){
  2216. $machineInfo['expired_at'] = date('Y-m-d H:i:s', time() + $drawMachineExpireDay * 86400);
  2217. }
  2218. unset($machineInfo['name']);
  2219. if(!$id = DrawLogModel::insertGetId($machineInfo)){
  2220. DB::rollBack();
  2221. $this->error = 3102;
  2222. return false;
  2223. }
  2224. // 抽奖完成
  2225. DB::commit();
  2226. // 消息
  2227. $dateTime = date('Y-m-d H:i:s');
  2228. $machineName = $machineName? $machineName : '算力矿机';
  2229. MessageService::make()->pushMessage($userId,"盲盒抽奖结果通知","您在{$dateTime}(UTC+8)使用一次盲盒机会抽奖【已中奖】一台{$machineName},请查看您的矿机列表查收。",3);
  2230. $this->error = web_lang('3106',['name'=>$machineName]);
  2231. return ['id'=> $id,'name'=> $machineName,'num'=> $randNum];
  2232. }
  2233. public function getGroupList($userId, $pageSize=12)
  2234. {
  2235. $page = request()->post('page',1);
  2236. $kw = request()->post('kw','');
  2237. $cacheKey = "caches:groups:ulist_{$userId}_".md5("{$page}{$pageSize}{$kw}");
  2238. $datas = RedisService::get($cacheKey);
  2239. if ($datas) {
  2240. return [
  2241. 'pageSize' => $pageSize,
  2242. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  2243. 'list' => isset($datas['data']) ? $datas['data'] : []
  2244. ];
  2245. }
  2246. $datas = $this->model->from('member as a')
  2247. // ->distinct('b.id')
  2248. ->leftJoin('groups as b', function ($join) use($userId) {
  2249. $join->on('a.id', '=', 'b.user_id')->where(function($query) use($userId){
  2250. $query->whereRaw('FIND_IN_SET(?,lev_b.group_users)', $userId)->orWhereNull('b.id');
  2251. });
  2252. })
  2253. ->where(['a.mark'=>1])
  2254. ->where(function($query) use($kw){
  2255. if($kw){
  2256. $query->where('a.nickname','like',"%{$kw}%")
  2257. ->orWhere('a.id','=', intval($kw))
  2258. ->orWhere('b.id','=', intval($kw))
  2259. ->orWhere('b.name','like', "%{$kw}%");
  2260. }
  2261. })
  2262. ->where(function($query) use($userId){
  2263. $uids = MemberCollectModel::where(['user_id'=> $userId,'is_return'=>1,'status'=>1,'mark'=>1])->pluck('collect_uid');
  2264. $uids = $uids? $uids->toArray() : [];
  2265. // $uids1 = MessageModel::where(['to_uid'=> $userId,'group_id'=>0,'mark'=>1])->pluck('to_uid');
  2266. // $uids1 = $uids1? $uids1->toArray() : [];
  2267. // $uids = $uids && $uids1? array_merge($uids, $uids) : $uids;
  2268. $uids = array_unique($uids);
  2269. if($uids){
  2270. $query->whereIn('a.id', $uids);
  2271. }
  2272. })
  2273. ->select(['a.id','a.nickname','a.avatar','b.id as group_id','b.name as group_name','b.user_id as group_user_id','b.thumb as group_thumb','b.group_users'])
  2274. ->orderBy('a.update_time', 'desc')
  2275. ->orderBy('b.update_time','desc')
  2276. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  2277. $datas = $datas ? $datas->toArray() : [];
  2278. if ($datas) {
  2279. foreach ($datas['data'] as &$item){
  2280. $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
  2281. $item['avatar'] = get_image_url($item['avatar']);
  2282. $item['group_thumb'] = $item['group_thumb']? $item['group_thumb'] : '';
  2283. $item['users'] = [];
  2284. $groupUsers = isset($item['group_users']) && $item['group_users']? explode(',', $item['group_users']) : [];
  2285. if(empty($item['group_thumb'])){
  2286. $userIds = $groupUsers? array_slice($groupUsers,0,9) : [$userId];
  2287. $item['group_user_count'] = $groupUsers? count($groupUsers) : 1;
  2288. $item['users'] = GroupService::make()->getGroupUsers($item['group_id'], $userIds);
  2289. }
  2290. if(!in_array($userId , $groupUsers)){
  2291. $item['group_id'] = 0;
  2292. $item['users'] = [];
  2293. }
  2294. }
  2295. unset($item);
  2296. RedisService::set($cacheKey, $datas, rand(3, 5));
  2297. }
  2298. return [
  2299. 'pageSize' => $pageSize,
  2300. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  2301. 'list' => isset($datas['data']) ? $datas['data'] : []
  2302. ];
  2303. }
  2304. /**
  2305. * 我的矿机(中奖记录)
  2306. * @param $userId
  2307. * @param $params
  2308. * @param int $pageSize
  2309. * @return array
  2310. */
  2311. public function getMachineList($userId, $params, $pageSize=15)
  2312. {
  2313. $page = request()->post('page',1);
  2314. $cacheKey = "caches:machine:list_{$userId}_{$page}_".md5(json_encode($params,256));
  2315. $datas = RedisService::get($cacheKey);
  2316. if ($datas) {
  2317. return [
  2318. 'pageSize' => $pageSize,
  2319. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  2320. 'list' => isset($datas['data']) ? $datas['data'] : []
  2321. ];
  2322. }
  2323. $where = ['a.status' => 1,'a.user_id'=> $userId, 'a.mark' => 1,'b.mark'=>1];
  2324. $field = ['a.*','b.name'];
  2325. $datas = DrawLogModel::from('draw_logs as a')
  2326. ->leftjoin('machine as b','b.id','=','a.machine_id')
  2327. ->where($where)
  2328. ->where(function($query) use($params){
  2329. $type = isset($params['type'])? $params['type'] : 0;
  2330. if($type == 1){
  2331. $query->where('a.expired_at','>=', date('Y-m-d H:i:s'));
  2332. }else if ($type == 2){
  2333. $query->where('a.expired_at','<', date('Y-m-d H:i:s'));
  2334. }
  2335. })
  2336. ->select($field)
  2337. ->orderBy('a.create_time', 'desc')
  2338. ->orderBy('a.expired_at', 'desc')
  2339. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  2340. $datas = $datas ? $datas->toArray() : [];
  2341. if ($datas) {
  2342. RedisService::set($cacheKey, $datas, rand(3, 5));
  2343. }
  2344. return [
  2345. 'pageSize' => $pageSize,
  2346. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  2347. 'list' => isset($datas['data']) ? $datas['data'] : []
  2348. ];
  2349. }
  2350. }