MemberService.php 70 KB

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