MemberService.php 56 KB

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