MemberService.php 55 KB

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