MemberService.php 57 KB

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