User.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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', 'h5register', '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. public function h5register()
  34. {
  35. $mobile = input('mobile');
  36. $captcha = input('captcha');
  37. $invite_no = input('invite_no','');
  38. if (!$mobile || !$captcha) {
  39. $this->error(__('Invalid parameters'));
  40. }
  41. if (!Validate::regex($mobile, "^1\d{10}$")) {
  42. $this->error(__('Mobile is incorrect'));
  43. }
  44. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  45. $this->error(__('Captcha is incorrect'));
  46. }
  47. $user = \app\common\model\User::getByMobile($mobile);
  48. if ($user) {
  49. $this->error('该手机号已经注册过了');
  50. } else {
  51. $extend = [];
  52. if(!empty($invite_no)){
  53. $inviteUserInfo = \app\common\model\User::where(["invite_no" => $invite_no])->find();
  54. if (!$inviteUserInfo) {
  55. //$this->error("查询不到该邀请码用户信息!");
  56. }else{
  57. $extend['pre_userid'] = $inviteUserInfo['id'];
  58. }
  59. }
  60. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  61. }
  62. if ($ret) {
  63. $this->success('注册成功');
  64. } else {
  65. $this->error($this->auth->getError());
  66. }
  67. }
  68. /**
  69. * 手机验证码登录
  70. *
  71. * @param string $mobile 手机号
  72. * @param string $captcha 验证码
  73. */
  74. public function mobilelogin()
  75. {
  76. $mobile = input('mobile');
  77. $captcha = input('captcha');
  78. if (!$mobile || !$captcha) {
  79. $this->error(__('Invalid parameters'));
  80. }
  81. if (!Validate::regex($mobile, "^1\d{10}$")) {
  82. $this->error(__('Mobile is incorrect'));
  83. }
  84. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  85. $this->error(__('Captcha is incorrect'));
  86. }
  87. $user = \app\common\model\User::getByMobile($mobile);
  88. if ($user) {
  89. if ($user->status == -1) {
  90. $this->error('账户已注销');
  91. }
  92. if ($user->status != 1) {
  93. $this->error(__('Account is locked'));
  94. }
  95. //如果已经有账号则直接登录
  96. $is_register = 0;
  97. $ret = $this->auth->direct($user->id);
  98. } else {
  99. $is_register = 1;
  100. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, []);
  101. }
  102. if ($ret) {
  103. Sms::flush($mobile, 'mobilelogin');
  104. // $data = ['is_register' => $is_register, 'userinfo' => $this->auth->getUserinfo()];
  105. $this->success(__('Logged in successful'), $this->auth->getUserinfo());
  106. } else {
  107. $this->error($this->auth->getError());
  108. }
  109. }
  110. //苹果登录+注册
  111. public function applelogin(){
  112. $iosUserId = input('ios_user_id','');
  113. if(!$iosUserId){
  114. $this->error(__('Invalid parameters'));
  115. }
  116. $user = Db::name('user')->where('ios_user_id',$iosUserId)->find();
  117. if ($user) {
  118. if ($user['status'] == -1) {
  119. $this->error('账户已经注销');
  120. }
  121. if ($user['status'] != 1) {
  122. $this->error(__('Account is locked'));
  123. }
  124. //如果已经有账号则直接登录
  125. $ret = $this->auth->direct($user['id']);
  126. } else {
  127. $ret = $this->auth->ios_register($iosUserId);
  128. }
  129. if ($ret) {
  130. $this->success(__('Logged in successful'), $this->auth->getUserinfo());
  131. } else {
  132. $this->error($this->auth->getError());
  133. }
  134. }
  135. /*
  136. * 修改用户的坐标
  137. * */
  138. public function change_longlat(){
  139. $longitude = input('longitude',0);
  140. $latitude = input('latitude',0);
  141. if(empty($longitude) || empty($latitude)){
  142. $this->error();
  143. }
  144. $data = [
  145. 'longitude' => $longitude,
  146. 'latitude' => $latitude,
  147. ];
  148. Db::name('user')->where('id',$this->auth->id)->update($data);
  149. $this->success();
  150. }
  151. /**
  152. * 绑定用户
  153. */
  154. public function bindUser()
  155. {
  156. $invite_no = input('invite_no'); // 邀请码
  157. if (!$invite_no) {
  158. $this->error("请输入邀请码!");
  159. }
  160. $user_id = $this->auth->id;
  161. if($this->auth->pre_userid){
  162. $this->error('您已经填写过邀请人');
  163. }
  164. // 查询邀请码用户信息
  165. $inviteUserInfo = \app\common\model\User::where(["invite_no" => $invite_no])->find();
  166. if (!$inviteUserInfo) {
  167. $this->error("查询不到该邀请码用户信息!");
  168. }
  169. //判断邀请码用户不能是自己的下级
  170. if ($inviteUserInfo['pre_userid'] == $user_id) {
  171. throw new Exception('对方已被您邀请过');
  172. }
  173. if ($inviteUserInfo->id == $user_id) $this->error("不能邀请自己哦!");
  174. //if ($inviteUserInfo->is_auth != 2) $this->error("该邀请码用户尚未完成实名认证");
  175. //邀请奖励
  176. $res = \app\common\model\User::update(["pre_userid" => $inviteUserInfo->id], ["id" => $user_id]);
  177. if ($res) {
  178. $this->success("恭喜,绑定成功!");
  179. } else {
  180. $this->success("网络繁忙,请稍后重试!");
  181. }
  182. }
  183. /**
  184. * 退出登录
  185. */
  186. public function logout()
  187. {
  188. $this->auth->logout();
  189. $this->success(__('Logout successful'));
  190. }
  191. /**
  192. * 修改会员个人信息
  193. *
  194. * @ApiMethod (POST)
  195. * @param string $avatar 头像地址
  196. * @param string $username 用户名
  197. * @param string $nickname 昵称
  198. * @param string $bio 个人简介
  199. */
  200. public function profile()
  201. {
  202. $field_array = ['avatar','nickname','desc','age_id','gender','job_id','province_id','city_id','has_info'];
  203. $data = [];
  204. foreach($field_array as $key => $field){
  205. //前端传不了post,改了
  206. if(!request()->has($field,'post')){
  207. continue;
  208. }
  209. /*if(!input('?'.$field)){
  210. continue;
  211. }*/
  212. $newone = input($field);
  213. if($field == 'avatar'){
  214. $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
  215. }
  216. $data[$field] = $newone;
  217. }
  218. if(empty($data)){
  219. $this->error('没有任何改变');
  220. }
  221. /*if (!empty($data['nickname']) && !empty($data['avatar']) && !empty($data['age_id']) && $data['has_info']==0) {
  222. $data['has_info'] = 1;
  223. }*/
  224. Db::startTrans();
  225. $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
  226. if($update_rs === false){
  227. Db::rollback();
  228. $this->error('修改资料失败');
  229. }
  230. //完成任务,上传头像
  231. if(isset($data['avatar']) && !empty($data['avatar'])){
  232. \app\common\model\TaskLog::tofinish($this->auth->id,1);
  233. }
  234. Db::commit();
  235. $this->success();
  236. }
  237. /**
  238. * 修改手机号
  239. *
  240. * @param string $mobile 手机号
  241. * @param string $captcha 验证码
  242. */
  243. public function changemobile()
  244. {
  245. $user = $this->auth->getUser();
  246. $mobile = input('mobile');
  247. $captcha = input('captcha');
  248. if (!$mobile || !$captcha) {
  249. $this->error(__('Invalid parameters'));
  250. }
  251. if (!Validate::regex($mobile, "^1\d{10}$")) {
  252. $this->error(__('Mobile is incorrect'));
  253. }
  254. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  255. $this->error(__('Mobile already exists'));
  256. }
  257. $result = Sms::check($mobile, $captcha, 'changeMobile');
  258. if (!$result) {
  259. $this->error(__('Captcha is incorrect'));
  260. }
  261. $verification = $user->verification;
  262. $verification->mobile = 1;
  263. $user->verification = $verification;
  264. $user->mobile = $mobile;
  265. $user->save();
  266. Sms::flush($mobile, 'changeMobile');
  267. $this->success("手机号更换成功!");
  268. }
  269. /**
  270. * 重置密码
  271. *
  272. * @param string $mobile 手机号
  273. * @param string $newpassword 新密码
  274. * @param string $captcha 验证码
  275. */
  276. public function resetpwd()
  277. {
  278. $type = input("type");
  279. $mobile = input("mobile");
  280. $email = input("email");
  281. $newpassword = input("newpassword");
  282. $captcha = input("captcha");
  283. if (!$newpassword || !$captcha) {
  284. $this->error(__('Invalid parameters'));
  285. }
  286. if ($type == 'mobile') {
  287. if (!Validate::regex($mobile, "^1\d{10}$")) {
  288. $this->error(__('Mobile is incorrect'));
  289. }
  290. $user = \app\common\model\User::getByMobile($mobile);
  291. if (!$user) {
  292. $this->error(__('User not found'));
  293. }
  294. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  295. if (!$ret) {
  296. $this->error(__('Captcha is incorrect'));
  297. }
  298. Sms::flush($mobile, 'resetpwd');
  299. } else {
  300. if (!Validate::is($email, "email")) {
  301. $this->error(__('Email is incorrect'));
  302. }
  303. $user = \app\common\model\User::getByEmail($email);
  304. if (!$user) {
  305. $this->error(__('User not found'));
  306. }
  307. $ret = Ems::check($email, $captcha, 'resetpwd');
  308. if (!$ret) {
  309. $this->error(__('Captcha is incorrect'));
  310. }
  311. Ems::flush($email, 'resetpwd');
  312. }
  313. //模拟一次登录
  314. $this->auth->direct($user->id);
  315. $ret = $this->auth->changepwd($newpassword, '', true);
  316. if ($ret) {
  317. $this->success(__('Reset password successful'));
  318. } else {
  319. $this->error($this->auth->getError());
  320. }
  321. }
  322. /**
  323. * 设置密码
  324. * @param string $newpassword 新密码
  325. * @param string $newpassword 新密码
  326. */
  327. public function setpwd()
  328. {
  329. $params = $this->request->param();
  330. $validate = new \app\api\validate\User();
  331. $result = $validate->scene('setPwd')->check($params);
  332. if (!$result) {
  333. $this->error($validate->getError());
  334. }
  335. $ret = $this->auth->changepwd($params['password'], '', true);
  336. if ($ret) {
  337. $this->success(__('Set password successful'));
  338. } else {
  339. $this->error($this->auth->getError());
  340. }
  341. }
  342. /**
  343. * 修改密码
  344. *
  345. * @param string $mobile 手机号
  346. * @param string $newpassword 新密码
  347. * @param string $captcha 验证码
  348. */
  349. public function changepwd()
  350. {
  351. $params = $this->request->param();
  352. $validate = new \app\api\validate\User();
  353. $result = $validate->scene('changePwd')->check($params);
  354. if (!$result) {
  355. $this->error($validate->getError());
  356. }
  357. $mobile = input("mobile");
  358. $newpassword = input("password");
  359. $captcha = input("captcha");
  360. $user = \app\common\model\User::getByMobile($mobile);
  361. if (!$user) {
  362. $this->error(__('User not found'));
  363. }
  364. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  365. if (!$ret) {
  366. $this->error(__('Captcha is incorrect'));
  367. }
  368. Sms::flush($mobile, 'resetpwd');
  369. $ret = $this->auth->changepwd($newpassword, '', true);
  370. if ($ret) {
  371. $this->success(__('Change password successful'));
  372. } else {
  373. $this->error($this->auth->getError());
  374. }
  375. }
  376. /**
  377. * 运营商一键登录
  378. */
  379. public function onLogin()
  380. {
  381. $accessToken = $this->request->param('accessToken');// 运营商预取号获取到的token
  382. $token = $this->request->param('tokenT');// 易盾返回的token
  383. if (!$accessToken || !$token) {
  384. $this->error("参数获取失败!");
  385. }
  386. $params = array(
  387. // 运营商预取号获取到的token
  388. "accessToken" => $accessToken,
  389. // 易盾返回的token
  390. "token" => $token
  391. );
  392. // 获取密钥配置
  393. $configInfo = config("onLogin");
  394. $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);
  395. $ret = $onlogin->check($params);
  396. // $ret = [];
  397. // $ret["code"] = 200;
  398. // $ret["msg"] = "ok";
  399. // $ret["data"] = [
  400. // "phone" => "17574504021",
  401. // "resultCode" => 0
  402. // ];
  403. if ($ret["code"] == 200) {
  404. $data = $ret["data"];
  405. $phone = $data["phone"];
  406. if (empty($phone)) {
  407. // 取号失败,建议进行二次验证,例如短信验证码
  408. $this->error("取号登录失败,请用验证码方式登录!");
  409. } else {
  410. // 取号成功, 执行登录等流程
  411. // 用户登录逻辑 === 开始
  412. $userModel = new \app\common\model\User();
  413. $auth = \app\common\library\Auth::instance();
  414. $userInfo = $userModel->where(["mobile" => $phone])->find();
  415. // 用户信息不存在时使用
  416. $extend = ["mobile" => $phone];
  417. // 判断用户是否已经存在
  418. if ($userInfo) { // 登录
  419. $user = \app\common\model\User::get($userInfo["id"]);
  420. if (!$user) {
  421. $this->error("网络错误!请稍后重试");
  422. }
  423. if ($user->status != 'normal') {
  424. $this->error(__('Account is locked'));
  425. }
  426. $user->save(["logintime" => time()]);
  427. $res = $auth->direct($user->id);
  428. $is_register = 0;
  429. } else { // 注册
  430. // 先随机一个用户名,随后再变更为u+数字id
  431. $username = Random::alnum(20);
  432. $password = Random::alnum(6);
  433. Db::startTrans();
  434. try {
  435. // 默认注册一个会员
  436. $result = $auth->register($username, $password, "", $extend);
  437. if (!$result) {
  438. return false;
  439. }
  440. $user = $auth->getUser();
  441. $fields = ['username' => 'u' . $user->id];
  442. // 更新会员资料
  443. $user = \app\common\model\User::get($user->id);
  444. $user->save($fields);
  445. Db::commit();
  446. } catch (PDOException $e) {
  447. Db::rollback();
  448. $auth->logout();
  449. return false;
  450. }
  451. // 写入登录Cookies和Token
  452. $res = $auth->direct($user->id);
  453. $is_register = 1;
  454. }
  455. $userInfo["userinfo"] = $auth->getUserinfo();
  456. $userInfo["is_register"] = $is_register;
  457. if ($res) {
  458. $this->success("登录成功!", $userInfo);
  459. } else {
  460. $this->error("登录失败!");
  461. }
  462. // 用户登录逻辑 === 结束
  463. }
  464. } else {
  465. $this->error("登录失败,请用验证码方式登录!");
  466. }
  467. }
  468. /**
  469. * 注销账号
  470. *
  471. * @param string $mobile 手机号
  472. * @param string $captcha 验证码
  473. */
  474. public function cancleUser()
  475. {
  476. $user = $this->auth->getUser();
  477. $user->status = -1;
  478. //unset($user->power);
  479. $user->save();
  480. $this->auth->logout();
  481. $this->success("账号注销成功!");
  482. }
  483. /**
  484. * 获取昵称
  485. * @return string
  486. */
  487. public function getNickName()
  488. {
  489. $result['nickname'] = get_rand_nick_name();
  490. $this->success('获取成功',$result);
  491. }
  492. //微信登录,预先假注册
  493. public function wechatlogin(){
  494. $code = input('code','');
  495. if(!$code){
  496. $this->error(__('Invalid parameters'));
  497. }
  498. //微信
  499. $wechat = new Wechat();
  500. $wxuserinfo = $wechat->getAccessToken($code);
  501. if(!$wxuserinfo){
  502. $this->error('openid获取失败');
  503. }
  504. if(!is_array($wxuserinfo) || !isset($wxuserinfo['openid'])){
  505. $this->error('openid获取失败');
  506. }
  507. $openid = $wxuserinfo['openid'];
  508. $user = Db::name('user')->where('openid',$openid)->find();
  509. if ($user) {
  510. if ($user['status'] == -1) {
  511. $this->error('账户已注销');
  512. }
  513. if ($user['status'] != 1) {
  514. $this->error(__('Account is locked'));
  515. }
  516. //如果已经有账号则直接登录
  517. $ret = $this->auth->direct($user['id']);
  518. $is_register = 0;
  519. $userInfo = $this->auth->getUserinfo();
  520. } else {
  521. //记录code和openid,绑定手机号的时候更新openid
  522. $wechatCodeData = [
  523. 'code' => $code,
  524. 'openid' => $openid,
  525. 'createtime' => time(),
  526. ];
  527. $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
  528. if (empty($wechatCode)) {
  529. Db::name('wechat_code')->insertGetId($wechatCodeData);
  530. } else {
  531. Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
  532. }
  533. $ret = true;
  534. $is_register = 1;
  535. $userInfo = [];
  536. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  537. $this->success('获取信息成功', $data, 2);
  538. }
  539. if ($ret) {
  540. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  541. $this->success(__('Logged in successful'), $data);
  542. } else {
  543. $this->error($this->auth->getError());
  544. }
  545. }
  546. //获取openid
  547. public function getopenid() {
  548. //code
  549. $code = $this->request->post('code', '', 'trim');// code值
  550. if (!$code) {
  551. $this->error(__('Invalid parameters'));
  552. }
  553. $config = config('wxMiniProgram');
  554. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  555. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  556. $openidInfo = json_decode($openidInfo,true);
  557. if(!isset($openidInfo['openid'])) {
  558. $this->error('用户openid获取失败', $openidInfo);
  559. }
  560. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  561. //$openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  562. $this->success('获取成功', $openidInfo);
  563. }
  564. /**
  565. * 微信注册来的,绑定手机号
  566. *
  567. * @ApiMethod (POST)
  568. * @param string $mobile 手机号
  569. * @param string $captcha 验证码
  570. */
  571. public function bindmobile()
  572. {
  573. try {
  574. $code = $this->request->param('code');
  575. $mobile = $this->request->param('mobile');
  576. $captcha = $this->request->param('captcha');
  577. if (!$mobile || !$captcha || !$code) {
  578. throw new Exception(__('Invalid parameters'));
  579. }
  580. if (!Validate::regex($mobile, "^1\d{10}$")) {
  581. throw new Exception(__('Mobile is incorrect'));
  582. }
  583. $result = Sms::check($mobile, $captcha, 'changemobile');
  584. if (!$result) {
  585. throw new Exception(__('Captcha is incorrect'));
  586. }
  587. $wechatCodeWhere['code'] = $code;
  588. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  589. if (empty($wechatCode)) {
  590. throw new Exception('请先微信登录');
  591. }
  592. //检查appid绑定的用户
  593. $user = Db::name('user')->where('openid',$wechatCode['openid'])->find();
  594. if ($user) {
  595. if ($user['status'] == -1) {
  596. $this->error('账户已注销');
  597. }
  598. if ($user['status'] != 1) {
  599. $this->error(__('Account is locked'));
  600. }
  601. //如果已经有账号则直接登录
  602. $ret = $this->auth->direct($user['id']);
  603. $this->success('success',$this->userInfo('return'));
  604. }
  605. $where['mobile'] = $mobile;
  606. $userData = model('User')->where($where)->find();//老用户
  607. if (!empty($userData)) {
  608. if (empty($userData['openid'])) {
  609. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  610. } else {
  611. if ($userData['openid'] != $wechatCode['openid']) {
  612. throw new Exception('该手机号已被其他用户绑定');
  613. }
  614. }
  615. $ret = $this->auth->direct($userData['id']);
  616. } else {
  617. $extend = [
  618. 'openid' => $wechatCode['openid'],
  619. ];
  620. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  621. }
  622. if (!$ret) {
  623. throw new Exception($this->auth->getError());
  624. }
  625. Sms::flush($mobile, 'changemobile');
  626. $this->success('success',$this->userInfo('return'));
  627. } catch (Exception $e) {
  628. $this->error($e->getMessage());
  629. }
  630. }
  631. /**
  632. * 手机注册来的,绑定微信
  633. *
  634. * @ApiMethod (POST)
  635. * @param string $wechat_openid
  636. */
  637. public function bindopenid()
  638. {
  639. Db::startTrans();
  640. try {
  641. $code = $this->request->param('code','');
  642. if(!$code){
  643. throw new Exception(__('Invalid parameters'));
  644. }
  645. //微信
  646. $wechat = new Wechat();
  647. $openid = $wechat->getOpenid($code);
  648. if(!$openid){
  649. throw new Exception('openid获取失败');
  650. }
  651. $user = model('User')->find($this->auth->id);
  652. if(!empty($user['openid']) && $openid != $user['openid']){
  653. throw new Exception('已经绑定了微信号');
  654. }
  655. $otherUserWhere['openid'] = $openid;
  656. $otherUserWhere['id'] = ['neq',$this->auth->id];
  657. $otherUser = model('User')->where($otherUserWhere)->find();
  658. if (!empty($otherUser)) {
  659. throw new Exception('该微信已被其他用户绑定过');
  660. }
  661. $user->openid = $openid;
  662. $userRes = $user->save();
  663. if (!$userRes) {
  664. throw new Exception('绑定微信失败');
  665. }
  666. Db::commit();
  667. $this->success('success',$this->userInfo('return'));
  668. } catch (Exception $e) {
  669. Db::rollback();
  670. $this->error($e->getMessage());
  671. }
  672. }
  673. //用户详细资料
  674. public function userInfo($type = 1){
  675. $info = $this->auth->getUserinfo();
  676. if($type == 'return'){
  677. return $info;
  678. }
  679. $this->success(__('success'),$info);
  680. }
  681. /**
  682. * 微信解绑
  683. * @return void
  684. */
  685. public function clearopenid()
  686. {
  687. try {
  688. $userId = $this->auth->id;
  689. $where['id'] = $userId;
  690. $data['openid'] = '';
  691. $user = model('User')->update($data,$where);
  692. $this->success('解绑成功');
  693. } catch (Exception $e) {
  694. $this->error($e->getMessage());
  695. }
  696. }
  697. }