MemberService.php 55 KB

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