MemberService.php 55 KB

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