MemberService.php 77 KB

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