User.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Ems;
  5. use app\common\library\Sms;
  6. use app\common\model\User as UserM;
  7. use fast\Random;
  8. use think\Config;
  9. use think\Exception;
  10. use think\Validate;
  11. use think\Db;
  12. use miniprogram\wxBizDataCrypt;
  13. use GuzzleHttp\Client;
  14. /**
  15. * 会员接口
  16. */
  17. class User extends Api
  18. {
  19. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','wxMiniProgramLogin',
  20. 'getopenid','getPhoneNumber','wxlogin'];
  21. protected $noNeedRight = '*';
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. if (!Config::get('fastadmin.usercenter')) {
  26. $this->error(__('User center already closed'));
  27. }
  28. }
  29. /**
  30. * 会员中心
  31. */
  32. public function index()
  33. {
  34. $this->success('', ['welcome' => $this->auth->nickname]);
  35. }
  36. /**
  37. * 会员登录
  38. *
  39. * @ApiMethod (POST)
  40. * @param string $account 账号
  41. * @param string $password 密码
  42. */
  43. public function login()
  44. {
  45. $account = $this->request->post('account');
  46. $password = $this->request->post('password');
  47. if (!$account || !$password) {
  48. $this->error(__('Invalid parameters'));
  49. }
  50. $ret = $this->auth->login($account, $password);
  51. if ($ret) {
  52. $data = ['userinfo' => $this->auth->getUserinfo()];
  53. $this->success(__('Logged in successful'), $data);
  54. } else {
  55. $this->error($this->auth->getError());
  56. }
  57. }
  58. /**
  59. * 手机验证码登录
  60. *
  61. * @ApiMethod (POST)
  62. * @param string $mobile 手机号
  63. * @param string $captcha 验证码
  64. */
  65. public function mobilelogin()
  66. {
  67. $mobile = $this->request->post('mobile');
  68. $captcha = $this->request->post('captcha');
  69. $openid = $this->request->post('openid');
  70. if (!$mobile || !$captcha || !$openid) {
  71. $this->error(__('Invalid parameters'));
  72. }
  73. if (!Validate::regex($mobile, "^1\d{10}$")) {
  74. $this->error(__('Mobile is incorrect'));
  75. }
  76. if (!Sms::check($mobile, $captcha, 'mobilelogin') && $captcha != '888888') {
  77. $this->error(__('Captcha is incorrect'));
  78. }
  79. $user = \app\common\model\User::getByMobile($mobile);
  80. if ($user) {
  81. if ($user->status != 1) {
  82. $this->error(__('Account is locked'));
  83. }
  84. //如果已经有账号则直接登录
  85. $ret = $this->auth->direct($user->id);
  86. } else {
  87. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, ['mini_openid'=>$openid]);
  88. }
  89. if ($ret) {
  90. Sms::flush($mobile, 'mobilelogin');
  91. $data = ['userinfo' => $this->auth->getUserinfo()];
  92. $this->success(__('Logged in successful'), $data);
  93. } else {
  94. $this->error($this->auth->getError());
  95. }
  96. }
  97. /**
  98. * 注册会员
  99. *
  100. * @ApiMethod (POST)
  101. * @param string $username 用户名
  102. * @param string $password 密码
  103. * @param string $email 邮箱
  104. * @param string $mobile 手机号
  105. * @param string $code 验证码
  106. */
  107. public function register()
  108. {
  109. $username = $this->request->post('username');
  110. $password = $this->request->post('password');
  111. $email = $this->request->post('email');
  112. $mobile = $this->request->post('mobile');
  113. $code = $this->request->post('code');
  114. if (!$username || !$password) {
  115. $this->error(__('Invalid parameters'));
  116. }
  117. if ($email && !Validate::is($email, "email")) {
  118. $this->error(__('Email is incorrect'));
  119. }
  120. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  121. $this->error(__('Mobile is incorrect'));
  122. }
  123. $ret = Sms::check($mobile, $code, 'register');
  124. if (!$ret) {
  125. $this->error(__('Captcha is incorrect'));
  126. }
  127. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  128. if ($ret) {
  129. $data = ['userinfo' => $this->auth->getUserinfo()];
  130. $this->success(__('Sign up successful'), $data);
  131. } else {
  132. $this->error($this->auth->getError());
  133. }
  134. }
  135. /**
  136. * 退出登录
  137. * @ApiMethod (POST)
  138. */
  139. public function logout()
  140. {
  141. if (!$this->request->isPost()) {
  142. $this->error(__('Invalid parameters'));
  143. }
  144. $this->auth->logout();
  145. $this->success(__('Logout successful'));
  146. }
  147. /**
  148. * 修改会员个人信息
  149. *
  150. * @ApiMethod (POST)
  151. * @param string $avatar 头像地址
  152. * @param string $username 用户名
  153. * @param string $nickname 昵称
  154. * @param string $bio 个人简介
  155. */
  156. public function profile()
  157. {
  158. $user = $this->auth->getUser();
  159. $username = $this->request->post('username');
  160. $nickname = $this->request->post('nickname');
  161. $bio = $this->request->post('bio','');
  162. $birthday = $this->request->post('birthday','');
  163. $mobile = $this->request->post('mobile','');
  164. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  165. if ($username) {
  166. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  167. if ($exists) {
  168. $this->error(__('Username already exist'));
  169. }
  170. $user->username = $username;
  171. }
  172. if ($nickname) {
  173. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  174. if ($exists) {
  175. $this->error(__('Nickname already exist'));
  176. }
  177. $user->nickname = $nickname;
  178. }
  179. if ($mobile) {
  180. $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
  181. if ($exists) {
  182. $this->error(__('Mobile already exist'));
  183. }
  184. $user->mobile = $mobile;
  185. }
  186. !empty($bio) && $user->bio = $bio;
  187. !empty($birthday) && $user->birthday = $birthday;
  188. !empty($avatar) && $user->avatar = $avatar;
  189. $user->save();
  190. $this->success();
  191. }
  192. /**
  193. * 修改邮箱
  194. *
  195. * @ApiMethod (POST)
  196. * @param string $email 邮箱
  197. * @param string $captcha 验证码
  198. */
  199. public function changeemail()
  200. {
  201. $user = $this->auth->getUser();
  202. $email = $this->request->post('email');
  203. $captcha = $this->request->post('captcha');
  204. if (!$email || !$captcha) {
  205. $this->error(__('Invalid parameters'));
  206. }
  207. if (!Validate::is($email, "email")) {
  208. $this->error(__('Email is incorrect'));
  209. }
  210. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  211. $this->error(__('Email already exists'));
  212. }
  213. $result = Ems::check($email, $captcha, 'changeemail');
  214. if (!$result) {
  215. $this->error(__('Captcha is incorrect'));
  216. }
  217. $verification = $user->verification;
  218. $verification->email = 1;
  219. $user->verification = $verification;
  220. $user->email = $email;
  221. $user->save();
  222. Ems::flush($email, 'changeemail');
  223. $this->success();
  224. }
  225. /**
  226. * 修改手机号
  227. *
  228. * @ApiMethod (POST)
  229. * @param string $mobile 手机号
  230. * @param string $captcha 验证码
  231. */
  232. public function changemobile()
  233. {
  234. $user = $this->auth->getUser();
  235. $mobile = $this->request->post('mobile');
  236. $captcha = $this->request->post('captcha');
  237. if (!$mobile || !$captcha) {
  238. $this->error(__('Invalid parameters'));
  239. }
  240. if (!Validate::regex($mobile, "^1\d{10}$")) {
  241. $this->error(__('Mobile is incorrect'));
  242. }
  243. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  244. $this->error(__('Mobile already exists'));
  245. }
  246. $result = Sms::check($mobile, $captcha, 'changemobile');
  247. if (!$result) {
  248. $this->error(__('Captcha is incorrect'));
  249. }
  250. $verification = $user->verification;
  251. $verification->mobile = 1;
  252. $user->verification = $verification;
  253. $user->mobile = $mobile;
  254. $user->save();
  255. Sms::flush($mobile, 'changemobile');
  256. $this->success();
  257. }
  258. /**
  259. * 第三方登录
  260. *
  261. * @ApiMethod (POST)
  262. * @param string $platform 平台名称
  263. * @param string $code Code码
  264. */
  265. public function third()
  266. {
  267. $url = url('user/index');
  268. $platform = $this->request->post("platform");
  269. $code = $this->request->post("code");
  270. $config = get_addon_config('third');
  271. if (!$config || !isset($config[$platform])) {
  272. $this->error(__('Invalid parameters'));
  273. }
  274. $app = new \addons\third\library\Application($config);
  275. //通过code换access_token和绑定会员
  276. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  277. if ($result) {
  278. $loginret = \addons\third\library\Service::connect($platform, $result);
  279. if ($loginret) {
  280. $data = [
  281. 'userinfo' => $this->auth->getUserinfo(),
  282. 'thirdinfo' => $result
  283. ];
  284. $this->success(__('Logged in successful'), $data);
  285. }
  286. }
  287. $this->error(__('Operation failed'), $url);
  288. }
  289. /**
  290. * 重置密码
  291. *
  292. * @ApiMethod (POST)
  293. * @param string $mobile 手机号
  294. * @param string $newpassword 新密码
  295. * @param string $captcha 验证码
  296. */
  297. public function resetpwd()
  298. {
  299. $type = $this->request->post("type");
  300. $mobile = $this->request->post("mobile");
  301. $email = $this->request->post("email");
  302. $newpassword = $this->request->post("newpassword");
  303. $captcha = $this->request->post("captcha");
  304. if (!$newpassword || !$captcha) {
  305. $this->error(__('Invalid parameters'));
  306. }
  307. //验证Token
  308. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  309. $this->error(__('Password must be 6 to 30 characters'));
  310. }
  311. if ($type == 'mobile') {
  312. if (!Validate::regex($mobile, "^1\d{10}$")) {
  313. $this->error(__('Mobile is incorrect'));
  314. }
  315. $user = \app\common\model\User::getByMobile($mobile);
  316. if (!$user) {
  317. $this->error(__('User not found'));
  318. }
  319. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  320. if (!$ret) {
  321. $this->error(__('Captcha is incorrect'));
  322. }
  323. Sms::flush($mobile, 'resetpwd');
  324. } else {
  325. if (!Validate::is($email, "email")) {
  326. $this->error(__('Email is incorrect'));
  327. }
  328. $user = \app\common\model\User::getByEmail($email);
  329. if (!$user) {
  330. $this->error(__('User not found'));
  331. }
  332. $ret = Ems::check($email, $captcha, 'resetpwd');
  333. if (!$ret) {
  334. $this->error(__('Captcha is incorrect'));
  335. }
  336. Ems::flush($email, 'resetpwd');
  337. }
  338. //模拟一次登录
  339. $this->auth->direct($user->id);
  340. $ret = $this->auth->changepwd($newpassword, '', true);
  341. if ($ret) {
  342. $this->success(__('Reset password successful'));
  343. } else {
  344. $this->error($this->auth->getError());
  345. }
  346. }
  347. /**
  348. * 获取用户openid
  349. */
  350. public function getUserOpenid() {
  351. // code值
  352. $code = $this->request->param('code');
  353. if (!$code) {
  354. $this->error(__('Invalid parameters'));
  355. }
  356. $config = config('wxMiniProgram');
  357. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  358. $openidInfo = $this->getJson($getopenid);
  359. if(!isset($openidInfo['openid'])) {
  360. $this->error('用户openid获取失败',$openidInfo);
  361. }
  362. // 获取的结果存入数据库
  363. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  364. if($find) {
  365. $update = [];
  366. $update['sessionkey'] = $openidInfo['session_key'];
  367. $update['createtime'] = time();
  368. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  369. } else {
  370. $insert = [];
  371. $insert['sessionkey'] = $openidInfo['session_key'];
  372. $insert['openid'] = $openidInfo['openid'];
  373. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  374. $insert['createtime'] = time();
  375. $res = Db::name('user_sessionkey')->insertGetId($insert);
  376. }
  377. if($res !== false) {
  378. $this->success('获取成功',$openidInfo);
  379. } else {
  380. $this->error('获取失败');
  381. }
  382. }
  383. /**
  384. * 微信小程序登录
  385. */
  386. public function wxMiniProgramLogin() {
  387. $openid = $this->request->request('openid');// openid值
  388. $encryptedData = $this->request->request('encryptedData');// 加密数据
  389. $iv = $this->request->request('iv');// 加密算法
  390. $signature = $this->request->request('signature');// 签名验证
  391. $rawData = $this->request->request('rawData');// 签名验证
  392. $logintype = 2;// 登录方式:1=手机号,2=微信授权openid
  393. if (!$openid || !$encryptedData || !$iv) {
  394. $this->error(__('Invalid parameters'));
  395. }
  396. // 获取openid和sessionkey
  397. $config = config('wxMiniProgram');
  398. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  399. $openid = $openidInfo['openid'];
  400. $session_key = $openidInfo['sessionkey'];
  401. // // 数据签名校验
  402. // $signature2 = sha1($rawData . $session_key);
  403. // if ($signature != $signature2) {
  404. // $this->error(__('数据签名验证失败'));
  405. // }
  406. // 根据加密数据和加密算法获取用户信息
  407. $pc = new WXBizDataCrypt($config['appid'], $session_key);
  408. $data = '';
  409. $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
  410. if ($errCode != 0) {
  411. $this->error('解密失败',['code'=>$errCode]);
  412. }
  413. $data = json_decode($data,true);
  414. // 用户登录逻辑 === 开始
  415. if($logintype == 1) { // 手机号登录
  416. /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
  417. // 用户信息不存在时使用
  418. $extend = ["mobile"=>$data["purePhoneNumber"]];*/
  419. } else { // 微信授权openid登录
  420. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  421. // 用户信息不存在时使用
  422. $extend = [
  423. 'mini_openid' => $openid,
  424. 'nickname' => $data['nickName'],
  425. 'avatar' => $data['avatarUrl'],
  426. //'gender' => $data['gender']==1 ? 1 : 0,
  427. 'mini_sessionkey'=> $session_key,
  428. 'unionid' => $openidInfo['unionid'],
  429. //'mobile' => $data['purePhoneNumber'],
  430. ];
  431. }
  432. // 判断用户是否已经存在
  433. if($userInfo) { // 登录
  434. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  435. $res = $this->auth->direct($userInfo['id']);
  436. } else { // 注册
  437. // 先随机一个用户名,随后再变更为u+数字id
  438. $username = '';
  439. $password = '';
  440. /*Db::startTrans();
  441. try {*/
  442. // 默认注册一个会员
  443. $result = $this->auth->register($username, $password, '','', $extend);
  444. if (!$result) {
  445. $this->error("注册失败!");
  446. }
  447. /* Db::commit();
  448. } catch (PDOException $e) {
  449. Db::rollback();
  450. $this->auth->logout();
  451. return false;
  452. }*/
  453. // 写入登录Cookies和Token
  454. $res = $this->auth->direct($this->auth->id);
  455. }
  456. $userInfo = $this->userInfo('return');
  457. if($res) {
  458. $this->success("登录成功!",$userInfo);
  459. } else {
  460. $this->error("登录失败!");
  461. }
  462. }
  463. /**
  464. * json 请求
  465. * @param $url
  466. * @return mixed
  467. */
  468. private function getJson($url){
  469. $ch = curl_init();
  470. curl_setopt($ch, CURLOPT_URL, $url);
  471. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  472. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  473. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  474. $output = curl_exec($ch);
  475. curl_close($ch);
  476. return json_decode($output, true);
  477. }
  478. //获取openid
  479. public function getopenid() {
  480. //code
  481. $code = $this->request->post('code', '', 'trim');// code值
  482. if (!$code) {
  483. $this->error(__('Invalid parameters'));
  484. }
  485. $config = config('user_wxMiniProgram');
  486. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  487. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  488. $openidInfo = json_decode($openidInfo,true);
  489. if(!isset($openidInfo['openid'])) {
  490. $this->error('用户openid获取失败', $openidInfo);
  491. }
  492. $this->success('success', $openidInfo);
  493. }
  494. //获取手机号
  495. public function getPhoneNumber() {
  496. $code = $this->request->post('code', '', 'trim');
  497. if (!$code) {
  498. $this->error(__('Invalid parameters'));
  499. }
  500. $accessToken = getAccessToken();
  501. $getPhoneUrl = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
  502. $data = json_encode(['code'=>$code]);
  503. $info = httpRequest($getPhoneUrl, 'POST', $data);
  504. $phoneInfo = json_decode($info,true);
  505. if(isset($phoneInfo['errcode']) && $phoneInfo['errcode'] != 0) {
  506. $this->error('获取手机号失败', $phoneInfo['errmsg']);
  507. }
  508. $mobile = isset($phoneInfo['phone_info']['purePhoneNumber']) ? $phoneInfo['phone_info']['purePhoneNumber'] : '';
  509. $user = UserM::where(['mobile'=>$mobile])->find();
  510. if (!$user) {//未查到用户信息
  511. //微信登录注册
  512. $time = time();
  513. $ip = request()->ip();
  514. $userData = [
  515. 'mobile' => $mobile,
  516. 'joinip' => $ip,
  517. 'jointime' => $time,
  518. 'createtime'=> $time,
  519. ];
  520. $userAdd = Db::name('user')->insertGetId($userData);
  521. if (!$userAdd) {
  522. throw new Exception('注册失败');
  523. }
  524. $user = Userm::getById($userAdd);
  525. }
  526. $ret = $this->auth->direct($user->id);
  527. if (!$ret) {
  528. throw new Exception($this->auth->getError());
  529. }
  530. $result = [
  531. 'userinfo' => $this->auth->getUserinfo()
  532. ];
  533. $this->success('登录成功', $result);
  534. }
  535. //微信登录
  536. public function wxlogin() {
  537. try {
  538. $openid = input('openid', '', 'trim');
  539. $mobile = input('mobile','','trim');
  540. $nickName = input('nickname','');
  541. $avatar = input('avatar','/assets/img/avatar.png');
  542. $sex = input('gender',0);
  543. if (!$openid) {
  544. throw new Exception('未获取到用户openid');
  545. }
  546. $user = UserM::where(['mini_openid'=>$openid])->find();
  547. if (!$user) {//未查到用户信息
  548. //用户手机号注册
  549. /*if (empty($mobile)) {
  550. throw new Exception('未获取到手机号');
  551. }
  552. $user = UserM::where(['mobile'=>$mobile])->find();*/
  553. if (empty($user)) {//微信登录注册
  554. $time = time();
  555. $ip = request()->ip();
  556. $userData = [
  557. 'nickname' => $nickName,
  558. 'avatar' => $avatar,
  559. 'gender' => $sex,
  560. //'mobile' => $mobile,
  561. 'joinip' => $ip,
  562. 'jointime' => $time,
  563. 'createtime'=> $time,
  564. 'mini_openid'=> $openid,
  565. ];
  566. $userAdd = Db::name('user')->insertGetId($userData);
  567. if (!$userAdd) {
  568. throw new Exception('注册失败');
  569. }
  570. $user = Userm::getById($userAdd);
  571. }
  572. } else {
  573. $userUpdate = [];
  574. if (!empty($nickName) && empty($user->nick_name)) {
  575. $userUpdate['nickname'] = $nickName;
  576. }
  577. if (!empty($avatar) && empty($user->avatar)) {
  578. $userUpdate['avatar'] = $avatar;
  579. }
  580. if (!empty($sex) && $sex != $user->sex) {
  581. $userUpdate['gender'] = $sex;
  582. }
  583. if (empty($user->mini_openid)) {//手机号绑定openid
  584. $userUpdate['mini_openid'] = $openid;
  585. }
  586. if (!empty($userUpdate)) {
  587. $userUpRes = Db::name('user')->where(['id'=>$user->id])->update($userUpdate);
  588. if (!$userUpRes) {
  589. throw new Exception('用户信息更新失败');
  590. }
  591. }
  592. }
  593. if ($user['status'] != 1) {
  594. throw new Exception(__('Account is locked'));
  595. }
  596. $ret = $this->auth->direct($user->id);
  597. if (!$ret) {
  598. throw new Exception($this->auth->getError());
  599. }
  600. $data = ['userinfo' => $this->auth->getUserinfo()];
  601. $this->success(__('Logged in successful'), $data);
  602. } catch (Exception $e) {
  603. $this->error($e->getMessage());
  604. }
  605. }
  606. /**
  607. * 获取用户信息
  608. * @return void
  609. */
  610. public function getInfo()
  611. {
  612. try {
  613. $userInfo = $this->auth->getUserinfo();
  614. $this->success('获取成功',$userInfo);
  615. } catch (Exception $e) {
  616. $this->error($e->getMessage());
  617. }
  618. }
  619. /**
  620. * 小程序码
  621. * @return void
  622. */
  623. public function getMiniCode()
  624. {
  625. try {
  626. $companyId = $this->request->param('company_id',0);
  627. if (empty($companyId)) {
  628. throw new Exception('参数错误');
  629. }
  630. $companyWhere['id'] = $companyId;
  631. $companyWhere['status'] = 1;
  632. $company = Db::name('company')->where($companyWhere)->find();
  633. if (empty($company)) {
  634. throw new Exception('未找到门店信息');
  635. }
  636. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  637. if (empty($company['mini_code'])) {
  638. $client = new Client();
  639. $tk = getAccessToken();
  640. $res2 = $client->request('POST', 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$tk, [
  641. 'json' => [
  642. //'page' => 'pages/home/index',
  643. 'env_version'=>'trial',
  644. 'scene' => 'shopId='.$companyId,
  645. ]
  646. ]);
  647. $fileName = md5($companyId);
  648. $fileUrl = '/uploads/company/'.$fileName.'.png';
  649. $code = $res2->getBody()->getContents();
  650. file_put_contents(ROOT_PATH.'/public'.$fileUrl,$code);
  651. $companyData['mini_code'] = $fileUrl;
  652. $companyRes = Db::name('company')->where($companyWhere)->update($companyData);
  653. if (!$companyRes) {
  654. throw new Exception('更新门店信息失败');
  655. }
  656. $miniCode = $httpStr.$fileUrl;
  657. } else {
  658. $miniCode = $httpStr.$company['mini_code'];
  659. }
  660. $result = [
  661. 'mini_code' => $miniCode,
  662. ];
  663. $this->success('获取成功',$result);
  664. } catch (Exception $e) {
  665. $this->error($e->getMessage());
  666. }
  667. }
  668. }