User.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. public function realauth()
  774. {
  775. try {
  776. $realName = $this->request->param('real_name','');
  777. $idCard = $this->request->param('id_card','');
  778. if ($this->auth->is_auth == 2) {
  779. $this->error('您已经真人认证过了~');
  780. }
  781. if (empty($realName)) {
  782. throw new Exception('请输入姓名');
  783. }
  784. if (empty($idCard)) {
  785. throw new Exception('请输入身份证号');
  786. }
  787. $userAuthWhere['user_id'] = ['neq',$this->auth->id];
  788. $userAuthWhere['idcard'] = $idCard;
  789. // 获取用户已经实名认证的数量
  790. $authenticatedCount = model('UserAuth')->where(['idcard' => $idCard])->count();
  791. // 如果已经实名认证的数量不超过3个
  792. if ($authenticatedCount > 3) {
  793. throw new Exception('您当前身份证号已经认证过3次');
  794. }
  795. /*$userAuth = model('UserAuth')->where($userAuthWhere)->find();
  796. if (!empty($userAuth)) {
  797. throw new Exception('该身份证号已被其他用户实名验证过');
  798. }*/
  799. /*$userService = new UserService();
  800. $faceParams = [
  801. 'real_name' => $realName,
  802. 'id_card' => $idCard,
  803. 'user_id' => $this->auth->id,
  804. ];
  805. $res = $userService->faceAuth($faceParams);
  806. if (!$res['status']) {
  807. $this->error('您的网络开小差啦5~');
  808. }
  809. $rs = $res['data'];
  810. if (!$rs || $rs['code'] != 0) {
  811. $this->error('您的网络开小差啦6~');
  812. }
  813. $user_auth = [
  814. 'user_id' => $this->auth->id,
  815. 'realname' => $realName,
  816. 'idcard' => $idCard,
  817. 'certify_id' => isset($rs['result']['faceId']) ? $rs['result']['faceId'] : '',
  818. 'out_trade_no' => isset($rs['result']['orderNo']) ? $rs['result']['orderNo'] : '',
  819. 'status' => 0,
  820. 'createtime' => time(),
  821. 'updatetime' => time()
  822. ];*/
  823. $userService = new UserService();
  824. $aliParams = [
  825. 'id_card' => $idCard,
  826. 'real_name' => $realName,
  827. ];
  828. $aliCheckRes = $userService->aliCheck($aliParams);
  829. if (!$aliCheckRes['status']) {
  830. throw new Exception($aliCheckRes['msg']);
  831. }
  832. $user_auth = [
  833. 'user_id' => $this->auth->id,
  834. 'realname' => $realName,
  835. 'idcard' => $idCard,
  836. 'certify_id' => '',
  837. 'out_trade_no' => '',
  838. 'status' => 1,
  839. 'createtime' => time(),
  840. ];
  841. //开启事务
  842. Db::startTrans();
  843. //查询是否认证过
  844. $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  845. if ($info) {
  846. $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
  847. } else {
  848. $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
  849. }
  850. if (!$auth_rs) {
  851. Db::rollback();
  852. $this->error('您的网络开小差啦7~');
  853. }
  854. //修改用户表认证状态
  855. $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', 2);
  856. if ($user_rs === false) {
  857. Db::rollback();
  858. $this->error('您的网络开小差啦8~');
  859. }
  860. Db::commit();
  861. /*$return_data = [
  862. 'face_id' => $user_auth['certify_id'],
  863. 'order_no' => $user_auth['out_trade_no'],
  864. 'user_id' => (string)$this->auth->id,
  865. 'nonce' => $rs['nonce'],
  866. 'sign' => $rs['sign'],
  867. ];*/
  868. $this->success('验证成功');
  869. } catch (Exception $e) {
  870. $this->error($e->getMessage());
  871. }
  872. }
  873. //查询真人认证结果
  874. public function getrealauthresult() {
  875. $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  876. if (!$user_auth) {
  877. $this->success('尚未认证');
  878. }
  879. if ($user_auth['status'] == 1) {
  880. $this->success('真人认证通过');
  881. }
  882. if (!$user_auth['certify_id']) {
  883. $this->success('请先进行真人认证');
  884. }
  885. $tencentConfig = config('tencent_yun');
  886. $sercrtId = isset($tencentConfig['SecretId']) ? $tencentConfig['SecretId'] : '';
  887. $sercrtKey = isset($tencentConfig['SecretKey']) ? $tencentConfig['SecretKey'] : '';
  888. //获取token
  889. $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.$sercrtId.'&secret='.$sercrtKey.'&grant_type=client_credential&version=1.0.0';
  890. $token_result = file_get_contents($token_url);
  891. if (!$token_result) {
  892. $this->error('您的网络开小差啦1~');
  893. }
  894. $token_result = json_decode($token_result, true);
  895. if ($token_result['code'] != 0) {
  896. $this->error('您的网络开小差啦2~');
  897. }
  898. $token = $token_result['access_token'];
  899. //获取签名鉴权参数ticket
  900. $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.$sercrtId.'&access_token='.$token.'&type=SIGN&version=1.0.0';
  901. $ticket_result = file_get_contents($ticket_url);
  902. if (!$ticket_result) {
  903. $this->error('您的网络开小差啦3~');
  904. }
  905. $ticket_result = json_decode($ticket_result, true);
  906. if ($ticket_result['code'] != 0) {
  907. $this->error('您的网络开小差啦4~');
  908. }
  909. $ticket = $ticket_result['tickets'][0]['value'];
  910. //获取签名
  911. $sign_data = [
  912. 'wbappid' => $sercrtId,
  913. 'orderNo' => $user_auth['out_trade_no'],
  914. 'version' => '1.0.0',
  915. 'ticket' => $ticket,
  916. 'nonce' => Random::alnum(32)
  917. ];//p($sign_data);
  918. asort($sign_data); //p($sign_data);//排序
  919. $sign_string = join('', $sign_data);//p($sign_string);
  920. $sign = sha1($sign_string);//p($sign);
  921. //人脸核身结果查询
  922. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
  923. $data = [
  924. 'appId' => $sercrtId,
  925. 'version' => '1.0.0',
  926. 'nonce' => $sign_data['nonce'],
  927. 'orderNo' => $user_auth['out_trade_no'],
  928. 'sign' => $sign
  929. ];
  930. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  931. if (!$rs) {
  932. $this->error('您的网络开小差啦5~');
  933. }
  934. $rs = json_decode($rs, true);
  935. if (!$rs || $rs['code'] != 0) {
  936. $this->error($rs['msg']);
  937. }
  938. if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
  939. $edit_data['status'] = 2;
  940. $msg = '真人认证成功';
  941. } else {
  942. $edit_data['status'] = -1;
  943. $edit_data['certify_id'] = '';
  944. $edit_data['out_trade_no'] = '';
  945. $msg = '真人认证失败';
  946. }
  947. $edit_data['updatetime'] = time();
  948. //开启事务
  949. Db::startTrans();
  950. //修改认证信息
  951. $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
  952. if (!$result) {
  953. Db::rollback();
  954. $this->error('查询认证结果失败2');
  955. }
  956. //修改用户信息
  957. $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', $edit_data['status']);
  958. if (!$rs) {
  959. Db::rollback();
  960. $this->error('查询认证结果失败3');
  961. }
  962. if ($edit_data['status'] == 2) { //通过
  963. //tag任务赠送金币
  964. //真人认证奖励
  965. /*$task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,20);
  966. if($task_rs === false){
  967. Db::rollback();
  968. $this->error('完成任务赠送奖励失败');
  969. }*/
  970. //系统消息
  971. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
  972. } else {
  973. //系统消息
  974. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
  975. }
  976. Db::commit();
  977. $this->success($msg);
  978. }
  979. /**
  980. * 微信注册来的,绑定手机号
  981. *
  982. * @ApiMethod (POST)
  983. * @param string $mobile 手机号
  984. * @param string $captcha 验证码
  985. */
  986. public function bindmobile()
  987. {
  988. Db::startTrans();
  989. try {
  990. $code = $this->request->param('code');
  991. $mobile = $this->request->param('mobile');
  992. $captcha = $this->request->param('captcha');
  993. if (!$mobile || !$captcha || !$code) {
  994. throw new Exception(__('Invalid parameters'));
  995. }
  996. if (!Validate::regex($mobile, "^1\d{10}$")) {
  997. throw new Exception(__('Mobile is incorrect'));
  998. }
  999. $result = Sms::check($mobile, $captcha, 'changemobile');
  1000. if (!$result) {
  1001. throw new Exception(__('Captcha is incorrect'));
  1002. }
  1003. $where['mobile'] = $mobile;
  1004. $userData = model('User')->where($where)->find();//老用户
  1005. $wechatCodeWhere['code'] = $code;
  1006. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  1007. if (empty($wechatCode)) {
  1008. throw new Exception('请先微信登录');
  1009. }
  1010. if (!empty($userData)) {
  1011. if (empty($userData['openid'])) {
  1012. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  1013. } else {
  1014. if ($userData['openid'] != $wechatCode['openid']) {
  1015. throw new Exception('该手机号已被其他用户绑定');
  1016. }
  1017. }
  1018. $ret = $this->auth->direct($userData['id']);
  1019. } else {
  1020. $extend = [
  1021. 'openid' => $wechatCode['openid'],
  1022. ];
  1023. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  1024. }
  1025. if (!$ret) {
  1026. throw new Exception($this->auth->getError());
  1027. }
  1028. Sms::flush($mobile, 'changemobile');
  1029. Db::commit();
  1030. $this->success('success',$this->userInfo('return'));
  1031. } catch (Exception $e) {
  1032. Db::rollback();
  1033. $this->error($e->getMessage());
  1034. }
  1035. }
  1036. /**
  1037. * 手机注册来的,绑定微信
  1038. *
  1039. * @ApiMethod (POST)
  1040. * @param string $wechat_openid
  1041. */
  1042. public function bindopenid()
  1043. {
  1044. Db::startTrans();
  1045. try {
  1046. $code = $this->request->param('code','');
  1047. if(!$code){
  1048. throw new Exception(__('Invalid parameters'));
  1049. }
  1050. //微信
  1051. $wechat = new Wechat();
  1052. $openid = $wechat->getOpenid($code);
  1053. if(!$openid){
  1054. throw new Exception('openid获取失败');
  1055. }
  1056. $user = model('User')->find($this->auth->id);
  1057. if(!empty($user['openid']) && $openid != $user['openid']){
  1058. throw new Exception('已经绑定了微信号');
  1059. }
  1060. $otherUserWhere['openid'] = $openid;
  1061. $otherUserWhere['id'] = ['neq',$this->auth->id];
  1062. $otherUser = model('User')->where($otherUserWhere)->find();
  1063. if (!empty($otherUser)) {
  1064. throw new Exception('该微信已被其他用户绑定过');
  1065. }
  1066. $user->openid = $openid;
  1067. $userRes = $user->save();
  1068. if (!$userRes) {
  1069. throw new Exception('绑定微信失败');
  1070. }
  1071. Db::commit();
  1072. $this->success('success',$this->userInfo('return'));
  1073. } catch (Exception $e) {
  1074. Db::rollback();
  1075. $this->error($e->getMessage());
  1076. }
  1077. }
  1078. //用户详细资料
  1079. public function userInfo($type = 1){
  1080. $info = $this->auth->getUserinfo();
  1081. if($type == 'return'){
  1082. return $info;
  1083. }
  1084. $this->success(__('success'),$info);
  1085. }
  1086. /**
  1087. * 微信解绑
  1088. * @return void
  1089. */
  1090. public function clearopenid()
  1091. {
  1092. try {
  1093. $userId = $this->auth->id;
  1094. $where['id'] = $userId;
  1095. $data['openid'] = '';
  1096. $user = model('User')->update($data,$where);
  1097. $this->success('解绑成功');
  1098. } catch (Exception $e) {
  1099. $this->error($e->getMessage());
  1100. }
  1101. }
  1102. }