MemberService.php 77 KB

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