MemberService.php 54 KB

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