User.php 45 KB

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