User.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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\library\Wechat;
  7. use app\common\service\UserService;
  8. use fast\Random;
  9. use think\Exception;
  10. use think\Log;
  11. use think\Validate;
  12. use miniprogram\wxBizDataCrypt;
  13. use onlogin\onlogin;
  14. use think\Db;
  15. /**
  16. * 会员接口
  17. */
  18. class User extends Api
  19. {
  20. protected $noNeedLogin = ['login', 'onLogin', 'mobilelogin', 'register', 'resetpwd', 'changemobile', 'third', 'getUserOpenid', 'wxMiniProgramLogin','getNickName','wechatlogin','bindmobile'];
  21. protected $noNeedRight = '*';
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. }
  26. /**
  27. * 会员中心
  28. */
  29. public function index()
  30. {
  31. $this->success('', ['welcome' => $this->auth->nickname]);
  32. }
  33. /**
  34. * 会员登录
  35. *
  36. * @param string $account 账号
  37. * @param string $password 密码
  38. */
  39. public function login()
  40. {
  41. $account = $this->request->request('account');
  42. $password = $this->request->request('password');
  43. if (!$account || !$password) {
  44. $this->error(__('Invalid parameters'));
  45. }
  46. $ret = $this->auth->login($account, $password);
  47. if ($ret) {
  48. $data = ['userinfo' => $this->auth->getUserinfo()];
  49. $this->success(__('Logged in successful'), $data);
  50. } else {
  51. $this->error($this->auth->getError());
  52. }
  53. }
  54. /**
  55. * 手机验证码登录
  56. *
  57. * @param string $mobile 手机号
  58. * @param string $captcha 验证码
  59. */
  60. public function mobilelogin()
  61. {
  62. $mobile = input('mobile');
  63. $captcha = input('captcha');
  64. if (!$mobile || !$captcha) {
  65. $this->error(__('Invalid parameters'));
  66. }
  67. if (!Validate::regex($mobile, "^1\d{10}$")) {
  68. $this->error(__('Mobile is incorrect'));
  69. }
  70. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  71. $this->error(__('Captcha is incorrect'));
  72. }
  73. $user = \app\common\model\User::getByMobile($mobile);
  74. if ($user) {
  75. if ($user->status == -1) {
  76. $this->error('账户已注销');
  77. }
  78. if ($user->status != 1) {
  79. $this->error(__('Account is locked'));
  80. }
  81. //如果已经有账号则直接登录
  82. $is_register = 0;
  83. $ret = $this->auth->direct($user->id);
  84. } else {
  85. $is_register = 1;
  86. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, []);
  87. }
  88. if ($ret) {
  89. Sms::flush($mobile, 'mobilelogin');
  90. // $data = ['is_register' => $is_register, 'userinfo' => $this->auth->getUserinfo()];
  91. $this->success(__('Logged in successful'), $this->auth->getUserinfo());
  92. } else {
  93. $this->error($this->auth->getError());
  94. }
  95. }
  96. //苹果登录+注册
  97. public function applelogin(){
  98. $iosUserId = input('ios_user_id','');
  99. if(!$iosUserId){
  100. $this->error(__('Invalid parameters'));
  101. }
  102. $user = Db::name('user')->where('ios_user_id',$iosUserId)->find();
  103. if ($user) {
  104. if ($user['status'] == -1) {
  105. $this->error('账户已经注销');
  106. }
  107. if ($user['status'] != 1) {
  108. $this->error(__('Account is locked'));
  109. }
  110. //如果已经有账号则直接登录
  111. $ret = $this->auth->direct($user['id']);
  112. } else {
  113. $ret = $this->auth->ios_register($iosUserId);
  114. }
  115. if ($ret) {
  116. $this->success(__('Logged in successful'), $this->auth->getUserinfo());
  117. } else {
  118. $this->error($this->auth->getError());
  119. }
  120. }
  121. /*
  122. * 修改用户的坐标
  123. * */
  124. public function change_longlat(){
  125. $longitude = input('longitude',0);
  126. $latitude = input('latitude',0);
  127. if(empty($longitude) || empty($latitude)){
  128. $this->error();
  129. }
  130. $data = [
  131. 'longitude' => $longitude,
  132. 'latitude' => $latitude,
  133. ];
  134. Db::name('user')->where('id',$this->auth->id)->update($data);
  135. $this->success();
  136. }
  137. /**
  138. * 绑定用户
  139. */
  140. public function bindUser()
  141. {
  142. $invite_no = input('invite_no'); // 邀请码
  143. if (!$invite_no) {
  144. $this->error("请输入邀请码!");
  145. }
  146. $user_id = $this->auth->id;
  147. // 查询邀请码用户信息
  148. $inviteUserInfo = \app\common\model\User::where(["invite_no" => $invite_no])->find();
  149. if (!$inviteUserInfo) {
  150. $this->error("查询不到该邀请码用户信息!");
  151. }
  152. //判断邀请码用户不能是自己的下级
  153. if ($inviteUserInfo['pre_userid'] == $user_id) {
  154. throw new Exception('对方已被您邀请过');
  155. }
  156. if ($inviteUserInfo->id == $user_id) $this->error("不能邀请自己哦!");
  157. if ($inviteUserInfo->is_auth != 2) $this->error("该邀请码用户尚未完成实名认证");
  158. $res = \app\common\model\User::update(["pre_userid" => $inviteUserInfo->id], ["id" => $user_id]);
  159. if ($res) {
  160. $this->success("恭喜,绑定成功!");
  161. } else {
  162. $this->success("网络繁忙,请稍后重试!");
  163. }
  164. }
  165. /**
  166. * 注册会员
  167. *
  168. * @param string $username 用户名
  169. * @param string $password 密码
  170. * @param string $email 邮箱
  171. * @param string $mobile 手机号
  172. * @param string $code 验证码
  173. */
  174. public function register()
  175. {
  176. $username = input('username');
  177. $password = input('password');
  178. $mobile = input('mobile');
  179. $code = input('code');
  180. if (!$username || !$password) {
  181. $this->error(__('Invalid parameters'));
  182. }
  183. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  184. $this->error(__('Mobile is incorrect'));
  185. }
  186. // $ret = Sms::check($mobile, $code, 'register');
  187. // if (!$ret) {
  188. // $this->error(__('Captcha is incorrect'));
  189. // }
  190. $ret = $this->auth->register($username, $password, $mobile, []);
  191. if ($ret) {
  192. $data = ['userinfo' => $this->auth->getUserinfo()];
  193. $this->success(__('Sign up successful'), $data);
  194. } else {
  195. $this->error($this->auth->getError());
  196. }
  197. }
  198. /**
  199. * 退出登录
  200. */
  201. public function logout()
  202. {
  203. $this->auth->logout();
  204. $this->success(__('Logout successful'));
  205. }
  206. /**
  207. * 修改会员个人信息
  208. *
  209. * @ApiMethod (POST)
  210. * @param string $avatar 头像地址
  211. * @param string $username 用户名
  212. * @param string $nickname 昵称
  213. * @param string $bio 个人简介
  214. */
  215. public function profile()
  216. {
  217. $field_array = ['avatar','nickname','desc','age_id','gender','job_id','province_id','city_id','has_info'];
  218. $data = [];
  219. foreach($field_array as $key => $field){
  220. //前端传不了post,改了
  221. if(!request()->has($field,'post')){
  222. continue;
  223. }
  224. /*if(!input('?'.$field)){
  225. continue;
  226. }*/
  227. $newone = input($field);
  228. if($field == 'avatar'){
  229. $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
  230. }
  231. $data[$field] = $newone;
  232. }
  233. if(isset($data['invite_no']) && !empty($data['invite_no'])){
  234. $intro_user = Db::name('user')->where('invite_no',$data['invite_no'])->value('id');
  235. if(!$intro_user){
  236. $this->error('不存在的邀请人');
  237. }
  238. if(!empty($this->auth->pre_userid)){
  239. $this->error('您已经填写过邀请人');
  240. }
  241. unset($data['invite_no']);//别人的邀请码,不能改了自己的
  242. $data['pre_userid'] = $intro_user;
  243. //邀请用户注册,给邀请人奖励
  244. if(isset($data['pre_userid']) && !empty($data['pre_userid'])){
  245. /*$intro_gold = config('site.intro_newuser_gift_goldnum') ?: 0;
  246. if($intro_gold > 0){
  247. $wallet_rs = model('wallet')->lockChangeAccountRemain($data['intro_uid'],'gold',$intro_gold,63,'邀请'.$this->auth->username);
  248. if($wallet_rs['status'] === false){
  249. Db::rollback();
  250. $this->setError($wallet_rs['msg']);
  251. return false;
  252. }
  253. }*/
  254. }
  255. }
  256. if(empty($data)){
  257. $this->error('没有任何改变');
  258. }
  259. /*if (!empty($data['nickname']) && !empty($data['avatar']) && !empty($data['age_id']) && $data['has_info']==0) {
  260. $data['has_info'] = 1;
  261. }*/
  262. Db::startTrans();
  263. $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
  264. if($update_rs === false){
  265. Db::rollback();
  266. $this->error('修改资料失败');
  267. }
  268. Db::commit();
  269. $this->success();
  270. }
  271. /**
  272. * 修改手机号
  273. *
  274. * @param string $mobile 手机号
  275. * @param string $captcha 验证码
  276. */
  277. public function changemobile()
  278. {
  279. $user = $this->auth->getUser();
  280. $mobile = input('mobile');
  281. $captcha = input('captcha');
  282. if (!$mobile || !$captcha) {
  283. $this->error(__('Invalid parameters'));
  284. }
  285. if (!Validate::regex($mobile, "^1\d{10}$")) {
  286. $this->error(__('Mobile is incorrect'));
  287. }
  288. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  289. $this->error(__('Mobile already exists'));
  290. }
  291. $result = Sms::check($mobile, $captcha, 'changeMobile');
  292. if (!$result) {
  293. $this->error(__('Captcha is incorrect'));
  294. }
  295. $verification = $user->verification;
  296. $verification->mobile = 1;
  297. $user->verification = $verification;
  298. $user->mobile = $mobile;
  299. $user->save();
  300. Sms::flush($mobile, 'changeMobile');
  301. $this->success("手机号更换成功!");
  302. }
  303. /**
  304. * 第三方登录
  305. *
  306. * @param string $platform 平台名称
  307. * @param string $code Code码
  308. */
  309. public function third()
  310. {
  311. $url = url('user/index');
  312. $platform = input("platform");
  313. $code = input("code");
  314. $config = get_addon_config('third');
  315. if (!$config || !isset($config[$platform])) {
  316. $this->error(__('Invalid parameters'));
  317. }
  318. $app = new \addons\third\library\Application($config);
  319. //通过code换access_token和绑定会员
  320. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  321. if ($result) {
  322. $loginret = \addons\third\library\Service::connect($platform, $result);
  323. if ($loginret) {
  324. $data = [
  325. 'userinfo' => $this->auth->getUserinfo(),
  326. 'thirdinfo' => $result
  327. ];
  328. $this->success(__('Logged in successful'), $data);
  329. }
  330. }
  331. $this->error(__('Operation failed'), $url);
  332. }
  333. /**
  334. * 重置密码
  335. *
  336. * @param string $mobile 手机号
  337. * @param string $newpassword 新密码
  338. * @param string $captcha 验证码
  339. */
  340. public function resetpwd()
  341. {
  342. $type = input("type");
  343. $mobile = input("mobile");
  344. $email = input("email");
  345. $newpassword = input("newpassword");
  346. $captcha = input("captcha");
  347. if (!$newpassword || !$captcha) {
  348. $this->error(__('Invalid parameters'));
  349. }
  350. if ($type == 'mobile') {
  351. if (!Validate::regex($mobile, "^1\d{10}$")) {
  352. $this->error(__('Mobile is incorrect'));
  353. }
  354. $user = \app\common\model\User::getByMobile($mobile);
  355. if (!$user) {
  356. $this->error(__('User not found'));
  357. }
  358. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  359. if (!$ret) {
  360. $this->error(__('Captcha is incorrect'));
  361. }
  362. Sms::flush($mobile, 'resetpwd');
  363. } else {
  364. if (!Validate::is($email, "email")) {
  365. $this->error(__('Email is incorrect'));
  366. }
  367. $user = \app\common\model\User::getByEmail($email);
  368. if (!$user) {
  369. $this->error(__('User not found'));
  370. }
  371. $ret = Ems::check($email, $captcha, 'resetpwd');
  372. if (!$ret) {
  373. $this->error(__('Captcha is incorrect'));
  374. }
  375. Ems::flush($email, 'resetpwd');
  376. }
  377. //模拟一次登录
  378. $this->auth->direct($user->id);
  379. $ret = $this->auth->changepwd($newpassword, '', true);
  380. if ($ret) {
  381. $this->success(__('Reset password successful'));
  382. } else {
  383. $this->error($this->auth->getError());
  384. }
  385. }
  386. /**
  387. * 设置密码
  388. * @param string $newpassword 新密码
  389. * @param string $newpassword 新密码
  390. */
  391. public function setpwd()
  392. {
  393. $params = $this->request->param();
  394. $validate = new \app\api\validate\User();
  395. $result = $validate->scene('setPwd')->check($params);
  396. if (!$result) {
  397. $this->error($validate->getError());
  398. }
  399. $ret = $this->auth->changepwd($params['password'], '', true);
  400. if ($ret) {
  401. $this->success(__('Set password successful'));
  402. } else {
  403. $this->error($this->auth->getError());
  404. }
  405. }
  406. /**
  407. * 修改密码
  408. *
  409. * @param string $mobile 手机号
  410. * @param string $newpassword 新密码
  411. * @param string $captcha 验证码
  412. */
  413. public function changepwd()
  414. {
  415. $params = $this->request->param();
  416. $validate = new \app\api\validate\User();
  417. $result = $validate->scene('changePwd')->check($params);
  418. if (!$result) {
  419. $this->error($validate->getError());
  420. }
  421. $mobile = input("mobile");
  422. $newpassword = input("password");
  423. $captcha = input("captcha");
  424. $user = \app\common\model\User::getByMobile($mobile);
  425. if (!$user) {
  426. $this->error(__('User not found'));
  427. }
  428. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  429. if (!$ret) {
  430. $this->error(__('Captcha is incorrect'));
  431. }
  432. Sms::flush($mobile, 'resetpwd');
  433. $ret = $this->auth->changepwd($newpassword, '', true);
  434. if ($ret) {
  435. $this->success(__('Change password successful'));
  436. } else {
  437. $this->error($this->auth->getError());
  438. }
  439. }
  440. /**
  441. * 获取用户openid
  442. */
  443. public function getUserOpenid()
  444. {
  445. $code = $this->request->param('code');// code值
  446. if (!$code) {
  447. $this->error(__('Invalid parameters'));
  448. }
  449. $config = config("wxMiniProgram");
  450. $getopenid = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $config["appid"] . "&secret=" . $config["secret"] . "&js_code=" . $code . "&grant_type=authorization_code";
  451. $openidInfo = $this->getJson($getopenid);
  452. if (!isset($openidInfo["openid"])) {
  453. $this->error("用户openid获取失败", $openidInfo);
  454. }
  455. // 获取的结果存入数据库
  456. $sessionkeyModel = new \app\common\model\UserSessionkey();
  457. if ($sessionkeyModel->where(["openid" => $openidInfo["openid"]])->find()) {
  458. $update = [];
  459. $update["sessionkey"] = $openidInfo["session_key"];
  460. $res = $sessionkeyModel->update($update, ["openid" => $openidInfo["openid"]]);
  461. } else {
  462. $insert = [];
  463. $insert["sessionkey"] = $openidInfo["session_key"];
  464. $insert["openid"] = $openidInfo["openid"];
  465. $insert["createtime"] = time();
  466. $res = $sessionkeyModel->insert($insert);
  467. }
  468. if ($res) {
  469. $this->success("获取成功!", $openidInfo);
  470. } else {
  471. $this->error("获取失败!");
  472. }
  473. }
  474. /**
  475. * 微信小程序登录
  476. */
  477. public function wxMiniProgramLogin()
  478. {
  479. $openid = $this->request->param('openid');// openid值
  480. $encryptedData = $this->request->param('encryptedData');// 加密数据
  481. $iv = $this->request->param('iv');// 加密算法
  482. $signature = $this->request->param('signature');// 签名验证
  483. $rawData = $this->request->param('rawData');// 签名验证
  484. $logintype = $this->request->param('loginType', 1);// 登录方式:1=手机号,2=微信授权openid
  485. if (!$openid || !$encryptedData || !$iv) {
  486. $this->error(__('Invalid parameters'));
  487. }
  488. $encryptedData = urldecode($encryptedData);
  489. $config = config("wxMiniProgram");
  490. // 获取openid和sessionkey
  491. $sessionkeyModel = new \app\common\model\UserSessionkey();
  492. $openidInfo = $sessionkeyModel->where(["openid" => $openid])->find();
  493. $openid = $openidInfo['openid'];
  494. $session_key = $openidInfo['sessionkey'];
  495. // // 数据签名校验
  496. // $signature2 = sha1($rawData . $session_key);
  497. // if ($signature != $signature2) {
  498. // $this->error(__('数据签名验证失败'));
  499. // }
  500. // 根据加密数据和加密算法获取用户信息
  501. $pc = new WXBizDataCrypt($config["appid"], $session_key);
  502. $data = "";
  503. $errCode = $pc->decryptData($encryptedData, $iv, $data);
  504. if ($errCode == 0) {
  505. $data = json_decode($data, true);
  506. // 用户登录逻辑 === 开始
  507. $userModel = new \app\common\model\User();
  508. $auth = \app\common\library\Auth::instance();
  509. if ($logintype == 1) { // 手机号登录
  510. $userInfo = $userModel->where(["mobile" => $data["purePhoneNumber"]])->find();
  511. // 用户信息不存在时使用
  512. $extend = ["mobile" => $data["purePhoneNumber"]];
  513. } else { // 微信授权openid登录
  514. $userInfo = $userModel->where(["openid" => $openid])->find();
  515. // 用户信息不存在时使用
  516. $extend = [
  517. 'openid' => $data['openId'],
  518. 'nickname' => $data['nickName'],
  519. 'avatar' => $data['avatarUrl'],
  520. 'gender' => $data['gender'],
  521. ];
  522. }
  523. // 判断用户是否已经存在
  524. if ($userInfo) { // 登录
  525. $user = \app\common\model\User::get($userInfo["id"]);
  526. if (!$user) {
  527. $this->error("网络错误!请稍后重试");
  528. }
  529. $user->save(["logintime" => time()]);
  530. $res = $auth->direct($user->id);
  531. $is_register = 0;
  532. } else { // 注册
  533. // 先随机一个用户名,随后再变更为u+数字id
  534. $username = Random::alnum(20);
  535. $password = Random::alnum(6);
  536. Db::startTrans();
  537. try {
  538. // 默认注册一个会员
  539. $result = $auth->register($username, $password, "", $extend);
  540. if (!$result) {
  541. return false;
  542. }
  543. $user = $auth->getUser();
  544. $fields = ['username' => 'u' . $user->id];
  545. // 更新会员资料
  546. $user = \app\common\model\User::get($user->id);
  547. $user->save($fields);
  548. Db::commit();
  549. } catch (PDOException $e) {
  550. Db::rollback();
  551. $auth->logout();
  552. return false;
  553. }
  554. // 写入登录Cookies和Token
  555. $res = $auth->direct($user->id);
  556. $is_register = 1;
  557. }
  558. $userInfo = $auth->getUserinfo();
  559. $userInfo["is_register"] = $is_register;
  560. if ($res) {
  561. $this->success("登录成功!", $userInfo);
  562. } else {
  563. $this->error("登录失败!");
  564. }
  565. // 用户登录逻辑 === 结束
  566. } else {
  567. $this->error("解密失败!", ["code" => $errCode]);
  568. }
  569. }
  570. /**
  571. * json 请求
  572. * @param $url
  573. * @return mixed
  574. */
  575. private function getJson($url)
  576. {
  577. $ch = curl_init();
  578. curl_setopt($ch, CURLOPT_URL, $url);
  579. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  580. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  581. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  582. $output = curl_exec($ch);
  583. curl_close($ch);
  584. return json_decode($output, true);
  585. }
  586. /**
  587. * 运营商一键登录
  588. */
  589. public function onLogin()
  590. {
  591. $accessToken = $this->request->param('accessToken');// 运营商预取号获取到的token
  592. $token = $this->request->param('tokenT');// 易盾返回的token
  593. if (!$accessToken || !$token) {
  594. $this->error("参数获取失败!");
  595. }
  596. $params = array(
  597. // 运营商预取号获取到的token
  598. "accessToken" => $accessToken,
  599. // 易盾返回的token
  600. "token" => $token
  601. );
  602. // 获取密钥配置
  603. $configInfo = config("onLogin");
  604. $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);
  605. $ret = $onlogin->check($params);
  606. // $ret = [];
  607. // $ret["code"] = 200;
  608. // $ret["msg"] = "ok";
  609. // $ret["data"] = [
  610. // "phone" => "17574504021",
  611. // "resultCode" => 0
  612. // ];
  613. if ($ret["code"] == 200) {
  614. $data = $ret["data"];
  615. $phone = $data["phone"];
  616. if (empty($phone)) {
  617. // 取号失败,建议进行二次验证,例如短信验证码
  618. $this->error("取号登录失败,请用验证码方式登录!");
  619. } else {
  620. // 取号成功, 执行登录等流程
  621. // 用户登录逻辑 === 开始
  622. $userModel = new \app\common\model\User();
  623. $auth = \app\common\library\Auth::instance();
  624. $userInfo = $userModel->where(["mobile" => $phone])->find();
  625. // 用户信息不存在时使用
  626. $extend = ["mobile" => $phone];
  627. // 判断用户是否已经存在
  628. if ($userInfo) { // 登录
  629. $user = \app\common\model\User::get($userInfo["id"]);
  630. if (!$user) {
  631. $this->error("网络错误!请稍后重试");
  632. }
  633. if ($user->status != 'normal') {
  634. $this->error(__('Account is locked'));
  635. }
  636. $user->save(["logintime" => time()]);
  637. $res = $auth->direct($user->id);
  638. $is_register = 0;
  639. } else { // 注册
  640. // 先随机一个用户名,随后再变更为u+数字id
  641. $username = Random::alnum(20);
  642. $password = Random::alnum(6);
  643. Db::startTrans();
  644. try {
  645. // 默认注册一个会员
  646. $result = $auth->register($username, $password, "", $extend);
  647. if (!$result) {
  648. return false;
  649. }
  650. $user = $auth->getUser();
  651. $fields = ['username' => 'u' . $user->id];
  652. // 更新会员资料
  653. $user = \app\common\model\User::get($user->id);
  654. $user->save($fields);
  655. Db::commit();
  656. } catch (PDOException $e) {
  657. Db::rollback();
  658. $auth->logout();
  659. return false;
  660. }
  661. // 写入登录Cookies和Token
  662. $res = $auth->direct($user->id);
  663. $is_register = 1;
  664. }
  665. $userInfo["userinfo"] = $auth->getUserinfo();
  666. $userInfo["is_register"] = $is_register;
  667. if ($res) {
  668. $this->success("登录成功!", $userInfo);
  669. } else {
  670. $this->error("登录失败!");
  671. }
  672. // 用户登录逻辑 === 结束
  673. }
  674. } else {
  675. $this->error("登录失败,请用验证码方式登录!");
  676. }
  677. }
  678. /**
  679. * 注销账号
  680. *
  681. * @param string $mobile 手机号
  682. * @param string $captcha 验证码
  683. */
  684. public function cancleUser()
  685. {
  686. $user = $this->auth->getUser();
  687. $user->status = -1;
  688. //unset($user->power);
  689. $user->save();
  690. $this->auth->logout();
  691. $this->success("账号注销成功!");
  692. }
  693. /**
  694. * 获取昵称
  695. * @return string
  696. */
  697. public function getNickName()
  698. {
  699. $result['nickname'] = get_rand_nick_name();
  700. $this->success('获取成功',$result);
  701. }
  702. //微信登录,预先假注册
  703. public function wechatlogin(){
  704. $code = $this->request->param('code','');
  705. if(!$code){
  706. $this->error(__('Invalid parameters'));
  707. }
  708. //微信
  709. $wechat = new Wechat();
  710. $wxuserinfo = $wechat->getwxuserinfo($code);
  711. Log::error('code:'.$code.',wxuserinfo:'.json_encode($wxuserinfo));
  712. if(!$wxuserinfo){
  713. $this->error('openid获取失败');
  714. }
  715. $openid = $wxuserinfo['openid'];
  716. $user = Db::name('user')->where('openid',$openid)->find();
  717. if ($user) {
  718. if ($user['status'] == -1) {
  719. $this->error('账户已注销');
  720. }
  721. if ($user['status'] != 1) {
  722. $this->error(__('Account is locked'));
  723. }
  724. //如果已经有账号则直接登录
  725. $ret = $this->auth->direct($user['id']);
  726. $is_register = 0;
  727. $userInfo = $this->auth->getUserinfo();
  728. } else {
  729. //记录code和openid,绑定手机号的时候更新openid
  730. $wechatCodeData = [
  731. 'code' => $code,
  732. 'openid' => $openid,
  733. 'createtime' => time(),
  734. ];
  735. $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
  736. if (empty($wechatCode)) {
  737. Db::name('wechat_code')->insertGetId($wechatCodeData);
  738. } else {
  739. Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
  740. }
  741. $ret = true;
  742. $is_register = 1;
  743. $userInfo = [];
  744. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  745. $this->success('获取信息成功', $data, 2);
  746. }
  747. if ($ret) {
  748. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  749. $this->success(__('Logged in successful'), $data);
  750. } else {
  751. $this->error($this->auth->getError());
  752. }
  753. }
  754. //获取openid
  755. public function getopenid() {
  756. //code
  757. $code = $this->request->post('code', '', 'trim');// code值
  758. if (!$code) {
  759. $this->error(__('Invalid parameters'));
  760. }
  761. $config = config('wxMiniProgram');
  762. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  763. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  764. $openidInfo = json_decode($openidInfo,true);
  765. if(!isset($openidInfo['openid'])) {
  766. $this->error('用户openid获取失败', $openidInfo);
  767. }
  768. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  769. //$openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  770. $this->success('获取成功', $openidInfo);
  771. }
  772. /**
  773. * 微信注册来的,绑定手机号
  774. *
  775. * @ApiMethod (POST)
  776. * @param string $mobile 手机号
  777. * @param string $captcha 验证码
  778. */
  779. public function bindmobile()
  780. {
  781. Db::startTrans();
  782. try {
  783. $code = $this->request->param('code');
  784. $mobile = $this->request->param('mobile');
  785. $captcha = $this->request->param('captcha');
  786. if (!$mobile || !$captcha || !$code) {
  787. throw new Exception(__('Invalid parameters'));
  788. }
  789. if (!Validate::regex($mobile, "^1\d{10}$")) {
  790. throw new Exception(__('Mobile is incorrect'));
  791. }
  792. $result = Sms::check($mobile, $captcha, 'changemobile');
  793. if (!$result) {
  794. throw new Exception(__('Captcha is incorrect'));
  795. }
  796. $where['mobile'] = $mobile;
  797. $userData = model('User')->where($where)->find();//老用户
  798. $wechatCodeWhere['code'] = $code;
  799. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  800. if (empty($wechatCode)) {
  801. throw new Exception('请先微信登录');
  802. }
  803. if (!empty($userData)) {
  804. if (empty($userData['openid'])) {
  805. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  806. } else {
  807. if ($userData['openid'] != $wechatCode['openid']) {
  808. throw new Exception('该手机号已被其他用户绑定');
  809. }
  810. }
  811. $ret = $this->auth->direct($userData['id']);
  812. } else {
  813. $extend = [
  814. 'openid' => $wechatCode['openid'],
  815. ];
  816. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  817. }
  818. if (!$ret) {
  819. throw new Exception($this->auth->getError());
  820. }
  821. Sms::flush($mobile, 'changemobile');
  822. Db::commit();
  823. $this->success('success',$this->userInfo('return'));
  824. } catch (Exception $e) {
  825. Db::rollback();
  826. $this->error($e->getMessage());
  827. }
  828. }
  829. /**
  830. * 手机注册来的,绑定微信
  831. *
  832. * @ApiMethod (POST)
  833. * @param string $wechat_openid
  834. */
  835. public function bindopenid()
  836. {
  837. Db::startTrans();
  838. try {
  839. $code = $this->request->param('code','');
  840. if(!$code){
  841. throw new Exception(__('Invalid parameters'));
  842. }
  843. //微信
  844. $wechat = new Wechat();
  845. $openid = $wechat->getOpenid($code);
  846. if(!$openid){
  847. throw new Exception('openid获取失败');
  848. }
  849. $user = model('User')->find($this->auth->id);
  850. if(!empty($user['openid']) && $openid != $user['openid']){
  851. throw new Exception('已经绑定了微信号');
  852. }
  853. $otherUserWhere['openid'] = $openid;
  854. $otherUserWhere['id'] = ['neq',$this->auth->id];
  855. $otherUser = model('User')->where($otherUserWhere)->find();
  856. if (!empty($otherUser)) {
  857. throw new Exception('该微信已被其他用户绑定过');
  858. }
  859. $user->openid = $openid;
  860. $userRes = $user->save();
  861. if (!$userRes) {
  862. throw new Exception('绑定微信失败');
  863. }
  864. Db::commit();
  865. $this->success('success',$this->userInfo('return'));
  866. } catch (Exception $e) {
  867. Db::rollback();
  868. $this->error($e->getMessage());
  869. }
  870. }
  871. //用户详细资料
  872. public function userInfo($type = 1){
  873. $info = $this->auth->getUserinfo();
  874. if($type == 'return'){
  875. return $info;
  876. }
  877. $this->success(__('success'),$info);
  878. }
  879. /**
  880. * 微信解绑
  881. * @return void
  882. */
  883. public function clearopenid()
  884. {
  885. try {
  886. $userId = $this->auth->id;
  887. $where['id'] = $userId;
  888. $data['openid'] = '';
  889. $user = model('User')->update($data,$where);
  890. $this->success('解绑成功');
  891. } catch (Exception $e) {
  892. $this->error($e->getMessage());
  893. }
  894. }
  895. }