MemberService.php 70 KB

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