MemberService.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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\LiveModel;
  16. use App\Models\MemberBankModel;
  17. use App\Models\MemberModel;
  18. use App\Models\MerchantModel;
  19. use App\Models\VideoModel;
  20. use App\Services\BaseService;
  21. use App\Services\CityService;
  22. use App\Services\ConfigService;
  23. use App\Services\EmailService;
  24. use App\Services\RedisService;
  25. use App\Services\SmsService;
  26. use App\Services\ToolService;
  27. use App\Services\UdunpayService;
  28. use App\Services\WalletService;
  29. use Illuminate\Support\Facades\DB;
  30. use phpQrcode\QRcode;
  31. /**
  32. * 会员管理-服务类
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. * Class MemberService
  36. * @package App\Services\Api
  37. */
  38. class MemberService extends BaseService
  39. {
  40. // 静态对象
  41. protected static $instance = null;
  42. /**
  43. * 构造函数
  44. * @author laravel开发员
  45. * @since 2020/11/11
  46. * MemberService constructor.
  47. */
  48. public function __construct()
  49. {
  50. $this->model = new MemberModel();
  51. }
  52. /**
  53. * 静态入口
  54. * @return MemberService|static|null
  55. */
  56. public static function make()
  57. {
  58. if (!self::$instance) {
  59. self::$instance = new static();
  60. }
  61. return self::$instance;
  62. }
  63. /**
  64. * 获取资料详情
  65. * @param $where
  66. * @param array $field
  67. */
  68. public function getInfo($where, $type = 'detail', array $field = [], $userId=0)
  69. {
  70. $defaultField = ['id', 'username','email', 'realname', 'mobile','gender','member_level', 'nickname', 'code','supper_point', 'parent_id','province_id','city_id','signature','power_num','trade_state','trc_url','recharge_trc_url', 'point_id', 'balance','trx','usdt','wait_score', 'score','pay_password','realname','idcard_check', 'member_level', 'status', 'avatar'];
  71. $withs = ['merchant','acceptor','parent','point','level'];
  72. if ($type == 'team') {
  73. $defaultField = ['id', 'username','email','member_level', 'nickname', 'code', 'balance', 'score','point_id','power_num','parent_id', 'status', 'avatar'];
  74. }else if($type == 'share'){
  75. $withs = ['parent','level'];
  76. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url', 'score', 'status', 'avatar'];
  77. }else if($type == 'check'){
  78. $withs = ['parent','level'];
  79. $defaultField = ['id', 'username', 'nickname','member_level', 'code', 'balance','usdt','trx','trc_url','wait_score', 'score', 'status', 'avatar'];
  80. }else if ($type == 'info'){
  81. $withs = ['parent','level'];
  82. }
  83. $field = $field ? $field : $defaultField;
  84. if (is_array($where)) {
  85. $info = $this->model->with($withs)->where('mark',1)->where($where)->select($field)->first();
  86. } else {
  87. $info = $this->model->with($withs)->where('mark',1)->where(['id' => (int)$where])->select($field)->first();
  88. }
  89. $info = $info ? $info->toArray() : [];
  90. if ($info && !in_array($type, ['auth', 'check','login'])) {
  91. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  92. $info['balance'] = moneyFormat($info['balance'], 2);
  93. $info['usdt'] = moneyFormat($info['usdt'], 2);
  94. $info['score'] = moneyFormat($info['score'], 2);
  95. $info['merchant'] = isset($info['merchant']) && $info['merchant']? $info['merchant'] : ['id'=>0];
  96. $info['acceptor'] = isset($info['acceptor']) && $info['acceptor']? $info['acceptor'] : ['id'=>0];
  97. $info['level'] = isset($info['level']) && $info['level']? $info['level'] : ['id'=>0,'name'=>'普通用户'];
  98. $info['custom_phone'] = ConfigService::make()->getConfigByCode('custom_phone');
  99. $info['custom_telegram'] = ConfigService::make()->getConfigByCode('custom_telegram');
  100. $info['custom_email'] = ConfigService::make()->getConfigByCode('custom_email');
  101. // 二维码
  102. if (in_array($type, ['detail'])) {
  103. if (isset($info['wxpay_qrcode'])) {
  104. $info['wxpay_qrcode'] = $info['wxpay_qrcode'] ? get_image_url($info['wxpay_qrcode']) : '';
  105. }
  106. if (isset($info['alipay_qrcode'])) {
  107. $info['alipay_qrcode'] = $info['alipay_qrcode'] ? get_image_url($info['alipay_qrcode']) : '';
  108. }
  109. $info['parent'] = $info['parent']? $info['parent'] : ['id'=>0,'nickname' => '无', 'code' => '无'];
  110. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  111. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  112. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  113. if($userId != $info['id']){
  114. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  115. }else{
  116. $info['is_follow'] = 1;
  117. }
  118. }
  119. else if ($type == 'info') {
  120. $liveOpenLevel = ConfigService::make()->getConfigByCode('live_open_level',0);
  121. $liveOpenLevel = $liveOpenLevel>0? $liveOpenLevel : 0;
  122. $info['live_open'] = $info['member_level']>=$liveOpenLevel? 1 : 0;
  123. }
  124. else if ($type == 'recharge') {
  125. $wallet = WalletService::make()->getWallet(1);
  126. $info['recharge_trc_url'] = isset($wallet['address'])? $wallet['address'] : '';
  127. $info['xd_price'] = ConfigService::make()->getConfigByCode('xd_price',100);
  128. if($info['recharge_trc_url']){
  129. $qrcode = $this->makeQrcode($info['recharge_trc_url']);
  130. $info['trc_qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  131. }else{
  132. $info['trc_qrcode'] = '';
  133. }
  134. }
  135. else if ($type == 'team' || $type == 'share') {
  136. $inviteUrl = get_web_url('/#/pages/register/index?code=' . $info['code']);
  137. $qrcode = $this->makeQrcode($inviteUrl);
  138. $info['qrcode'] = $qrcode ? get_image_url($qrcode) : '';
  139. $info['invite_url'] = $inviteUrl;
  140. $info['qrcode_base64'] = $qrcode?getImageContent($qrcode):'';
  141. $info['team_count1'] = $this->getUserCountByType($info['id'], 1, 0); // 直推人数
  142. $info['team_count2'] = $this->getUserCountByType($info['id'], 3, 0); // 滑落人数
  143. $info['team_count'] = $this->getUserCountByType($info['id'], 2, 0); // 团队人数
  144. }else {
  145. // 默认地址
  146. $info['addressData'] = MemberAddressService::make()->getBindInfo($info['id']);
  147. }
  148. }
  149. return $info;
  150. }
  151. /**
  152. * 获取主页信息
  153. * @param $where
  154. * @param array $field
  155. */
  156. public function getHomeInfo($id, $userId=0)
  157. {
  158. $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'];
  159. $info = $this->model->where('mark',1)->where(['id' => $id])->select($field)->first();
  160. $info = $info ? $info->toArray() : [];
  161. if ($info) {
  162. $info['avatar'] = $info['avatar'] ? get_image_url($info['avatar']) : get_image_url('/images/member/logo.png');
  163. $info['fans'] = (int)MemberCollectService::make()->getCount($info['id'], 1,1); // 粉丝数量(被关注)
  164. $info['follow'] = (int)MemberCollectService::make()->getCount($info['id'], 1,2); // 关注数量
  165. $info['like_num'] = (int)VideoModel::where(['user_id'=>$info['id'],'mark'=>1])->sum('like_num'); // 点赞喜欢数量
  166. $info['is_follow'] = (int)MemberCollectService::make()->checkCollect($userId, $info['id'],1); // 是否关注了
  167. $info['is_fans'] = (int)MemberCollectService::make()->checkCollect($info['id'], $userId,1); // 是否我的粉丝
  168. $info['live_id'] = (int)LiveModel::where(['user_id'=> $info['id'],'status'=>1,'mark'=>1])->orderBy('create_time','desc')->value('id'); // 是否正在直播
  169. }
  170. return $info;
  171. }
  172. /**
  173. * 获取用户缓存信息
  174. * @param $where
  175. * @param array $field
  176. * @param int $expired
  177. * @return array|mixed
  178. */
  179. public function getCacheInfo($where, $field = [], $expired = 0)
  180. {
  181. $cacheKey = "caches:member:info:cache_" . md5(json_encode($where, 256) . json_encode($field, 256) . $expired);
  182. $info = RedisService::get($cacheKey);
  183. if ($info) {
  184. return $info;
  185. }
  186. $defaultField = ['id', 'username', 'realname', 'mobile', 'nickname', 'code', 'parent_id', 'balance','usdt', 'score', 'member_level', 'status', 'avatar'];
  187. $field = $field ? $field : $defaultField;
  188. $info = $this->model->where($where)->where('mark', 1)->select($field)->first();
  189. $info = $info ? $info->toArray() : [];
  190. if ($info) {
  191. if (isset($info['avatar'])) {
  192. $info['avatar'] = $info['avatar']? $info['avatar'] : '/images/member/logo.png';
  193. $info['avatar_preview'] = $info['avatar']? get_image_url($info['avatar']) : '';
  194. }
  195. RedisService::set($cacheKey, $info, $expired ? $expired : rand(3, 5));
  196. }
  197. return $info;
  198. }
  199. /**
  200. * 生成普通参数二维码
  201. * @param $str 参数
  202. * @param bool $refresh 是否重新生成
  203. * @return bool
  204. */
  205. public function makeQrcode($str, $refresh = false, $size = 4, $margin = 2, $level = 2)
  206. {
  207. $basePath = base_path() . '/public';
  208. $qrFile = '/images/qrcode/';
  209. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  210. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  211. }
  212. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  213. $qrFile = $qrFile . "C_{$key}.png";
  214. $cacheKey = "caches:qrcodes:member_" . $key;
  215. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  216. return $qrFile;
  217. }
  218. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  219. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  220. return false;
  221. }
  222. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  223. return $qrFile;
  224. }
  225. /**
  226. * 获取团队用户数量
  227. * @param $userId 当前用户ID
  228. * @param int $type 层级:1-直推,2-团队
  229. * @param int $isPoint 节点:1-滑落推荐,0-直接推荐
  230. * @return array|mixed
  231. */
  232. public function getUserCountByType($userId, $type = 1, $isPoint=0)
  233. {
  234. $cacheKey = "caches:teams:count_{$userId}_{$type}_{$isPoint}";
  235. $data = RedisService::get($cacheKey);
  236. if ($data) {
  237. return $data;
  238. }
  239. $where = ['status' => 1, 'mark' => 1];
  240. $data = $this->model->where($where)
  241. ->where(function ($query) use ($type, $isPoint, $userId) {
  242. if($isPoint){
  243. if ($type == 1) { // 滑落推荐
  244. $query->where('point_id', $userId);
  245. } else if($type == 2){ // 滑落团队人数
  246. $query->whereRaw('FIND_IN_SET(?,points)', $userId);
  247. }
  248. }else{
  249. if ($type == 1) { // 直推人数
  250. $query->where('parent_id', $userId);
  251. } else if($type == 2){ // 团队人数
  252. $query->whereRaw("FIND_IN_SET({$userId},parents)");
  253. } else if($type == 3){ // 滑落人数
  254. $query->where('parent_id', $userId)->where('point_id','!=', $userId);
  255. }
  256. }
  257. })->count('id');
  258. if ($data) {
  259. RedisService::set($cacheKey, $data, rand(3, 5));
  260. }
  261. return $data;
  262. }
  263. /**
  264. * 分销用户列表
  265. * @param $userId
  266. * @param $params
  267. * @param int $pageSize
  268. * @return array
  269. */
  270. public function getTeamList($userId, $params, $pageSize=15)
  271. {
  272. $page = request()->post('page',1);
  273. $cacheKey = "caches:teams:list_{$userId}_{$page}";
  274. $datas = RedisService::get($cacheKey);
  275. if ($datas) {
  276. return [
  277. 'pageSize' => $pageSize,
  278. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  279. 'list' => isset($datas['data']) ? $datas['data'] : []
  280. ];
  281. }
  282. $where = ['status' => 1, 'mark' => 1];
  283. $field = ['id','avatar', 'nickname', 'username', 'email', 'balance', 'parent_id','power_num','point_id','create_time', 'status'];
  284. $datas = $this->model->with(['level'])->where($where)
  285. ->where(function ($query) use ($userId) {
  286. $query->where('parent_id', $userId);
  287. })
  288. ->where(function($query) use($params){
  289. $kw = isset($params['kw'])? trim($params['kw']) : '';
  290. if($kw){
  291. $query->where('id','=', "%{$kw}%")->orWhere('email','like',"%{$kw}%")->orWhere('username','like',"%{$kw}%");
  292. }
  293. })
  294. ->select($field)
  295. ->orderBy('create_time', 'desc')
  296. ->orderBy('id', 'desc')
  297. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  298. $datas = $datas ? $datas->toArray() : [];
  299. if ($datas) {
  300. foreach ($datas['data'] as &$item) {
  301. $item['avatar'] = $item['avatar']? $item['avatar'] : '/images/member/logo.png';
  302. $item['avatar'] = get_image_url($item['avatar']);
  303. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'y-m-d H:i') : '';
  304. $item['is_online'] = RedisService::get("auths:info:".$item['id'])? 1: 0;
  305. }
  306. unset($item);
  307. RedisService::set($cacheKey, $datas, rand(5, 10));
  308. }
  309. return [
  310. 'pageSize' => $pageSize,
  311. 'total' => isset($datas['total']) ? $datas['total'] : 0,
  312. 'list' => isset($datas['data']) ? $datas['data'] : []
  313. ];
  314. }
  315. /**
  316. * 手机号是否已注册
  317. * @param $mobile
  318. * @return mixed
  319. */
  320. public function checkPhoneExists($mobile)
  321. {
  322. return parent::checkExists('mobile', $mobile); // TODO: Change the autogenerated stub
  323. }
  324. /**
  325. * 账号注册
  326. * @param $params
  327. * @return array|false
  328. */
  329. public function register($params)
  330. {
  331. // 授权
  332. $email = isset($params['email']) ? trim($params['email']) : '';
  333. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  334. $nickname = isset($params['nickname']) ? trim($params['nickname']) : '';
  335. $code = isset($params['code']) ? trim($params['code']) : '';
  336. $scene = isset($params['scene']) ? $params['scene'] : '';
  337. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  338. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  339. if (empty($params) || empty($email) || $code <= 0) {
  340. $this->error = 2014;
  341. return false;
  342. }
  343. // 验证码
  344. if (!EmailService::make()->check($email, $code, $scene)) {
  345. $this->error = EmailService::make()->getError();
  346. return false;
  347. }
  348. // 验证是否注册
  349. if($this->model->where(['email'=> $email,'mark'=>1])->value('id')){
  350. $this->error = 2009;
  351. return false;
  352. }
  353. // 推荐人
  354. $parentId = 0;
  355. $pointId = 0;
  356. $parents = '';
  357. $points = '';
  358. if ($inviteCode) {
  359. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  360. ->select(['id', 'parents', 'parent_id'])
  361. ->first();
  362. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  363. $parents = isset($inviteInfo['parents']) ? $parentId.','.$inviteInfo['parents'] : ($parentId ? $parentId . ',' : '');
  364. // 挂靠节点
  365. if($parentId>0){
  366. $pointId = $this->getPointParentId($parentId);
  367. if($pointId){
  368. $pointParent = $this->model->where(['id'=> $pointId,'mark'=>1])->select(['id','points'])->first();
  369. $points = isset($pointParent['points']) ? $pointId.','.$pointParent['points'] : ($pointId ? $pointId . ',' : '');
  370. }
  371. }
  372. }
  373. // 注册
  374. $id = $this->model->max('id') + 1;
  375. $system = isset($params['system'])? $params['system'] : [];
  376. $ip = get_client_ip();
  377. $ipData = ToolService::make()->getIpAddress($ip,'');
  378. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  379. $city = isset($ipData['city'])? $ipData['city'] : '';
  380. $emailName = explode('@', $email)[0];
  381. // 钱包
  382. $data = [
  383. 'parent_id' => $parentId,
  384. 'point_id' => $pointId,
  385. 'points' => $points,
  386. 'openid' => '',
  387. 'avatar' => '',
  388. 'nickname' => $nickname ? $nickname : '用户'.substr($emailName,-8,8),
  389. 'username' => $email,
  390. 'password' => get_password('xl123456'),
  391. 'code' => strtoupper(get_random_code(9, 'X', "{$id}")),
  392. 'email' => $email,
  393. 'mobile' => $mobile,
  394. 'recharge_trc_url' => UdunpayService::make()->createAddress(195),
  395. 'parents' => $parents,
  396. 'province_id' => CityService::make()->getFieldByName($province),
  397. 'city_id' => CityService::make()->getFieldByName($city),
  398. 'app_uuid' => isset($system['uuid']) ? $system['uuid'] : '',
  399. 'device' => $appSources == 'android' ? 2 : 1,
  400. 'status' => 1,
  401. 'balance' => 0,
  402. 'score' => 0,
  403. 'mark' => 1,
  404. 'login_ip' => $ip,
  405. 'create_time' => time(),
  406. ];
  407. $userId = $this->model->insertGetId($data);
  408. $this->error = 2008;
  409. return [
  410. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  411. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'point_id'=> $pointId, 'username' => $data['username']],
  412. ];
  413. }
  414. /**
  415. * 邮箱登录
  416. * @param $params
  417. * @return array|false
  418. */
  419. public function loginByEmail($params)
  420. {
  421. // 授权
  422. $email = isset($params['email']) ? $params['email'] : '';
  423. $code = isset($params['code']) ? $params['code'] : '';
  424. $scene = isset($params['scene']) ? $params['scene'] : '';
  425. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  426. if (empty($params) || empty($email) || empty($scene) || $code <= 0) {
  427. $this->error = 2014;
  428. return false;
  429. }
  430. // 验证码
  431. if (!EmailService::make()->check($email, $code, $scene)) {
  432. $this->error = EmailService::make()->getError();
  433. return false;
  434. }
  435. // 验证是否注册,没有则注册
  436. $data = $this->model->where(['email' => $email, 'mark' => 1])->select(['id', 'username','point_id', 'parent_id', 'code', 'status'])->first();
  437. $data = $data ? $data->toArray() : [];
  438. $userId = isset($data['id']) ? $data['id'] : 0;
  439. $status = isset($data['status']) ? $data['status'] : 0;
  440. if(empty($data) || $userId<=0){
  441. $this->error = 2001;
  442. return false;
  443. }
  444. if ($status != 1) {
  445. $this->error = 2015;
  446. return false;
  447. }
  448. // 获取登录授权token
  449. $jwt = new Jwt('jwt_dys_app');
  450. $token = $jwt->getToken($userId);
  451. // 结果返回
  452. $result = [
  453. 'access_token' => $token,
  454. 'info' => ['uid' => $userId,'parent_id'=> $data['parent_id'], 'username' => $data['username']],
  455. ];
  456. // 用户信息
  457. $ip = get_client_ip();
  458. $updateData = [
  459. 'login_time' => time(),
  460. 'login_ip' => $ip,
  461. ];
  462. if(!RedisService::get("caches:member:updateArea:{$userId}")){
  463. $ipData = ToolService::make()->getIpAddress($ip,'');
  464. $province = isset($ipData['regionName'])? $ipData['regionName'] : '';
  465. $city = isset($ipData['city'])? $ipData['city'] : '';
  466. $updateData['province_id'] = CityService::make()->getFieldByName($province);
  467. $updateData['city_id'] = CityService::make()->getFieldByName($city);
  468. }
  469. $this->model->where(['id'=> $userId])->update($updateData);
  470. $this->error = 2004;
  471. $data['token'] = $token;
  472. RedisService::set("caches:member:updateArea:{$userId}", $updateData, 3600);
  473. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  474. return $result;
  475. }
  476. /**
  477. * 手机号登录
  478. * @param $params
  479. * @return array|false
  480. */
  481. public function loginByMobile($params)
  482. {
  483. // 授权
  484. $mobile = isset($params['mobile']) ? $params['mobile'] : '';
  485. $code = isset($params['sms_code']) ? $params['sms_code'] : '';
  486. $smsType = isset($params['sms_type']) ? $params['sms_type'] : '';
  487. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  488. $openid = isset($params['openid']) ? $params['openid'] : '';
  489. $avatar = isset($params['avatar']) ? $params['avatar'] : '';
  490. $regType = isset($params['type']) ? $params['type'] : 'app';
  491. $appSources = isset($params['app_sources']) ? $params['app_sources'] : '';
  492. $inviteCode = isset($params['invite_code']) ? $params['invite_code'] : '';
  493. if (empty($params) || empty($mobile) || $code <= 0) {
  494. $this->error = 2014;
  495. return false;
  496. }
  497. // 验证码
  498. if (!SmsService::make()->check($mobile, $code, $smsType?$smsType:'login')) {
  499. $this->error = SmsService::make()->getError();
  500. return false;
  501. }
  502. // 推荐人
  503. $parentId = 0;
  504. $parents = '';
  505. if ($inviteCode) {
  506. $inviteInfo = $this->model->where(['code' => $inviteCode, 'mark' => 1])
  507. ->select(['id', 'parents', 'parent_id'])
  508. ->first();
  509. $parentId = isset($inviteInfo['id']) ? $inviteInfo['id'] : 0;
  510. $parents = isset($inviteInfo['parents']) ? $inviteInfo['parents'] . $parentId . ',' : ($parentId ? $parentId . ',' : '');
  511. }
  512. // 验证是否注册,没有则注册
  513. $data = $this->model->with(['merchant','mechanic'])->where(['mobile' => $mobile, 'mark' => 1])->select(['id', 'openid', 'username', 'parent_id', 'code', 'push_cid', 'status'])->first();
  514. $data = $data ? $data->toArray() : [];
  515. $userId = isset($data['id']) ? $data['id'] : 0;
  516. $status = isset($data['status']) ? $data['status'] : 0;
  517. if ($userId && $status != 1) {
  518. $this->error = 2015;
  519. return false;
  520. }
  521. // 是否是商家或技师,有订单提醒
  522. $noticeUser = ['id'=> 0,'uid'=>$userId,'type'=>1];
  523. $merchant = isset($data['merchant'])? $data['merchant'] : [];
  524. $merchantStatus = isset($merchant['status'])? $merchant['status'] : 0;
  525. $mechanic = isset($data['mechanic'])? $data['mechanic'] : [];
  526. $mechanicStatus = isset($mechanic['status'])? $mechanic['status'] : 0;
  527. if($merchantStatus==2){
  528. $uid = isset($merchant['id'])? $merchant['id'] : 0;
  529. if($uid>0){
  530. $noticeUser = ['id'=>$uid,'type'=>2,'uid'=> $userId];
  531. }
  532. }else if($mechanicStatus == 2){
  533. $uid = isset($mechanic['id'])? $mechanic['id'] : 0;
  534. if($uid>0){
  535. $noticeUser = ['id'=>$uid,'type'=>3,'uid'=>$userId];
  536. }
  537. }
  538. $pushCid = isset($params['push_cid']) ? $params['push_cid'] : '';
  539. if (!$userId) {
  540. $id = $this->model->max('id') + 1;
  541. $data = [
  542. 'parent_id' => $parentId,
  543. 'openid' => $openid,
  544. 'avatar' => $avatar,
  545. 'nickname' => $nickname ? $nickname : get_random_code(4, '用户u').substr($mobile,-4,4),
  546. 'username' => get_username($id),
  547. 'password' => get_password('123456'),
  548. 'code' => strtoupper(get_random_code(8, 'D', "{$id}")),
  549. 'mobile' => $mobile,
  550. 'parents' => $parents,
  551. 'push_cid' => isset($params['push_cid']) ? $params['push_cid'] : '',
  552. 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '',
  553. 'device' => $appSources == 'android' ? 2 : 1,
  554. 'status' => 1,
  555. 'balance' => 0,
  556. 'score' => 0,
  557. 'mark' => 1,
  558. 'login_time' => time(),
  559. 'login_ip' => get_client_ip(),
  560. 'create_time' => time(),
  561. ];
  562. $userId = $this->model->insertGetId($data);
  563. } elseif ($regType != 'h5') {
  564. // 登录更新
  565. $updateData = [
  566. 'app_uuid' => isset($params['uuid']) ? $params['uuid'] : '',
  567. 'login_count' => DB::raw("login_count+1"),
  568. 'login_time' => time(),
  569. 'login_ip' => get_client_ip(),
  570. 'update_time' => time(),
  571. ];
  572. if ($pushCid) {
  573. $updateData['push_cid'] = $pushCid;
  574. }
  575. $this->model->where(['id' => $userId])->update($updateData);
  576. }
  577. // H5 邀请注册,无需登录
  578. if ($regType == 'h5') {
  579. $this->error = $status ? 2023 : 2022;
  580. return [
  581. 'app_url' => ConfigService::make()->getConfigByCode("app_{$appSources}_url"),
  582. 'info' => ['uid' => $userId, 'invite_id' => $parentId, 'username' => $data['username']],
  583. ];
  584. }
  585. // 获取登录授权token
  586. $jwt = new Jwt('jwt_dys_app');
  587. $token = $jwt->getToken($userId);
  588. // 结果返回
  589. $result = [
  590. 'access_token' => $token,
  591. 'info' => ['uid' => $userId,'notice_user'=>$noticeUser, 'openid' => $data['openid'], 'username' => $data['username']],
  592. ];
  593. // 用户信息
  594. $this->error = 2004;
  595. $data['token'] = $token;
  596. unset($data['password']);
  597. // 实现初始化账单明细表
  598. AccountLogModel::where('id','<=',1)->value('id');
  599. RedisService::clear( "caches:map:{$userId}");
  600. RedisService::set("auths:info:{$userId}", $data, 3 * 24 * 3600);
  601. return $result;
  602. }
  603. /**
  604. * 修改头像/商家logo/技师头像
  605. * @param $userId
  606. * @param $avatar
  607. * @return mixed
  608. */
  609. public function saveAvatar($userId, $avatar)
  610. {
  611. $type = request()->post('type', 1);
  612. if($type == 1){
  613. $oldAvatar = $this->model->where(['id' => $userId])->value('avatar');
  614. if ($this->model->where(['id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  615. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  616. @unlink(ATTACHMENT_PATH . $oldAvatar);
  617. }
  618. return true;
  619. }
  620. }else if($type == 2){
  621. $oldAvatar = MerchantModel::where(['user_id' => $userId])->value('logo');
  622. if (MerchantModel::where(['user_id' => $userId])->update(['logo' => $avatar, 'update_time' => time()])) {
  623. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  624. @unlink(ATTACHMENT_PATH . $oldAvatar);
  625. }
  626. return true;
  627. }
  628. }else if($type == 3){
  629. $oldAvatar = MechanicModel::where(['user_id' => $userId])->value('avatar');
  630. if (MechanicModel::where(['user_id' => $userId])->update(['avatar' => $avatar, 'update_time' => time()])) {
  631. if ($oldAvatar && file_exists(ATTACHMENT_PATH . $oldAvatar)) {
  632. @unlink(ATTACHMENT_PATH . $oldAvatar);
  633. }
  634. return true;
  635. }
  636. }
  637. return false;
  638. }
  639. /**
  640. * 修改账号
  641. * @param $userId
  642. * @param $params
  643. * @return bool
  644. */
  645. public function modify($userId, $params)
  646. {
  647. $email = isset($params['email']) ? $params['email'] : '';
  648. $password = isset($params['password']) ? $params['password'] : '';
  649. $payPassword = isset($params['pay_password']) ? $params['pay_password'] : '';
  650. $scene = isset($params['scene'])? trim($params['scene']) : '';
  651. // 用户验证
  652. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','pay_password', 'status'])->first();
  653. if (!$info) {
  654. $this->error = 2001;
  655. return false;
  656. }
  657. // 使用状态校验
  658. if ($info['status'] != 1) {
  659. $this->error = 2009;
  660. return false;
  661. }
  662. // 密码校验
  663. $data = ['update_time' => time()];
  664. // 验证交易密码
  665. if(isset($params['pay_password']) && $scene != 'trade'){
  666. $userPayPassword = isset($info['pay_password'])? $info['pay_password'] : '';
  667. if(empty($userPayPassword)){
  668. $this->error = 1040;
  669. return false;
  670. }
  671. if($userPayPassword != get_password($payPassword)){
  672. $this->error = 2038;
  673. return false;
  674. }
  675. }
  676. // 邮箱验证
  677. if (isset($params['email']) && $email) {
  678. // 修改邮箱
  679. $newEmail = isset($params['new_email'])? trim($params['new_email']) : '';
  680. if(isset($params['new_email']) && $newEmail){
  681. $data['email'] = $newEmail;
  682. $data['username'] = $newEmail;
  683. $checkInfo = $this->model->where(['username' => $newEmail, 'mark' => 1])->select(['id', 'status'])->first();
  684. if ($checkInfo && $checkInfo['id'] != $userId) {
  685. $this->error = 2005;
  686. return false;
  687. }
  688. }
  689. // 邮箱验证码
  690. $code = isset($params['code'])? trim($params['code']) : '';
  691. $checkEmail = $scene == 'modify_email'? $newEmail : $email;
  692. if (!EmailService::make()->check($checkEmail, $code, $scene)) {
  693. $this->error = EmailService::make()->getError();
  694. return false;
  695. }
  696. }
  697. // 修改数据
  698. $nickname = isset($params['nickname']) ? $params['nickname'] : '';
  699. if (isset($params['nickname']) && $nickname) {
  700. $data['nickname'] = $nickname;
  701. }
  702. $gender = isset($params['gender']) ? intval($params['gender']) : 3;
  703. if (isset($params['gender']) && $gender) {
  704. $data['gender'] = $gender;
  705. }
  706. $intro = isset($params['intro']) ? $params['intro'] : '';
  707. if (isset($params['intro']) && $intro) {
  708. $data['intro'] = $intro;
  709. }
  710. if (isset($params['pay_password']) && $payPassword) {
  711. $payPassword = get_password($payPassword);
  712. $data['pay_password'] = $payPassword;
  713. }
  714. $this->model->where(['id' => $userId])->update($data);
  715. $this->error = 1008;
  716. return true;
  717. }
  718. /**
  719. * 身份认证
  720. * @param $userId
  721. * @param $params
  722. * @return bool
  723. */
  724. public function auth($userId, $params)
  725. {
  726. // 用户验证
  727. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id','username', 'status'])->first();
  728. if (!$info) {
  729. $this->error = 2001;
  730. return false;
  731. }
  732. // 使用状态校验
  733. if ($info['status'] != 1) {
  734. $this->error = 2009;
  735. return false;
  736. }
  737. // 密码校验
  738. $data = ['update_time' => time(),'idcard_check'=>1];
  739. if (isset($params['realname']) && $params['realname']) {
  740. $data['realname'] = trim($params['realname']);
  741. }
  742. $idcard = isset($params['idcard']) && $params['idcard'];
  743. if ($idcard) {
  744. $data['idcard'] = trim($params['idcard']);
  745. }
  746. if (isset($params['idcard_front_img'][0]) && $params['idcard_front_img'][0]) {
  747. $data['idcard_front_img'] = get_image_path($params['idcard_front_img'][0]['url']);
  748. }
  749. if (isset($params['idcard_back_img'][0]) && $params['idcard_back_img'][0]) {
  750. $data['idcard_back_img'] = get_image_path($params['idcard_back_img'][0]['url']);
  751. }
  752. $this->model->where(['id' => $userId])->update($data);
  753. // 发送消息
  754. $params = [
  755. 'title'=> "身份认证提交成功",
  756. 'body' => "您的身份认证信息已提交成功,请耐心等候审核",
  757. 'type' => 1, // 1-公告通知,2-订单通知,3-交易通知,4-其他
  758. 'content' => [
  759. 'account' => ['name' => '账号', 'text' => $info['username']],
  760. 'pay_time' => ['name' => '申请时间', 'text' => date('Y-m-d H:i:s')],
  761. 'status' => ['name' => '状态', 'text' => '待审核'],
  762. ],
  763. 'click_type' => 'payload',
  764. 'url' => '/pages/my/profile/auth',
  765. ];
  766. PushService::make()->pushMessageByUser($userId, $params, 0);
  767. $this->error = 2036;
  768. return true;
  769. }
  770. /**
  771. * 转账
  772. * @param $userId
  773. * @param $params
  774. * @return bool
  775. */
  776. public function transfer($userId, $params)
  777. {
  778. $toUserId = isset($params['to_user_id'])? intval($params['to_user_id']) : 0;
  779. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  780. $money = isset($params['money'])? floatval($params['money']) : 0;
  781. if(empty($toUserId) || $money<=0){
  782. $this->error = 2420;
  783. return false;
  784. }
  785. $cacheKey = "caches:members:transfer:{$userId}";
  786. if(RedisService::get($cacheKey)){
  787. $this->error = 1034;
  788. return false;
  789. }
  790. // 验证账户
  791. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  792. ->select(['id','nickname','username','usdt','pay_password','balance','status'])
  793. ->first();
  794. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  795. $usdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  796. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  797. $nickname = isset($userInfo['nickname'])? $userInfo['nickname'] : '';
  798. if(empty($userInfo) || $status != 1){
  799. $this->error = 2024;
  800. return false;
  801. }
  802. // 余额支付支付密码验证
  803. if(empty($userPayPassword)){
  804. $this->error = 1040;
  805. return false;
  806. }
  807. $payPassword = get_password($payPassword);
  808. if($payPassword != $userPayPassword){
  809. $this->error = 2038;
  810. return false;
  811. }
  812. // 验证账户
  813. $accountInfo = $this->model->where(['id'=> $toUserId,'mark'=>1])
  814. ->select(['id','nickname','usdt','username','balance','status'])
  815. ->first();
  816. $status = isset($accountInfo['status'])? $accountInfo['status'] : 0;
  817. $accountUsdt = isset($accountInfo['usdt'])? $accountInfo['usdt'] : 0;
  818. $toNickname = isset($accountInfo['nickname'])? $accountInfo['nickname'] : '';
  819. if(empty($accountInfo) || $status != 1){
  820. $this->error = 2421;
  821. return false;
  822. }
  823. if($money > $usdt){
  824. $this->error = 2422;
  825. return false;
  826. }
  827. // 用户余额转账到用户
  828. DB::beginTransaction();
  829. RedisService::set($cacheKey, $params, rand(2,5));
  830. $updateData = ['usdt'=> DB::raw("usdt - {$money}"),'update_time'=> time()];
  831. if(!$this->model->where(['id'=> $userId,'mark'=>1])->update($updateData)){
  832. DB::rollBack();
  833. $this->error = 2028;
  834. RedisService::clear($cacheKey);
  835. return false;
  836. }
  837. // 明细
  838. $orderNo = get_order_num('TR');
  839. $log = [
  840. 'user_id' => $userId,
  841. 'source_id' => $toUserId,
  842. 'source_order_no' => $orderNo,
  843. 'type' => 6,
  844. 'coin_type' => 1,
  845. 'user_type'=> 1,
  846. 'money' => -$money,
  847. 'actual_money' => -$money,
  848. 'balance' => $usdt,
  849. 'create_time' => time(),
  850. 'update_time' => time(),
  851. 'remark' => "USDT转账",
  852. 'status' => 1,
  853. 'mark' => 1,
  854. ];
  855. if(!AccountLogModel::insertGetId($log)){
  856. DB::rollBack();
  857. $this->error = 2423;
  858. RedisService::clear($cacheKey);
  859. return false;
  860. }
  861. // 到账
  862. $fee = ConfigService::make()->getConfigByCode('transfer_fee_rate',5);
  863. $fee = $fee>0 && $fee<100? moneyFormat($fee/100, 2) : 0;
  864. $feeUsdt = round($money * $fee,2);
  865. $realUsdt = moneyFormat($money - $feeUsdt,2);
  866. $updateData = ['usdt'=> DB::raw("usdt + {$realUsdt}"),'update_time'=> time()];
  867. if(!$this->model->where(['id'=> $toUserId,'mark'=>1])->update($updateData)){
  868. DB::rollBack();
  869. $this->error = 2424;
  870. RedisService::clear($cacheKey);
  871. return false;
  872. }
  873. // 明细
  874. $log = [
  875. 'user_id' => $toUserId,
  876. 'source_id' => $userId,
  877. 'source_order_no' => $orderNo,
  878. 'type' => 6,
  879. 'coin_type' => 1,
  880. 'user_type'=> 1,
  881. 'money' => $realUsdt,
  882. 'actual_money' => $realUsdt,
  883. 'balance' => $accountUsdt,
  884. 'create_time' => time(),
  885. 'update_time' => time(),
  886. 'remark' => "USDT转账",
  887. 'status' => 1,
  888. 'mark' => 1,
  889. ];
  890. if(!AccountLogModel::insertGetId($log)){
  891. DB::rollBack();
  892. $this->error = 2029;
  893. RedisService::clear($cacheKey);
  894. return false;
  895. }
  896. // 平台明细
  897. $log = [
  898. 'user_id' => 0,
  899. 'source_id' => $userId,
  900. 'source_order_no' => $orderNo,
  901. 'type' => 6,
  902. 'coin_type' => 1,
  903. 'user_type'=> 4,
  904. 'money' => $feeUsdt,
  905. 'actual_money' => $feeUsdt,
  906. 'balance' => 0,
  907. 'create_time' => time(),
  908. 'update_time' => time(),
  909. 'remark' => "USDT转账",
  910. 'status' => 1,
  911. 'mark' => 1,
  912. ];
  913. if(!AccountLogModel::insertGetId($log)){
  914. DB::rollBack();
  915. $this->error = 2029;
  916. RedisService::clear($cacheKey);
  917. return false;
  918. }
  919. // 平台
  920. FinanceService::make()->saveLog(0, $feeUsdt,1);
  921. // 消息
  922. $dateTime = date('Y-m-d H:i:s');
  923. MessageService::make()->pushMessage($userId,'USDT转账成功',"您在{$dateTime}(UTC+8)成功支付{$money}USDT转账给用户【{$toUserId}】{$toNickname}",3);
  924. $dateTime = date('Y-m-d H:i:s');
  925. MessageService::make()->pushMessage($toUserId,'USDT转账成功',"您在{$dateTime}(UTC+8)收到用户【{$userId}】{$nickname}的{$realUsdt}USDT转账",3);
  926. DB::commit();
  927. RedisService::clear($cacheKey);
  928. $this->error = 2425;
  929. return true;
  930. }
  931. /**
  932. * 余额充值
  933. * @param $userId
  934. * @param $params
  935. * @return array|false
  936. */
  937. public function recharge($userId, $params)
  938. {
  939. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  940. $usdt = isset($params['usdt'])? moneyFormat($params['usdt'], 2) : 0;
  941. $coinType = isset($params['coin_type']) && $params['coin_type']? intval($params['coin_type']) : 2;
  942. $payType = 10;
  943. if($usdt<=0){
  944. $this->error = 2031;
  945. return false;
  946. }
  947. $userInfo = $this->model->where(['id'=> $userId,'mark'=>1])
  948. ->select(['id','nickname','usdt','pay_password','balance','status'])
  949. ->first();
  950. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  951. $balance = isset($userInfo['balance'])? $userInfo['balance'] : 0;
  952. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  953. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  954. if(empty($userInfo) || $status != 1){
  955. $this->error = 2024;
  956. return false;
  957. }
  958. if($userPayPassword != get_password($payPassword)){
  959. $this->error = 2038;
  960. return false;
  961. }
  962. // 充值订单
  963. $orderNo = get_order_num('DR');
  964. $money = $usdt;
  965. // 星豆
  966. DB::beginTransaction();
  967. if($coinType == 2){
  968. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  969. $xdPrice = $xdPrice>0 && $xdPrice <=10000? $xdPrice : 100;
  970. $money = round($xdPrice * $usdt,2);
  971. if($usdt > $userUsdt){
  972. $this->error = 2035;
  973. return false;
  974. }
  975. // 扣除usdt余额
  976. $updateData = ['usdt'=>DB::raw("usdt - {$usdt}"),'balance'=>DB::raw("balance + {$money}"),'update_time'=>time()];
  977. if(!$this->model->where(['id'=> $userId])->update($updateData)){
  978. $this->error = 2036;
  979. DB::rollBack();
  980. return false;
  981. }
  982. }
  983. $data = [
  984. 'order_no'=> $orderNo,
  985. 'user_id'=> $userId,
  986. 'type'=> 1,
  987. 'user_type'=> 1,
  988. 'coin_type'=> 2,
  989. 'money'=> $usdt,
  990. 'actual_money'=> $money,
  991. 'pay_type'=> $payType,
  992. 'pay_status'=> 20,
  993. 'pay_at'=> date('Y-m-d H:i:s'),
  994. 'create_time'=> time(),
  995. 'update_time'=> time(),
  996. 'status'=> 2,
  997. 'mark'=> 1,
  998. ];
  999. if(!$orderId = BalanceLogModel::insertGetId($data)){
  1000. $this->error = 2033;
  1001. DB::rollBack();
  1002. return false;
  1003. }
  1004. // 扣除USDT
  1005. $log = [
  1006. 'user_id'=> $userId,
  1007. 'source_order_no'=> $data['order_no'],
  1008. 'user_type'=> 1,
  1009. 'type'=> 5,
  1010. 'coin_type'=> 1,
  1011. 'money'=> -$usdt,
  1012. 'actual_money'=> -$usdt,
  1013. 'balance'=> $userUsdt,
  1014. 'date'=> date('Y-m-d'),
  1015. 'create_time'=> time(),
  1016. 'remark'=> '星豆余额充值扣除',
  1017. 'status'=>1,
  1018. 'mark'=>1
  1019. ];
  1020. if(!AccountLogModel::insertGetId($log)){
  1021. $this->error = 2029;
  1022. DB::rollBack();
  1023. return false;
  1024. }
  1025. // 增加星豆余额
  1026. $log = [
  1027. 'user_id'=> $userId,
  1028. 'source_order_no'=> $data['order_no'],
  1029. 'user_type'=> 1,
  1030. 'type'=> 5,
  1031. 'coin_type'=> 2,
  1032. 'money'=> $usdt,
  1033. 'actual_money'=> $money,
  1034. 'balance'=> $balance,
  1035. 'date'=> date('Y-m-d'),
  1036. 'create_time'=> time(),
  1037. 'remark'=> '星豆余额充值',
  1038. 'status'=>1,
  1039. 'mark'=>1
  1040. ];
  1041. if(!AccountLogModel::insertGetId($log)){
  1042. $this->error = 2029;
  1043. DB::rollBack();
  1044. return false;
  1045. }
  1046. // 消息
  1047. $dateTime = date('Y-m-d H:i:s');
  1048. MessageService::make()->pushMessage($userId,'星豆余额充值成功',"您在{$dateTime}(UTC+8)成功支付{$usdt}USDT充值{$money}星豆",3);
  1049. DB::commit();
  1050. // 充值星豆任务
  1051. TaskService::make()->updateTask($userId,9, 0);
  1052. $this->error = 2037;
  1053. return ['order_id'=> $orderId,'balance'=> moneyFormat($balance + $money,2),'usdt'=> moneyFormat($userUsdt-$usdt, 2)];
  1054. }
  1055. /**
  1056. * 余额提现
  1057. * @param $userId
  1058. * @param $params
  1059. * @return array|false
  1060. */
  1061. public function withdraw($userId, $params)
  1062. {
  1063. $money = isset($params['money'])? floatval($params['money']) : 0;
  1064. $payPassword = isset($params['pay_password'])? trim($params['pay_password']) : '';
  1065. $userType = isset($params['user_type']) && $params['user_type']? intval($params['user_type']) : 1;
  1066. if($money<=0){
  1067. $this->error = 2401;
  1068. return false;
  1069. }
  1070. if(!in_array($userType,[1,2])){
  1071. $this->error = 2404;
  1072. return false;
  1073. }
  1074. $userInfo = $this->model->with(['merchant'])
  1075. ->where(['id'=> $userId,'mark'=>1])
  1076. ->select(['id','nickname','usdt','trc_url','pay_password','status'])
  1077. ->first();
  1078. $status = isset($userInfo['status'])? $userInfo['status'] : 0;
  1079. $userUsdt = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  1080. $userPayPassword = isset($userInfo['pay_password'])? $userInfo['pay_password'] : '';
  1081. $merchant = isset($userInfo['merchant'])? $userInfo['merchant'] : [];
  1082. $merchantUsdt = isset($merchant['usdt'])? $merchant['usdt'] : 0;
  1083. $merchantId = isset($merchant['id'])? $merchant['id'] : 0;
  1084. $merchantTradeStatus = isset($merchant['trade_status'])? $merchant['trade_status'] : 0;
  1085. if(empty($userInfo) || $status != 1){
  1086. $this->error = 2024;
  1087. return false;
  1088. }
  1089. if($userType == 2 && (empty($merchant) || !in_array($merchantTradeStatus,[1,2]))){
  1090. $this->error = 2024;
  1091. return false;
  1092. }
  1093. // 提现金额验证
  1094. $accountUsdt = $userType==1? $userUsdt : $merchantUsdt;
  1095. if ($money > $accountUsdt) {
  1096. $this->error = web_lang(2402, ['money' => $accountUsdt]);
  1097. return false;
  1098. }
  1099. // 提现账户
  1100. $trcUrl = isset($userInfo['trc_url']) ? $userInfo['trc_url'] : '';
  1101. if (empty($trcUrl)) {
  1102. $this->error = 2403;
  1103. return false;
  1104. }
  1105. if($userPayPassword != get_password($payPassword)){
  1106. $this->error = 2038;
  1107. return false;
  1108. }
  1109. $cacheKey = "caches:member:withdraw:lock_{$userId}";
  1110. if(RedisService::get($cacheKey)){
  1111. $this->error = 1034;
  1112. return false;
  1113. }
  1114. DB::beginTransaction();
  1115. RedisService::set($cacheKey, $userInfo, rand(2,3));
  1116. // 提现记录
  1117. $orderNo = get_order_num('DW');
  1118. $feeRate = ConfigService::make()->getConfigByCode('withdraw_fee_rate',5);
  1119. $feeRate = $feeRate>0 && $feeRate<100? moneyFormat($feeRate/100,2) : 0;
  1120. $fee = round($money*$feeRate, 2);
  1121. $realUsdt = moneyFormat($money - $fee, 2);
  1122. $data = [
  1123. 'order_no'=> $orderNo,
  1124. 'user_id'=> $userType==1? $userId : $merchantId,
  1125. 'type'=> 2,
  1126. 'user_type'=> $userType,
  1127. 'coin_type'=> 1,
  1128. 'money'=> $money,
  1129. 'actual_money'=> $realUsdt,
  1130. 'fee'=> $fee,
  1131. 'trc_url'=> $trcUrl,
  1132. 'pay_type'=> 20,
  1133. 'date'=> date('Y-m-d'),
  1134. 'create_time'=> time(),
  1135. 'update_time'=> time(),
  1136. 'status'=> 1,
  1137. 'mark'=> 1,
  1138. ];
  1139. if(!$id = BalanceLogModel::insertGetId($data)){
  1140. DB::rollBack();
  1141. $this->error = 2405;
  1142. RedisService::clear($cacheKey);
  1143. return false;
  1144. }
  1145. // 商户扣款
  1146. if($userType == 2){
  1147. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1148. if(!MerchantModel::where(['user_id'=> $userId,'mark'=>1])->update($updateData)){
  1149. DB::rollBack();
  1150. $this->error = 2406;
  1151. RedisService::clear($cacheKey);
  1152. return false;
  1153. }
  1154. // 明细
  1155. $log = [
  1156. 'user_id' => $merchantId,
  1157. 'source_id' => $userId,
  1158. 'source_order_no' => $orderNo,
  1159. 'type' => 5,
  1160. 'coin_type' => 1,
  1161. 'user_type'=> 2,
  1162. 'money' => -$money,
  1163. 'actual_money' => -$money,
  1164. 'balance' => $merchantUsdt,
  1165. 'create_time' => time(),
  1166. 'update_time' => time(),
  1167. 'remark' => "商户账户余额提现",
  1168. 'status' => 1,
  1169. 'mark' => 1,
  1170. ];
  1171. if (!AccountLogModel::insertGetId($log)) {
  1172. $this->error = 2407;
  1173. DB::rollBack();
  1174. RedisService::clear($cacheKey);
  1175. return false;
  1176. }
  1177. }
  1178. // 用户扣款
  1179. else{
  1180. $updateData = ['usdt'=>DB::raw("usdt - {$money}"),'update_time'=> time()];
  1181. if(!MemberModel::where(['id'=> $userId,'mark'=>1])->update($updateData)){
  1182. DB::rollBack();
  1183. $this->error = 2406;
  1184. RedisService::clear($cacheKey);
  1185. return false;
  1186. }
  1187. // 明细
  1188. $log = [
  1189. 'user_id' => $userId,
  1190. 'source_id' => 0,
  1191. 'source_order_no' => $orderNo,
  1192. 'type' => 5,
  1193. 'coin_type' => 1,
  1194. 'user_type'=> 1,
  1195. 'money' => -$money,
  1196. 'actual_money' => -$money,
  1197. 'balance' => $userUsdt,
  1198. 'create_time' => time(),
  1199. 'update_time' => time(),
  1200. 'remark' => "USDT余额提现",
  1201. 'status' => 1,
  1202. 'mark' => 1,
  1203. ];
  1204. if (!AccountLogModel::insertGetId($log)) {
  1205. $this->error = 2407;
  1206. DB::rollBack();
  1207. RedisService::clear($cacheKey);
  1208. return false;
  1209. }
  1210. }
  1211. DB::commit();
  1212. // 站内消息
  1213. $dateTime = date('Y-m-d H:i:s');
  1214. $title = $userType == 1 ? 'USDT余额提现申请成功' : '商户余额提现申请成功';
  1215. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额成功,请耐心等候审核!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额成功,请耐心等候审核!!!";
  1216. MessageService::make()->pushMessage($userId, $title, $message);
  1217. // 提现自动审核,低于该金额自动审核
  1218. $autoCheckUsdt = ConfigService::make()->getConfigByCode('withdraw_auto_money', 300);
  1219. $autoCheckUsdt = $autoCheckUsdt > 0 ? $autoCheckUsdt : 0;
  1220. if ($money <= $autoCheckUsdt) {
  1221. // 打款处理
  1222. $result = WalletService::make()->usdtTrcTransfer($trcUrl, $realUsdt);
  1223. $txID = isset($result['txId']) ? $result['txId'] : '';
  1224. $payAddress = isset($result['address']) ? $result['address'] : '';
  1225. if ($txID && $payAddress) {
  1226. $updateData = ['hash'=> $txID,'wallet_url'=> $payAddress,'audit_remark'=>'自动审核打款','status'=>2,'update_time'=>time()];
  1227. if(BalanceLogModel::where(['order_no'=> $orderNo,'user_type'=> $userType])->update($updateData)){
  1228. $title = $userType == 1 ? 'USDT余额提现审核成功' : '商户余额提现审核成功';
  1229. $message = $userType == 1 ? "您在{$dateTime}(UTC+8)申请提现{$money}USDT余额审核成功,请耐心等候打款到账!!!" : "您在{$dateTime}(UTC+8)申请提现{$money}USDT商户余额审核成功,请耐心等候打款到账!!!";
  1230. MessageService::make()->pushMessage($userId, $title, $message);
  1231. AccountLogModel::where(['source_order_no'=> $orderNo])->update(['hash'=> $txID,'update_time'=>time()]);
  1232. // 平台明细
  1233. $log = [
  1234. 'user_id' => 0,
  1235. 'source_id' => $userId,
  1236. 'source_order_no' => $orderNo,
  1237. 'type' => 5,
  1238. 'coin_type' => 1,
  1239. 'user_type'=> 4,
  1240. 'money' => $fee,
  1241. 'actual_money' => $fee,
  1242. 'balance' => 0,
  1243. 'create_time' => time(),
  1244. 'update_time' => time(),
  1245. 'hash' => $txID,
  1246. 'remark' => "USDT余额提现",
  1247. 'status' => 1,
  1248. 'mark' => 1,
  1249. ];
  1250. AccountLogModel::insertGetId($log);
  1251. // 平台流水
  1252. FinanceService::make()->saveLog(0, $fee, 1);
  1253. }
  1254. }
  1255. }
  1256. $this->error = $title;
  1257. RedisService::clear($cacheKey);
  1258. return [
  1259. 'id'=> $id,
  1260. 'money'=> $money,
  1261. 'user_type'=> $userType,
  1262. ];
  1263. }
  1264. /**
  1265. * 获取点对点上级节点
  1266. * @param $userId 推荐人ID
  1267. * @return int|mixed
  1268. */
  1269. public function getPointParentId($userId)
  1270. {
  1271. if($userId<=0){
  1272. return 0;
  1273. }
  1274. $userList = $this->model->where(['mark'=> 1])->whereRaw('FIND_IN_SET(?,points)', $userId)->select(['id','point_id','points'])->orderBy('create_time','asc')->get();
  1275. $userList = $userList? $userList->toArray() : [];
  1276. if(count($userList) < 3){
  1277. return $userId;
  1278. }
  1279. $users = [];
  1280. foreach($userList as $item){
  1281. $points = isset($item['points']) && $item['points']? explode(',', $item['points']) : [];
  1282. $points = array_filter($points);
  1283. $users[$item['id']]['pointLen'] = count($points);
  1284. $users[$item['id']]['children'] = isset($users[$item['id']]['children'])? $users[$item['id']]['children'] : 0;
  1285. $users[$item['point_id']]['children'] = isset($users[$item['point_id']]['children'])? $users[$item['point_id']]['children'] + 1 : 1;
  1286. }
  1287. //var_dump($users);
  1288. $pointId = 0;
  1289. $tempPointLen = 0;
  1290. $tempChildren = 0;
  1291. foreach ($userList as $item) {
  1292. $id = isset($item['id'])? $item['id'] : 0;
  1293. $children = isset($users[$id]['children'])? $users[$id]['children'] : 0;
  1294. $pointLen = isset($users[$id]['pointLen'])? $users[$id]['pointLen'] : 0;
  1295. //var_dump($id.'++'.$pointLen.'--'.$children.'=='.$pointId.'++'.$tempPointLen.'++'.$tempChildren);
  1296. if($pointLen<=$tempPointLen || $pointId == 0){
  1297. //var_dump($id.'++'.$pointLen.'--'.$children."\n\n");
  1298. if($children <$tempChildren || $pointId == 0){
  1299. $pointId = $id;
  1300. $tempPointLen = $pointLen;
  1301. $tempChildren = $children;
  1302. }
  1303. }
  1304. }
  1305. return $pointId;
  1306. }
  1307. }