User.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. /*
  380. public function onLogin()
  381. {
  382. $accessToken = $this->request->param('accessToken');// 运营商预取号获取到的token
  383. $token = $this->request->param('tokenT');// 易盾返回的token
  384. if (!$accessToken || !$token) {
  385. $this->error("参数获取失败!");
  386. }
  387. $params = array(
  388. // 运营商预取号获取到的token
  389. "accessToken" => $accessToken,
  390. // 易盾返回的token
  391. "token" => $token
  392. );
  393. // 获取密钥配置
  394. $configInfo = config("onLogin");
  395. $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);
  396. $ret = $onlogin->check($params);
  397. // $ret = [];
  398. // $ret["code"] = 200;
  399. // $ret["msg"] = "ok";
  400. // $ret["data"] = [
  401. // "phone" => "17574504021",
  402. // "resultCode" => 0
  403. // ];
  404. if ($ret["code"] == 200) {
  405. $data = $ret["data"];
  406. $phone = $data["phone"];
  407. if (empty($phone)) {
  408. // 取号失败,建议进行二次验证,例如短信验证码
  409. $this->error("取号登录失败,请用验证码方式登录!");
  410. } else {
  411. // 取号成功, 执行登录等流程
  412. // 用户登录逻辑 === 开始
  413. $userModel = new \app\common\model\User();
  414. $auth = \app\common\library\Auth::instance();
  415. $userInfo = $userModel->where(["mobile" => $phone])->find();
  416. // 用户信息不存在时使用
  417. $extend = ["mobile" => $phone];
  418. // 判断用户是否已经存在
  419. if ($userInfo) { // 登录
  420. $user = \app\common\model\User::get($userInfo["id"]);
  421. if (!$user) {
  422. $this->error("网络错误!请稍后重试");
  423. }
  424. if ($user->status != 'normal') {
  425. $this->error(__('Account is locked'));
  426. }
  427. $user->save(["logintime" => time()]);
  428. $res = $auth->direct($user->id);
  429. $is_register = 0;
  430. } else { // 注册
  431. // 先随机一个用户名,随后再变更为u+数字id
  432. $username = Random::alnum(20);
  433. $password = Random::alnum(6);
  434. Db::startTrans();
  435. try {
  436. // 默认注册一个会员
  437. $result = $auth->register($username, $password, "", $extend);
  438. if (!$result) {
  439. return false;
  440. }
  441. $user = $auth->getUser();
  442. $fields = ['username' => 'u' . $user->id];
  443. // 更新会员资料
  444. $user = \app\common\model\User::get($user->id);
  445. $user->save($fields);
  446. Db::commit();
  447. } catch (PDOException $e) {
  448. Db::rollback();
  449. $auth->logout();
  450. return false;
  451. }
  452. // 写入登录Cookies和Token
  453. $res = $auth->direct($user->id);
  454. $is_register = 1;
  455. }
  456. $userInfo["userinfo"] = $auth->getUserinfo();
  457. $userInfo["is_register"] = $is_register;
  458. if ($res) {
  459. $this->success("登录成功!", $userInfo);
  460. } else {
  461. $this->error("登录失败!");
  462. }
  463. // 用户登录逻辑 === 结束
  464. }
  465. } else {
  466. $this->error("登录失败,请用验证码方式登录!");
  467. }
  468. }
  469. */
  470. /**
  471. * 注销账号
  472. *
  473. * @param string $mobile 手机号
  474. * @param string $captcha 验证码
  475. */
  476. public function cancleUser()
  477. {
  478. $user = $this->auth->getUser();
  479. $user->status = -1;
  480. //unset($user->power);
  481. $user->save();
  482. $this->auth->logout();
  483. $this->success("账号注销成功!");
  484. }
  485. /**
  486. * 获取昵称
  487. * @return string
  488. */
  489. public function getNickName()
  490. {
  491. $result['nickname'] = get_rand_nick_name();
  492. $this->success('获取成功',$result);
  493. }
  494. //微信登录,预先假注册
  495. public function wechatlogin(){
  496. $code = input('code','');
  497. if(!$code){
  498. $this->error(__('Invalid parameters'));
  499. }
  500. //微信
  501. $wechat = new Wechat();
  502. $wxuserinfo = $wechat->getAccessToken($code);
  503. if(!$wxuserinfo){
  504. $this->error('openid获取失败');
  505. }
  506. if(!is_array($wxuserinfo) || !isset($wxuserinfo['openid'])){
  507. $this->error('openid获取失败');
  508. }
  509. $openid = $wxuserinfo['openid'];
  510. $user = Db::name('user')->where('openid',$openid)->find();
  511. if ($user) {
  512. if ($user['status'] == -1) {
  513. $this->error('账户已注销');
  514. }
  515. if ($user['status'] != 1) {
  516. $this->error(__('Account is locked'));
  517. }
  518. //如果已经有账号则直接登录
  519. $ret = $this->auth->direct($user['id']);
  520. $is_register = 0;
  521. $userInfo = $this->auth->getUserinfo();
  522. } else {
  523. //记录code和openid,绑定手机号的时候更新openid
  524. $wechatCodeData = [
  525. 'code' => $code,
  526. 'openid' => $openid,
  527. 'createtime' => time(),
  528. ];
  529. $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
  530. if (empty($wechatCode)) {
  531. Db::name('wechat_code')->insertGetId($wechatCodeData);
  532. } else {
  533. Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
  534. }
  535. $ret = true;
  536. $is_register = 1;
  537. $userInfo = [];
  538. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  539. $this->success('获取信息成功', $data, 2);
  540. }
  541. if ($ret) {
  542. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  543. $this->success(__('Logged in successful'), $data);
  544. } else {
  545. $this->error($this->auth->getError());
  546. }
  547. }
  548. //获取openid
  549. public function getopenid() {
  550. //code
  551. $code = $this->request->post('code', '', 'trim');// code值
  552. if (!$code) {
  553. $this->error(__('Invalid parameters'));
  554. }
  555. $config = config('wxMiniProgram');
  556. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  557. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  558. $openidInfo = json_decode($openidInfo,true);
  559. if(!isset($openidInfo['openid'])) {
  560. $this->error('用户openid获取失败', $openidInfo);
  561. }
  562. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  563. //$openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  564. $this->success('获取成功', $openidInfo);
  565. }
  566. /**
  567. * 微信注册来的,绑定手机号
  568. *
  569. * @ApiMethod (POST)
  570. * @param string $mobile 手机号
  571. * @param string $captcha 验证码
  572. */
  573. public function bindmobile()
  574. {
  575. try {
  576. $code = $this->request->param('code');
  577. $mobile = $this->request->param('mobile');
  578. $captcha = $this->request->param('captcha');
  579. if (!$mobile || !$captcha || !$code) {
  580. throw new Exception(__('Invalid parameters'));
  581. }
  582. if (!Validate::regex($mobile, "^1\d{10}$")) {
  583. throw new Exception(__('Mobile is incorrect'));
  584. }
  585. $result = Sms::check($mobile, $captcha, 'changemobile');
  586. if (!$result) {
  587. throw new Exception(__('Captcha is incorrect'));
  588. }
  589. $wechatCodeWhere['code'] = $code;
  590. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  591. if (empty($wechatCode)) {
  592. throw new Exception('请先微信登录');
  593. }
  594. //检查appid绑定的用户
  595. $user = Db::name('user')->where('openid',$wechatCode['openid'])->find();
  596. if ($user) {
  597. if ($user['status'] == -1) {
  598. $this->error('账户已注销');
  599. }
  600. if ($user['status'] != 1) {
  601. $this->error(__('Account is locked'));
  602. }
  603. //如果已经有账号则直接登录
  604. $ret = $this->auth->direct($user['id']);
  605. $this->success('success',$this->userInfo('return'));
  606. }
  607. $where['mobile'] = $mobile;
  608. $userData = model('User')->where($where)->find();//老用户
  609. if (!empty($userData)) {
  610. if (empty($userData['openid'])) {
  611. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  612. } else {
  613. if ($userData['openid'] != $wechatCode['openid']) {
  614. throw new Exception('该手机号已被其他用户绑定');
  615. }
  616. }
  617. $ret = $this->auth->direct($userData['id']);
  618. } else {
  619. $extend = [
  620. 'openid' => $wechatCode['openid'],
  621. ];
  622. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  623. }
  624. if (!$ret) {
  625. throw new Exception($this->auth->getError());
  626. }
  627. Sms::flush($mobile, 'changemobile');
  628. $this->success('success',$this->userInfo('return'));
  629. } catch (Exception $e) {
  630. $this->error($e->getMessage());
  631. }
  632. }
  633. /**
  634. * 手机注册来的,绑定微信
  635. *
  636. * @ApiMethod (POST)
  637. * @param string $wechat_openid
  638. */
  639. public function bindopenid()
  640. {
  641. Db::startTrans();
  642. try {
  643. $code = $this->request->param('code','');
  644. if(!$code){
  645. throw new Exception(__('Invalid parameters'));
  646. }
  647. //微信
  648. $wechat = new Wechat();
  649. $openid = $wechat->getOpenid($code);
  650. if(!$openid){
  651. throw new Exception('openid获取失败');
  652. }
  653. $user = model('User')->find($this->auth->id);
  654. if(!empty($user['openid']) && $openid != $user['openid']){
  655. throw new Exception('已经绑定了微信号');
  656. }
  657. $otherUserWhere['openid'] = $openid;
  658. $otherUserWhere['id'] = ['neq',$this->auth->id];
  659. $otherUser = model('User')->where($otherUserWhere)->find();
  660. if (!empty($otherUser)) {
  661. throw new Exception('该微信已被其他用户绑定过');
  662. }
  663. $user->openid = $openid;
  664. $userRes = $user->save();
  665. if (!$userRes) {
  666. throw new Exception('绑定微信失败');
  667. }
  668. Db::commit();
  669. $this->success('success',$this->userInfo('return'));
  670. } catch (Exception $e) {
  671. Db::rollback();
  672. $this->error($e->getMessage());
  673. }
  674. }
  675. //用户详细资料
  676. public function userInfo($type = 1){
  677. $info = $this->auth->getUserinfo();
  678. if($type == 'return'){
  679. return $info;
  680. }
  681. $this->success(__('success'),$info);
  682. }
  683. /**
  684. * 微信解绑
  685. * @return void
  686. */
  687. public function clearopenid()
  688. {
  689. try {
  690. $userId = $this->auth->id;
  691. $where['id'] = $userId;
  692. $data['openid'] = '';
  693. $user = model('User')->update($data,$where);
  694. $this->success('解绑成功');
  695. } catch (Exception $e) {
  696. $this->error($e->getMessage());
  697. }
  698. }
  699. }