User.php 30 KB

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