User.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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 = $this->request->request('mobile');
  63. $captcha = $this->request->request('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'), $data);
  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 = $this->request->request('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) $this->error("查询不到该邀请码用户信息!");
  150. if ($inviteUserInfo->id == $user_id) $this->error("不能邀请自己哦!");
  151. if ($inviteUserInfo->is_auth != 2) $this->error("该邀请码用户尚未完成实名认证");
  152. $res = \app\common\model\User::update(["pre_userid" => $inviteUserInfo->id,"bindtime" => time()], ["id" => $user_id]);
  153. if ($res) {
  154. $this->success("恭喜,绑定成功!");
  155. } else {
  156. $this->success("网络繁忙,请稍后重试!");
  157. }
  158. }
  159. /**
  160. * 注册会员
  161. *
  162. * @param string $username 用户名
  163. * @param string $password 密码
  164. * @param string $email 邮箱
  165. * @param string $mobile 手机号
  166. * @param string $code 验证码
  167. */
  168. public function register()
  169. {
  170. $username = $this->request->request('username');
  171. $password = $this->request->request('password');
  172. $mobile = $this->request->request('mobile');
  173. $code = $this->request->request('code');
  174. if (!$username || !$password) {
  175. $this->error(__('Invalid parameters'));
  176. }
  177. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  178. $this->error(__('Mobile is incorrect'));
  179. }
  180. // $ret = Sms::check($mobile, $code, 'register');
  181. // if (!$ret) {
  182. // $this->error(__('Captcha is incorrect'));
  183. // }
  184. $ret = $this->auth->register($username, $password, $mobile, []);
  185. if ($ret) {
  186. $data = ['userinfo' => $this->auth->getUserinfo()];
  187. $this->success(__('Sign up successful'), $data);
  188. } else {
  189. $this->error($this->auth->getError());
  190. }
  191. }
  192. /**
  193. * 退出登录
  194. */
  195. public function logout()
  196. {
  197. $this->auth->logout();
  198. $this->success(__('Logout successful'));
  199. }
  200. /**
  201. * 修改会员个人信息
  202. *
  203. * @ApiMethod (POST)
  204. * @param string $avatar 头像地址
  205. * @param string $username 用户名
  206. * @param string $nickname 昵称
  207. * @param string $bio 个人简介
  208. */
  209. public function profile()
  210. {
  211. $field_array = ['avatar','nickname','desc','age_id','gender','job_id','province_id','city_id','has_info'];
  212. $data = [];
  213. foreach($field_array as $key => $field){
  214. //前端传不了post,改了
  215. if(!request()->has($field,'post')){
  216. continue;
  217. }
  218. /*if(!input('?'.$field)){
  219. continue;
  220. }*/
  221. $newone = input($field);
  222. if($field == 'avatar'){
  223. $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
  224. }
  225. $data[$field] = $newone;
  226. }
  227. if(empty($data)){
  228. $this->error('没有任何改变');
  229. }
  230. /*if (!empty($data['nickname']) && !empty($data['avatar']) && !empty($data['age_id']) && $data['has_info']==0) {
  231. $data['has_info'] = 1;
  232. }*/
  233. Db::startTrans();
  234. $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
  235. if($update_rs === false){
  236. Db::rollback();
  237. $this->error('修改资料失败');
  238. }
  239. Db::commit();
  240. $this->success();
  241. }
  242. /**
  243. * 修改手机号
  244. *
  245. * @param string $mobile 手机号
  246. * @param string $captcha 验证码
  247. */
  248. public function changemobile()
  249. {
  250. $user = $this->auth->getUser();
  251. $mobile = $this->request->request('mobile');
  252. $captcha = $this->request->request('captcha');
  253. if (!$mobile || !$captcha) {
  254. $this->error(__('Invalid parameters'));
  255. }
  256. if (!Validate::regex($mobile, "^1\d{10}$")) {
  257. $this->error(__('Mobile is incorrect'));
  258. }
  259. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  260. $this->error(__('Mobile already exists'));
  261. }
  262. $result = Sms::check($mobile, $captcha, 'changeMobile');
  263. if (!$result) {
  264. $this->error(__('Captcha is incorrect'));
  265. }
  266. $verification = $user->verification;
  267. $verification->mobile = 1;
  268. $user->verification = $verification;
  269. $user->mobile = $mobile;
  270. $user->save();
  271. Sms::flush($mobile, 'changeMobile');
  272. $this->success("手机号更换成功!");
  273. }
  274. /**
  275. * 第三方登录
  276. *
  277. * @param string $platform 平台名称
  278. * @param string $code Code码
  279. */
  280. public function third()
  281. {
  282. $url = url('user/index');
  283. $platform = $this->request->request("platform");
  284. $code = $this->request->request("code");
  285. $config = get_addon_config('third');
  286. if (!$config || !isset($config[$platform])) {
  287. $this->error(__('Invalid parameters'));
  288. }
  289. $app = new \addons\third\library\Application($config);
  290. //通过code换access_token和绑定会员
  291. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  292. if ($result) {
  293. $loginret = \addons\third\library\Service::connect($platform, $result);
  294. if ($loginret) {
  295. $data = [
  296. 'userinfo' => $this->auth->getUserinfo(),
  297. 'thirdinfo' => $result
  298. ];
  299. $this->success(__('Logged in successful'), $data);
  300. }
  301. }
  302. $this->error(__('Operation failed'), $url);
  303. }
  304. /**
  305. * 重置密码
  306. *
  307. * @param string $mobile 手机号
  308. * @param string $newpassword 新密码
  309. * @param string $captcha 验证码
  310. */
  311. public function resetpwd()
  312. {
  313. $type = $this->request->request("type");
  314. $mobile = $this->request->request("mobile");
  315. $email = $this->request->request("email");
  316. $newpassword = $this->request->request("newpassword");
  317. $captcha = $this->request->request("captcha");
  318. if (!$newpassword || !$captcha) {
  319. $this->error(__('Invalid parameters'));
  320. }
  321. if ($type == 'mobile') {
  322. if (!Validate::regex($mobile, "^1\d{10}$")) {
  323. $this->error(__('Mobile is incorrect'));
  324. }
  325. $user = \app\common\model\User::getByMobile($mobile);
  326. if (!$user) {
  327. $this->error(__('User not found'));
  328. }
  329. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  330. if (!$ret) {
  331. $this->error(__('Captcha is incorrect'));
  332. }
  333. Sms::flush($mobile, 'resetpwd');
  334. } else {
  335. if (!Validate::is($email, "email")) {
  336. $this->error(__('Email is incorrect'));
  337. }
  338. $user = \app\common\model\User::getByEmail($email);
  339. if (!$user) {
  340. $this->error(__('User not found'));
  341. }
  342. $ret = Ems::check($email, $captcha, 'resetpwd');
  343. if (!$ret) {
  344. $this->error(__('Captcha is incorrect'));
  345. }
  346. Ems::flush($email, 'resetpwd');
  347. }
  348. //模拟一次登录
  349. $this->auth->direct($user->id);
  350. $ret = $this->auth->changepwd($newpassword, '', true);
  351. if ($ret) {
  352. $this->success(__('Reset password successful'));
  353. } else {
  354. $this->error($this->auth->getError());
  355. }
  356. }
  357. /**
  358. * 设置密码
  359. * @param string $newpassword 新密码
  360. * @param string $newpassword 新密码
  361. */
  362. public function setpwd()
  363. {
  364. $params = $this->request->param();
  365. $validate = new \app\api\validate\User();
  366. $result = $validate->scene('setPwd')->check($params);
  367. if (!$result) {
  368. $this->error($validate->getError());
  369. }
  370. $ret = $this->auth->changepwd($params['password'], '', true);
  371. if ($ret) {
  372. $this->success(__('Set password successful'));
  373. } else {
  374. $this->error($this->auth->getError());
  375. }
  376. }
  377. /**
  378. * 修改密码
  379. *
  380. * @param string $mobile 手机号
  381. * @param string $newpassword 新密码
  382. * @param string $captcha 验证码
  383. */
  384. public function changepwd()
  385. {
  386. $params = $this->request->param();
  387. $validate = new \app\api\validate\User();
  388. $result = $validate->scene('changePwd')->check($params);
  389. if (!$result) {
  390. $this->error($validate->getError());
  391. }
  392. $mobile = $this->request->request("mobile");
  393. $newpassword = $this->request->request("password");
  394. $captcha = $this->request->request("captcha");
  395. $user = \app\common\model\User::getByMobile($mobile);
  396. if (!$user) {
  397. $this->error(__('User not found'));
  398. }
  399. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  400. if (!$ret) {
  401. $this->error(__('Captcha is incorrect'));
  402. }
  403. Sms::flush($mobile, 'resetpwd');
  404. $ret = $this->auth->changepwd($newpassword, '', true);
  405. if ($ret) {
  406. $this->success(__('Change password successful'));
  407. } else {
  408. $this->error($this->auth->getError());
  409. }
  410. }
  411. /**
  412. * 获取用户openid
  413. */
  414. public function getUserOpenid()
  415. {
  416. $code = $this->request->param('code');// code值
  417. if (!$code) {
  418. $this->error(__('Invalid parameters'));
  419. }
  420. $config = config("wxMiniProgram");
  421. $getopenid = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $config["appid"] . "&secret=" . $config["secret"] . "&js_code=" . $code . "&grant_type=authorization_code";
  422. $openidInfo = $this->getJson($getopenid);
  423. if (!isset($openidInfo["openid"])) {
  424. $this->error("用户openid获取失败", $openidInfo);
  425. }
  426. // 获取的结果存入数据库
  427. $sessionkeyModel = new \app\common\model\UserSessionkey();
  428. if ($sessionkeyModel->where(["openid" => $openidInfo["openid"]])->find()) {
  429. $update = [];
  430. $update["sessionkey"] = $openidInfo["session_key"];
  431. $res = $sessionkeyModel->update($update, ["openid" => $openidInfo["openid"]]);
  432. } else {
  433. $insert = [];
  434. $insert["sessionkey"] = $openidInfo["session_key"];
  435. $insert["openid"] = $openidInfo["openid"];
  436. $insert["createtime"] = time();
  437. $res = $sessionkeyModel->insert($insert);
  438. }
  439. if ($res) {
  440. $this->success("获取成功!", $openidInfo);
  441. } else {
  442. $this->error("获取失败!");
  443. }
  444. }
  445. /**
  446. * 微信小程序登录
  447. */
  448. public function wxMiniProgramLogin()
  449. {
  450. $openid = $this->request->param('openid');// openid值
  451. $encryptedData = $this->request->param('encryptedData');// 加密数据
  452. $iv = $this->request->param('iv');// 加密算法
  453. $signature = $this->request->param('signature');// 签名验证
  454. $rawData = $this->request->param('rawData');// 签名验证
  455. $logintype = $this->request->param('loginType', 1);// 登录方式:1=手机号,2=微信授权openid
  456. if (!$openid || !$encryptedData || !$iv) {
  457. $this->error(__('Invalid parameters'));
  458. }
  459. $encryptedData = urldecode($encryptedData);
  460. $config = config("wxMiniProgram");
  461. // 获取openid和sessionkey
  462. $sessionkeyModel = new \app\common\model\UserSessionkey();
  463. $openidInfo = $sessionkeyModel->where(["openid" => $openid])->find();
  464. $openid = $openidInfo['openid'];
  465. $session_key = $openidInfo['sessionkey'];
  466. // // 数据签名校验
  467. // $signature2 = sha1($rawData . $session_key);
  468. // if ($signature != $signature2) {
  469. // $this->error(__('数据签名验证失败'));
  470. // }
  471. // 根据加密数据和加密算法获取用户信息
  472. $pc = new WXBizDataCrypt($config["appid"], $session_key);
  473. $data = "";
  474. $errCode = $pc->decryptData($encryptedData, $iv, $data);
  475. if ($errCode == 0) {
  476. $data = json_decode($data, true);
  477. // 用户登录逻辑 === 开始
  478. $userModel = new \app\common\model\User();
  479. $auth = \app\common\library\Auth::instance();
  480. if ($logintype == 1) { // 手机号登录
  481. $userInfo = $userModel->where(["mobile" => $data["purePhoneNumber"]])->find();
  482. // 用户信息不存在时使用
  483. $extend = ["mobile" => $data["purePhoneNumber"]];
  484. } else { // 微信授权openid登录
  485. $userInfo = $userModel->where(["openid" => $openid])->find();
  486. // 用户信息不存在时使用
  487. $extend = [
  488. 'openid' => $data['openId'],
  489. 'nickname' => $data['nickName'],
  490. 'avatar' => $data['avatarUrl'],
  491. 'gender' => $data['gender'],
  492. ];
  493. }
  494. // 判断用户是否已经存在
  495. if ($userInfo) { // 登录
  496. $user = \app\common\model\User::get($userInfo["id"]);
  497. if (!$user) {
  498. $this->error("网络错误!请稍后重试");
  499. }
  500. $user->save(["logintime" => time()]);
  501. $res = $auth->direct($user->id);
  502. $is_register = 0;
  503. } else { // 注册
  504. // 先随机一个用户名,随后再变更为u+数字id
  505. $username = Random::alnum(20);
  506. $password = Random::alnum(6);
  507. Db::startTrans();
  508. try {
  509. // 默认注册一个会员
  510. $result = $auth->register($username, $password, "", $extend);
  511. if (!$result) {
  512. return false;
  513. }
  514. $user = $auth->getUser();
  515. $fields = ['username' => 'u' . $user->id];
  516. // 更新会员资料
  517. $user = \app\common\model\User::get($user->id);
  518. $user->save($fields);
  519. Db::commit();
  520. } catch (PDOException $e) {
  521. Db::rollback();
  522. $auth->logout();
  523. return false;
  524. }
  525. // 写入登录Cookies和Token
  526. $res = $auth->direct($user->id);
  527. $is_register = 1;
  528. }
  529. $userInfo = $auth->getUserinfo();
  530. $userInfo["is_register"] = $is_register;
  531. if ($res) {
  532. $this->success("登录成功!", $userInfo);
  533. } else {
  534. $this->error("登录失败!");
  535. }
  536. // 用户登录逻辑 === 结束
  537. } else {
  538. $this->error("解密失败!", ["code" => $errCode]);
  539. }
  540. }
  541. /**
  542. * json 请求
  543. * @param $url
  544. * @return mixed
  545. */
  546. private function getJson($url)
  547. {
  548. $ch = curl_init();
  549. curl_setopt($ch, CURLOPT_URL, $url);
  550. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  551. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  552. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  553. $output = curl_exec($ch);
  554. curl_close($ch);
  555. return json_decode($output, true);
  556. }
  557. /**
  558. * 运营商一键登录
  559. */
  560. public function onLogin()
  561. {
  562. $accessToken = $this->request->param('accessToken');// 运营商预取号获取到的token
  563. $token = $this->request->param('tokenT');// 易盾返回的token
  564. if (!$accessToken || !$token) {
  565. $this->error("参数获取失败!");
  566. }
  567. $params = array(
  568. // 运营商预取号获取到的token
  569. "accessToken" => $accessToken,
  570. // 易盾返回的token
  571. "token" => $token
  572. );
  573. // 获取密钥配置
  574. $configInfo = config("onLogin");
  575. $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);
  576. $ret = $onlogin->check($params);
  577. // $ret = [];
  578. // $ret["code"] = 200;
  579. // $ret["msg"] = "ok";
  580. // $ret["data"] = [
  581. // "phone" => "17574504021",
  582. // "resultCode" => 0
  583. // ];
  584. if ($ret["code"] == 200) {
  585. $data = $ret["data"];
  586. $phone = $data["phone"];
  587. if (empty($phone)) {
  588. // 取号失败,建议进行二次验证,例如短信验证码
  589. $this->error("取号登录失败,请用验证码方式登录!");
  590. } else {
  591. // 取号成功, 执行登录等流程
  592. // 用户登录逻辑 === 开始
  593. $userModel = new \app\common\model\User();
  594. $auth = \app\common\library\Auth::instance();
  595. $userInfo = $userModel->where(["mobile" => $phone])->find();
  596. // 用户信息不存在时使用
  597. $extend = ["mobile" => $phone];
  598. // 判断用户是否已经存在
  599. if ($userInfo) { // 登录
  600. $user = \app\common\model\User::get($userInfo["id"]);
  601. if (!$user) {
  602. $this->error("网络错误!请稍后重试");
  603. }
  604. if ($user->status != 'normal') {
  605. $this->error(__('Account is locked'));
  606. }
  607. $user->save(["logintime" => time()]);
  608. $res = $auth->direct($user->id);
  609. $is_register = 0;
  610. } else { // 注册
  611. // 先随机一个用户名,随后再变更为u+数字id
  612. $username = Random::alnum(20);
  613. $password = Random::alnum(6);
  614. Db::startTrans();
  615. try {
  616. // 默认注册一个会员
  617. $result = $auth->register($username, $password, "", $extend);
  618. if (!$result) {
  619. return false;
  620. }
  621. $user = $auth->getUser();
  622. $fields = ['username' => 'u' . $user->id];
  623. // 更新会员资料
  624. $user = \app\common\model\User::get($user->id);
  625. $user->save($fields);
  626. Db::commit();
  627. } catch (PDOException $e) {
  628. Db::rollback();
  629. $auth->logout();
  630. return false;
  631. }
  632. // 写入登录Cookies和Token
  633. $res = $auth->direct($user->id);
  634. $is_register = 1;
  635. }
  636. $userInfo["userinfo"] = $auth->getUserinfo();
  637. $userInfo["is_register"] = $is_register;
  638. if ($res) {
  639. $this->success("登录成功!", $userInfo);
  640. } else {
  641. $this->error("登录失败!");
  642. }
  643. // 用户登录逻辑 === 结束
  644. }
  645. } else {
  646. $this->error("登录失败,请用验证码方式登录!");
  647. }
  648. }
  649. /**
  650. * 注销账号
  651. *
  652. * @param string $mobile 手机号
  653. * @param string $captcha 验证码
  654. */
  655. public function cancleUser()
  656. {
  657. $user = $this->auth->getUser();
  658. $user->status = -1;
  659. //unset($user->power);
  660. $user->save();
  661. $this->auth->logout();
  662. $this->success("账号注销成功!");
  663. }
  664. /**
  665. * 获取昵称
  666. * @return string
  667. */
  668. public function getNickName()
  669. {
  670. $result['nickname'] = get_rand_nick_name();
  671. $this->success('获取成功',$result);
  672. }
  673. //微信登录,预先假注册
  674. public function wechatlogin(){
  675. $code = $this->request->param('code','');
  676. if(!$code){
  677. $this->error(__('Invalid parameters'));
  678. }
  679. //微信
  680. $wechat = new Wechat();
  681. $wxuserinfo = $wechat->getwxuserinfo($code);
  682. Log::error('code:'.$code.',wxuserinfo:'.json_encode($wxuserinfo));
  683. if(!$wxuserinfo){
  684. $this->error('openid获取失败');
  685. }
  686. $openid = $wxuserinfo['openid'];
  687. $user = Db::name('user')->where('openid',$openid)->find();
  688. if ($user) {
  689. if ($user['status'] == -1) {
  690. $this->error('账户已注销');
  691. }
  692. if ($user['status'] != 1) {
  693. $this->error(__('Account is locked'));
  694. }
  695. //如果已经有账号则直接登录
  696. $ret = $this->auth->direct($user['id']);
  697. $is_register = 0;
  698. $userInfo = $this->auth->getUserinfo();
  699. } else {
  700. //记录code和openid,绑定手机号的时候更新openid
  701. $wechatCodeData = [
  702. 'code' => $code,
  703. 'openid' => $openid,
  704. 'createtime' => time(),
  705. ];
  706. $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
  707. if (empty($wechatCode)) {
  708. Db::name('wechat_code')->insertGetId($wechatCodeData);
  709. } else {
  710. Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
  711. }
  712. $ret = true;
  713. $is_register = 1;
  714. $userInfo = [];
  715. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  716. $this->success('获取信息成功', $data, 2);
  717. }
  718. if ($ret) {
  719. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  720. $this->success(__('Logged in successful'), $data);
  721. } else {
  722. $this->error($this->auth->getError());
  723. }
  724. }
  725. //获取openid
  726. public function getopenid() {
  727. //code
  728. $code = $this->request->post('code', '', 'trim');// code值
  729. if (!$code) {
  730. $this->error(__('Invalid parameters'));
  731. }
  732. $config = config('wxMiniProgram');
  733. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  734. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  735. $openidInfo = json_decode($openidInfo,true);
  736. if(!isset($openidInfo['openid'])) {
  737. $this->error('用户openid获取失败', $openidInfo);
  738. }
  739. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  740. //$openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  741. $this->success('获取成功', $openidInfo);
  742. }
  743. //生成海报
  744. public function createposter() {
  745. // $image = input('image', '', 'trim');
  746. // if (!$image) {
  747. // $this->error('您的网络开小差啦~');
  748. // }
  749. $image = config('site.intro_imges');
  750. $haibao = $this->haibao($this->auth->id,['invite_no'=>$this->auth->invite_no, 'background' => $image]);
  751. return $haibao;
  752. // $this->success('success', $haibao);
  753. }
  754. //海报
  755. public function haibao($player_id,$data){
  756. //下载页二维码,没必要保留
  757. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  758. $params = [
  759. 'text' => $httpStr.'/index/index/download?code=' . $data['invite_no'],
  760. 'size' => 90,
  761. 'logo' => false,
  762. 'label' => false,
  763. 'padding' => 0,
  764. ];
  765. $qrCode = \addons\qrcode\library\Service::qrcode($params);
  766. $qrcode_path = 'uploads/hbplayer/'.date('Ymd');
  767. mk_dir($qrcode_path);
  768. $download_qrcode = $qrcode_path.'/download'.$player_id.'.png';
  769. $qrCode->writeFile($download_qrcode);
  770. //海报
  771. $result['url'] = $this->createhaibao($download_qrcode,$player_id,$data);
  772. $this->success('获取成功',$result);
  773. }
  774. public function createhaibao($download_qrcode,$player_id,$sub_data){
  775. //二维码
  776. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  777. $download_qrcode= $httpStr.'/'.$download_qrcode;
  778. $data = [
  779. /*[
  780. "left" => "15px",
  781. "top" => "400px",
  782. "type" => "img",
  783. "width" => "58px",
  784. "height" => "58px",
  785. "src" => one_domain_image($this->auth->avatar),
  786. ],
  787. [
  788. "left" => "81px",
  789. "top" => "400px",
  790. "type" => "nickname",
  791. "width" => "80px",
  792. "height" => "24px",
  793. "size" => "12px",
  794. "color" => "#000",
  795. "content" => $this->auth->nickname
  796. ],
  797. [
  798. "left" => "81px",
  799. "top" => "400px",
  800. "type" => "nickname",
  801. "width" => "80px",
  802. "height" => "24px",
  803. "size" => "12px",
  804. "color" => "#000",
  805. "content" => $this->auth->invite_no
  806. ],*/
  807. [
  808. "left" => "18px",
  809. "top" => "410px",
  810. "type" => "text",
  811. "width" => "80px",
  812. "height" => "24px",
  813. "size" => "16px",
  814. "color" => "#123354",
  815. "content" => 'GG语音'
  816. ],
  817. [
  818. "left" => "18px",
  819. "top" => "445px",
  820. "type" => "text",
  821. "width" => "80px",
  822. "height" => "24px",
  823. "size" => "10px",
  824. "color" => "#123354",
  825. "content" => '更多现金奖励等你来拿'
  826. ],
  827. [
  828. "left" => "210px",
  829. "top" => "385px",
  830. "type" => "img",
  831. "width" => "95px",
  832. "height" => "95px",
  833. "src" => $download_qrcode//"https://metavision.oss-cn-hongkong.aliyuncs.com/uploads/20220615/f00cb545deb4c4e7296f444239d83e84.jpg"
  834. ]
  835. ];
  836. $data = json_encode($data, 320);
  837. $poster = [
  838. 'id' => $player_id,
  839. 'title' => 'GG语音',
  840. 'waittext' => '您的专属海报正在拼命生成中,请等待片刻...',
  841. 'bg_image' => $sub_data['background'] ? cdnurl($sub_data['background']) : '/assets/img/inviteposter.png',
  842. 'data' => $data,
  843. 'status' => 'normal',
  844. 'weigh' => 0,
  845. 'createtime' => 1653993709,
  846. 'updatetime' => 1653994259,
  847. ];
  848. $image = new \addons\poster\library\Image();
  849. $imgurl = $image->createPosterImage($poster, $this->auth->getUser());
  850. if (!$imgurl) {
  851. $this->error('生成海报出错');
  852. }
  853. // $imgurl = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"] . '/' . $imgurl;
  854. return $httpStr.'/' . $imgurl;
  855. }
  856. //申请真人认证
  857. public function realauth()
  858. {
  859. try {
  860. $realName = $this->request->param('real_name','');
  861. $idCard = $this->request->param('id_card','');
  862. if ($this->auth->is_auth == 2) {
  863. $this->error('您已经真人认证过了~');
  864. }
  865. if (empty($realName)) {
  866. throw new Exception('请输入姓名');
  867. }
  868. if (empty($idCard)) {
  869. throw new Exception('请输入身份证号');
  870. }
  871. $userAuthWhere['user_id'] = ['neq',$this->auth->id];
  872. $userAuthWhere['idcard'] = $idCard;
  873. // 获取用户已经实名认证的数量
  874. $authenticatedCount = model('UserAuth')->where(['idcard' => $idCard])->count();
  875. // 如果已经实名认证的数量不超过3个
  876. if ($authenticatedCount > 3) {
  877. throw new Exception('您当前身份证号已经认证过3次');
  878. }
  879. /*$userAuth = model('UserAuth')->where($userAuthWhere)->find();
  880. if (!empty($userAuth)) {
  881. throw new Exception('该身份证号已被其他用户实名验证过');
  882. }*/
  883. /*$userService = new UserService();
  884. $faceParams = [
  885. 'real_name' => $realName,
  886. 'id_card' => $idCard,
  887. 'user_id' => $this->auth->id,
  888. ];
  889. $res = $userService->faceAuth($faceParams);
  890. if (!$res['status']) {
  891. $this->error('您的网络开小差啦5~');
  892. }
  893. $rs = $res['data'];
  894. if (!$rs || $rs['code'] != 0) {
  895. $this->error('您的网络开小差啦6~');
  896. }
  897. $user_auth = [
  898. 'user_id' => $this->auth->id,
  899. 'realname' => $realName,
  900. 'idcard' => $idCard,
  901. 'certify_id' => isset($rs['result']['faceId']) ? $rs['result']['faceId'] : '',
  902. 'out_trade_no' => isset($rs['result']['orderNo']) ? $rs['result']['orderNo'] : '',
  903. 'status' => 0,
  904. 'createtime' => time(),
  905. 'updatetime' => time()
  906. ];*/
  907. $userService = new UserService();
  908. $aliParams = [
  909. 'id_card' => $idCard,
  910. 'real_name' => $realName,
  911. ];
  912. $aliCheckRes = $userService->aliCheck($aliParams);
  913. if (!$aliCheckRes['status']) {
  914. throw new Exception($aliCheckRes['msg']);
  915. }
  916. $user_auth = [
  917. 'user_id' => $this->auth->id,
  918. 'realname' => $realName,
  919. 'idcard' => $idCard,
  920. 'certify_id' => '',
  921. 'out_trade_no' => '',
  922. 'status' => 1,
  923. 'createtime' => time(),
  924. ];
  925. //开启事务
  926. Db::startTrans();
  927. //查询是否认证过
  928. $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  929. if ($info) {
  930. $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
  931. } else {
  932. $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
  933. }
  934. if (!$auth_rs) {
  935. Db::rollback();
  936. $this->error('您的网络开小差啦7~');
  937. }
  938. //修改用户表认证状态
  939. $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', 2);
  940. if ($user_rs === false) {
  941. Db::rollback();
  942. $this->error('您的网络开小差啦8~');
  943. }
  944. Db::commit();
  945. /*$return_data = [
  946. 'face_id' => $user_auth['certify_id'],
  947. 'order_no' => $user_auth['out_trade_no'],
  948. 'user_id' => (string)$this->auth->id,
  949. 'nonce' => $rs['nonce'],
  950. 'sign' => $rs['sign'],
  951. ];*/
  952. $this->success('验证成功');
  953. } catch (Exception $e) {
  954. $this->error($e->getMessage());
  955. }
  956. }
  957. //查询真人认证结果
  958. public function getrealauthresult() {
  959. $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  960. if (!$user_auth) {
  961. $this->success('尚未认证');
  962. }
  963. if ($user_auth['status'] == 1) {
  964. $this->success('真人认证通过');
  965. }
  966. if (!$user_auth['certify_id']) {
  967. $this->success('请先进行真人认证');
  968. }
  969. $tencentConfig = config('tencent_yun');
  970. $sercrtId = isset($tencentConfig['SecretId']) ? $tencentConfig['SecretId'] : '';
  971. $sercrtKey = isset($tencentConfig['SecretKey']) ? $tencentConfig['SecretKey'] : '';
  972. //获取token
  973. $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.$sercrtId.'&secret='.$sercrtKey.'&grant_type=client_credential&version=1.0.0';
  974. $token_result = file_get_contents($token_url);
  975. if (!$token_result) {
  976. $this->error('您的网络开小差啦1~');
  977. }
  978. $token_result = json_decode($token_result, true);
  979. if ($token_result['code'] != 0) {
  980. $this->error('您的网络开小差啦2~');
  981. }
  982. $token = $token_result['access_token'];
  983. //获取签名鉴权参数ticket
  984. $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.$sercrtId.'&access_token='.$token.'&type=SIGN&version=1.0.0';
  985. $ticket_result = file_get_contents($ticket_url);
  986. if (!$ticket_result) {
  987. $this->error('您的网络开小差啦3~');
  988. }
  989. $ticket_result = json_decode($ticket_result, true);
  990. if ($ticket_result['code'] != 0) {
  991. $this->error('您的网络开小差啦4~');
  992. }
  993. $ticket = $ticket_result['tickets'][0]['value'];
  994. //获取签名
  995. $sign_data = [
  996. 'wbappid' => $sercrtId,
  997. 'orderNo' => $user_auth['out_trade_no'],
  998. 'version' => '1.0.0',
  999. 'ticket' => $ticket,
  1000. 'nonce' => Random::alnum(32)
  1001. ];//p($sign_data);
  1002. asort($sign_data); //p($sign_data);//排序
  1003. $sign_string = join('', $sign_data);//p($sign_string);
  1004. $sign = sha1($sign_string);//p($sign);
  1005. //人脸核身结果查询
  1006. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
  1007. $data = [
  1008. 'appId' => $sercrtId,
  1009. 'version' => '1.0.0',
  1010. 'nonce' => $sign_data['nonce'],
  1011. 'orderNo' => $user_auth['out_trade_no'],
  1012. 'sign' => $sign
  1013. ];
  1014. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  1015. if (!$rs) {
  1016. $this->error('您的网络开小差啦5~');
  1017. }
  1018. $rs = json_decode($rs, true);
  1019. if (!$rs || $rs['code'] != 0) {
  1020. $this->error($rs['msg']);
  1021. }
  1022. if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
  1023. $edit_data['status'] = 2;
  1024. $msg = '真人认证成功';
  1025. } else {
  1026. $edit_data['status'] = -1;
  1027. $edit_data['certify_id'] = '';
  1028. $edit_data['out_trade_no'] = '';
  1029. $msg = '真人认证失败';
  1030. }
  1031. $edit_data['updatetime'] = time();
  1032. //开启事务
  1033. Db::startTrans();
  1034. //修改认证信息
  1035. $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
  1036. if (!$result) {
  1037. Db::rollback();
  1038. $this->error('查询认证结果失败2');
  1039. }
  1040. //修改用户信息
  1041. $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', $edit_data['status']);
  1042. if (!$rs) {
  1043. Db::rollback();
  1044. $this->error('查询认证结果失败3');
  1045. }
  1046. if ($edit_data['status'] == 2) { //通过
  1047. //tag任务赠送金币
  1048. //真人认证奖励
  1049. /*$task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,20);
  1050. if($task_rs === false){
  1051. Db::rollback();
  1052. $this->error('完成任务赠送奖励失败');
  1053. }*/
  1054. //系统消息
  1055. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
  1056. } else {
  1057. //系统消息
  1058. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
  1059. }
  1060. Db::commit();
  1061. $this->success($msg);
  1062. }
  1063. /**
  1064. * 微信注册来的,绑定手机号
  1065. *
  1066. * @ApiMethod (POST)
  1067. * @param string $mobile 手机号
  1068. * @param string $captcha 验证码
  1069. */
  1070. public function bindmobile()
  1071. {
  1072. Db::startTrans();
  1073. try {
  1074. $code = $this->request->param('code');
  1075. $mobile = $this->request->param('mobile');
  1076. $captcha = $this->request->param('captcha');
  1077. if (!$mobile || !$captcha || !$code) {
  1078. throw new Exception(__('Invalid parameters'));
  1079. }
  1080. if (!Validate::regex($mobile, "^1\d{10}$")) {
  1081. throw new Exception(__('Mobile is incorrect'));
  1082. }
  1083. $result = Sms::check($mobile, $captcha, 'changemobile');
  1084. if (!$result) {
  1085. throw new Exception(__('Captcha is incorrect'));
  1086. }
  1087. $where['mobile'] = $mobile;
  1088. $userData = model('User')->where($where)->find();//老用户
  1089. $wechatCodeWhere['code'] = $code;
  1090. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  1091. if (empty($wechatCode)) {
  1092. throw new Exception('请先微信登录');
  1093. }
  1094. if (!empty($userData)) {
  1095. if (empty($userData['openid'])) {
  1096. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  1097. } else {
  1098. if ($userData['openid'] != $wechatCode['openid']) {
  1099. throw new Exception('该手机号已被其他用户绑定');
  1100. }
  1101. }
  1102. $ret = $this->auth->direct($userData['id']);
  1103. } else {
  1104. $extend = [
  1105. 'openid' => $wechatCode['openid'],
  1106. ];
  1107. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  1108. }
  1109. if (!$ret) {
  1110. throw new Exception($this->auth->getError());
  1111. }
  1112. Sms::flush($mobile, 'changemobile');
  1113. Db::commit();
  1114. $this->success('success',$this->userInfo('return'));
  1115. } catch (Exception $e) {
  1116. Db::rollback();
  1117. $this->error($e->getMessage());
  1118. }
  1119. }
  1120. /**
  1121. * 手机注册来的,绑定微信
  1122. *
  1123. * @ApiMethod (POST)
  1124. * @param string $wechat_openid
  1125. */
  1126. public function bindopenid()
  1127. {
  1128. Db::startTrans();
  1129. try {
  1130. $code = $this->request->param('code','');
  1131. if(!$code){
  1132. throw new Exception(__('Invalid parameters'));
  1133. }
  1134. //微信
  1135. $wechat = new Wechat();
  1136. $openid = $wechat->getOpenid($code);
  1137. if(!$openid){
  1138. throw new Exception('openid获取失败');
  1139. }
  1140. $user = model('User')->find($this->auth->id);
  1141. if(!empty($user['openid']) && $openid != $user['openid']){
  1142. throw new Exception('已经绑定了微信号');
  1143. }
  1144. $otherUserWhere['openid'] = $openid;
  1145. $otherUserWhere['id'] = ['neq',$this->auth->id];
  1146. $otherUser = model('User')->where($otherUserWhere)->find();
  1147. if (!empty($otherUser)) {
  1148. throw new Exception('该微信已被其他用户绑定过');
  1149. }
  1150. $user->openid = $openid;
  1151. $userRes = $user->save();
  1152. if (!$userRes) {
  1153. throw new Exception('绑定微信失败');
  1154. }
  1155. Db::commit();
  1156. $this->success('success',$this->userInfo('return'));
  1157. } catch (Exception $e) {
  1158. Db::rollback();
  1159. $this->error($e->getMessage());
  1160. }
  1161. }
  1162. //用户详细资料
  1163. public function userInfo($type = 1){
  1164. $info = $this->auth->getUserinfo();
  1165. if($type == 'return'){
  1166. return $info;
  1167. }
  1168. $this->success(__('success'),$info);
  1169. }
  1170. /**
  1171. * 微信解绑
  1172. * @return void
  1173. */
  1174. public function clearopenid()
  1175. {
  1176. try {
  1177. $userId = $this->auth->id;
  1178. $where['id'] = $userId;
  1179. $data['openid'] = '';
  1180. $user = model('User')->update($data,$where);
  1181. $this->success('解绑成功');
  1182. } catch (Exception $e) {
  1183. $this->error($e->getMessage());
  1184. }
  1185. }
  1186. }