User.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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') && $captcha != '1212') {
  71. $this->error(__('Captcha is incorrect'));
  72. }
  73. $user = \app\common\model\User::getByMobile($mobile);
  74. if ($user) {
  75. if ($user->status != 'normal') {
  76. $this->error(__('Account is locked'));
  77. }
  78. //如果已经有账号则直接登录
  79. $is_register = 0;
  80. $ret = $this->auth->direct($user->id);
  81. } else {
  82. $is_register = 1;
  83. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, []);
  84. }
  85. if ($ret) {
  86. Sms::flush($mobile, 'mobilelogin');
  87. $data = ['is_register' => $is_register, 'userinfo' => $this->auth->getUserinfo()];
  88. $this->success(__('Logged in successful'), $data);
  89. } else {
  90. $this->error($this->auth->getError());
  91. }
  92. }
  93. /**
  94. * 绑定用户
  95. */
  96. public function bindUser()
  97. {
  98. $invite_no = $this->request->request('invite_no'); // 邀请码
  99. if (!$invite_no) {
  100. $this->error("请输入邀请码!");
  101. }
  102. $user_id = $this->auth->id;
  103. // 查询邀请码用户信息
  104. $inviteUserInfo = \app\common\model\User::where(["invite_no" => $invite_no])->find();
  105. if (!$inviteUserInfo) $this->error("查询不到该邀请码用户信息!");
  106. if ($inviteUserInfo->id == $user_id) $this->error("不能邀请自己哦!");
  107. if ($inviteUserInfo->is_auth != 2) $this->error("该邀请码用户尚未完成实名认证");
  108. $res = \app\common\model\User::update(["pre_userid" => $inviteUserInfo->id,"bindtime" => time()], ["id" => $user_id]);
  109. if ($res) {
  110. $this->success("恭喜,绑定成功!");
  111. } else {
  112. $this->success("网络繁忙,请稍后重试!");
  113. }
  114. }
  115. /**
  116. * 注册会员
  117. *
  118. * @param string $username 用户名
  119. * @param string $password 密码
  120. * @param string $email 邮箱
  121. * @param string $mobile 手机号
  122. * @param string $code 验证码
  123. */
  124. public function register()
  125. {
  126. $username = $this->request->request('username');
  127. $password = $this->request->request('password');
  128. $mobile = $this->request->request('mobile');
  129. $code = $this->request->request('code');
  130. if (!$username || !$password) {
  131. $this->error(__('Invalid parameters'));
  132. }
  133. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  134. $this->error(__('Mobile is incorrect'));
  135. }
  136. // $ret = Sms::check($mobile, $code, 'register');
  137. // if (!$ret) {
  138. // $this->error(__('Captcha is incorrect'));
  139. // }
  140. $ret = $this->auth->register($username, $password, $mobile, []);
  141. if ($ret) {
  142. $data = ['userinfo' => $this->auth->getUserinfo()];
  143. $this->success(__('Sign up successful'), $data);
  144. } else {
  145. $this->error($this->auth->getError());
  146. }
  147. }
  148. /**
  149. * 退出登录
  150. */
  151. public function logout()
  152. {
  153. $this->auth->logout();
  154. $this->success(__('Logout successful'));
  155. }
  156. /**
  157. * 修改会员个人信息
  158. *
  159. * @param string $avatar 头像地址
  160. * @param string $username 用户名
  161. * @param string $nickname 昵称
  162. * @param string $bio 个人简介
  163. */
  164. public function profile()
  165. {
  166. $user = $this->auth->getUser();
  167. $username = $this->request->request('username');
  168. $nickname = $this->request->request('nickname');
  169. $bio = $this->request->request('bio');
  170. $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
  171. if ($username) {
  172. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  173. if ($exists) {
  174. $this->error(__('Username already exists'));
  175. }
  176. $user->username = $username;
  177. }
  178. if ($nickname) {
  179. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  180. if ($exists) {
  181. $this->error(__('Nickname already exists'));
  182. }
  183. $user->nickname = $nickname;
  184. }
  185. $user->bio = $bio;
  186. $user->avatar = $avatar;
  187. $user->save();
  188. $this->success();
  189. }
  190. /**
  191. * 修改手机号
  192. *
  193. * @param string $mobile 手机号
  194. * @param string $captcha 验证码
  195. */
  196. public function changemobile()
  197. {
  198. $user = $this->auth->getUser();
  199. $mobile = $this->request->request('mobile');
  200. $captcha = $this->request->request('captcha');
  201. if (!$mobile || !$captcha) {
  202. $this->error(__('Invalid parameters'));
  203. }
  204. if (!Validate::regex($mobile, "^1\d{10}$")) {
  205. $this->error(__('Mobile is incorrect'));
  206. }
  207. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  208. $this->error(__('Mobile already exists'));
  209. }
  210. $result = Sms::check($mobile, $captcha, 'changeMobile');
  211. if (!$result) {
  212. $this->error(__('Captcha is incorrect'));
  213. }
  214. $verification = $user->verification;
  215. $verification->mobile = 1;
  216. $user->verification = $verification;
  217. $user->mobile = $mobile;
  218. $user->save();
  219. Sms::flush($mobile, 'changeMobile');
  220. $this->success("手机号更换成功!");
  221. }
  222. /**
  223. * 第三方登录
  224. *
  225. * @param string $platform 平台名称
  226. * @param string $code Code码
  227. */
  228. public function third()
  229. {
  230. $url = url('user/index');
  231. $platform = $this->request->request("platform");
  232. $code = $this->request->request("code");
  233. $config = get_addon_config('third');
  234. if (!$config || !isset($config[$platform])) {
  235. $this->error(__('Invalid parameters'));
  236. }
  237. $app = new \addons\third\library\Application($config);
  238. //通过code换access_token和绑定会员
  239. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  240. if ($result) {
  241. $loginret = \addons\third\library\Service::connect($platform, $result);
  242. if ($loginret) {
  243. $data = [
  244. 'userinfo' => $this->auth->getUserinfo(),
  245. 'thirdinfo' => $result
  246. ];
  247. $this->success(__('Logged in successful'), $data);
  248. }
  249. }
  250. $this->error(__('Operation failed'), $url);
  251. }
  252. /**
  253. * 重置密码
  254. *
  255. * @param string $mobile 手机号
  256. * @param string $newpassword 新密码
  257. * @param string $captcha 验证码
  258. */
  259. public function resetpwd()
  260. {
  261. $type = $this->request->request("type");
  262. $mobile = $this->request->request("mobile");
  263. $email = $this->request->request("email");
  264. $newpassword = $this->request->request("newpassword");
  265. $captcha = $this->request->request("captcha");
  266. if (!$newpassword || !$captcha) {
  267. $this->error(__('Invalid parameters'));
  268. }
  269. if ($type == 'mobile') {
  270. if (!Validate::regex($mobile, "^1\d{10}$")) {
  271. $this->error(__('Mobile is incorrect'));
  272. }
  273. $user = \app\common\model\User::getByMobile($mobile);
  274. if (!$user) {
  275. $this->error(__('User not found'));
  276. }
  277. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  278. if (!$ret) {
  279. $this->error(__('Captcha is incorrect'));
  280. }
  281. Sms::flush($mobile, 'resetpwd');
  282. } else {
  283. if (!Validate::is($email, "email")) {
  284. $this->error(__('Email is incorrect'));
  285. }
  286. $user = \app\common\model\User::getByEmail($email);
  287. if (!$user) {
  288. $this->error(__('User not found'));
  289. }
  290. $ret = Ems::check($email, $captcha, 'resetpwd');
  291. if (!$ret) {
  292. $this->error(__('Captcha is incorrect'));
  293. }
  294. Ems::flush($email, 'resetpwd');
  295. }
  296. //模拟一次登录
  297. $this->auth->direct($user->id);
  298. $ret = $this->auth->changepwd($newpassword, '', true);
  299. if ($ret) {
  300. $this->success(__('Reset password successful'));
  301. } else {
  302. $this->error($this->auth->getError());
  303. }
  304. }
  305. /**
  306. * 设置密码
  307. * @param string $newpassword 新密码
  308. * @param string $newpassword 新密码
  309. */
  310. public function setpwd()
  311. {
  312. $params = $this->request->param();
  313. $validate = new \app\api\validate\User();
  314. $result = $validate->scene('setPwd')->check($params);
  315. if (!$result) {
  316. $this->error($validate->getError());
  317. }
  318. $ret = $this->auth->changepwd($params['password'], '', true);
  319. if ($ret) {
  320. $this->success(__('Set password successful'));
  321. } else {
  322. $this->error($this->auth->getError());
  323. }
  324. }
  325. /**
  326. * 修改密码
  327. *
  328. * @param string $mobile 手机号
  329. * @param string $newpassword 新密码
  330. * @param string $captcha 验证码
  331. */
  332. public function changepwd()
  333. {
  334. $params = $this->request->param();
  335. $validate = new \app\api\validate\User();
  336. $result = $validate->scene('changePwd')->check($params);
  337. if (!$result) {
  338. $this->error($validate->getError());
  339. }
  340. $mobile = $this->request->request("mobile");
  341. $newpassword = $this->request->request("password");
  342. $captcha = $this->request->request("captcha");
  343. $user = \app\common\model\User::getByMobile($mobile);
  344. if (!$user) {
  345. $this->error(__('User not found'));
  346. }
  347. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  348. if (!$ret) {
  349. $this->error(__('Captcha is incorrect'));
  350. }
  351. Sms::flush($mobile, 'resetpwd');
  352. $ret = $this->auth->changepwd($newpassword, '', true);
  353. if ($ret) {
  354. $this->success(__('Change password successful'));
  355. } else {
  356. $this->error($this->auth->getError());
  357. }
  358. }
  359. /**
  360. * 获取用户openid
  361. */
  362. public function getUserOpenid()
  363. {
  364. $code = $this->request->param('code');// code值
  365. if (!$code) {
  366. $this->error(__('Invalid parameters'));
  367. }
  368. $config = config("wxMiniProgram");
  369. $getopenid = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $config["appid"] . "&secret=" . $config["secret"] . "&js_code=" . $code . "&grant_type=authorization_code";
  370. $openidInfo = $this->getJson($getopenid);
  371. if (!isset($openidInfo["openid"])) {
  372. $this->error("用户openid获取失败", $openidInfo);
  373. }
  374. // 获取的结果存入数据库
  375. $sessionkeyModel = new \app\common\model\UserSessionkey();
  376. if ($sessionkeyModel->where(["openid" => $openidInfo["openid"]])->find()) {
  377. $update = [];
  378. $update["sessionkey"] = $openidInfo["session_key"];
  379. $res = $sessionkeyModel->update($update, ["openid" => $openidInfo["openid"]]);
  380. } else {
  381. $insert = [];
  382. $insert["sessionkey"] = $openidInfo["session_key"];
  383. $insert["openid"] = $openidInfo["openid"];
  384. $insert["createtime"] = time();
  385. $res = $sessionkeyModel->insert($insert);
  386. }
  387. if ($res) {
  388. $this->success("获取成功!", $openidInfo);
  389. } else {
  390. $this->error("获取失败!");
  391. }
  392. }
  393. /**
  394. * 微信小程序登录
  395. */
  396. public function wxMiniProgramLogin()
  397. {
  398. $openid = $this->request->param('openid');// openid值
  399. $encryptedData = $this->request->param('encryptedData');// 加密数据
  400. $iv = $this->request->param('iv');// 加密算法
  401. $signature = $this->request->param('signature');// 签名验证
  402. $rawData = $this->request->param('rawData');// 签名验证
  403. $logintype = $this->request->param('loginType', 1);// 登录方式:1=手机号,2=微信授权openid
  404. if (!$openid || !$encryptedData || !$iv) {
  405. $this->error(__('Invalid parameters'));
  406. }
  407. $encryptedData = urldecode($encryptedData);
  408. $config = config("wxMiniProgram");
  409. // 获取openid和sessionkey
  410. $sessionkeyModel = new \app\common\model\UserSessionkey();
  411. $openidInfo = $sessionkeyModel->where(["openid" => $openid])->find();
  412. $openid = $openidInfo['openid'];
  413. $session_key = $openidInfo['sessionkey'];
  414. // // 数据签名校验
  415. // $signature2 = sha1($rawData . $session_key);
  416. // if ($signature != $signature2) {
  417. // $this->error(__('数据签名验证失败'));
  418. // }
  419. // 根据加密数据和加密算法获取用户信息
  420. $pc = new WXBizDataCrypt($config["appid"], $session_key);
  421. $data = "";
  422. $errCode = $pc->decryptData($encryptedData, $iv, $data);
  423. if ($errCode == 0) {
  424. $data = json_decode($data, true);
  425. // 用户登录逻辑 === 开始
  426. $userModel = new \app\common\model\User();
  427. $auth = \app\common\library\Auth::instance();
  428. if ($logintype == 1) { // 手机号登录
  429. $userInfo = $userModel->where(["mobile" => $data["purePhoneNumber"]])->find();
  430. // 用户信息不存在时使用
  431. $extend = ["mobile" => $data["purePhoneNumber"]];
  432. } else { // 微信授权openid登录
  433. $userInfo = $userModel->where(["openid" => $openid])->find();
  434. // 用户信息不存在时使用
  435. $extend = [
  436. 'openid' => $data['openId'],
  437. 'nickname' => $data['nickName'],
  438. 'avatar' => $data['avatarUrl'],
  439. 'gender' => $data['gender'],
  440. ];
  441. }
  442. // 判断用户是否已经存在
  443. if ($userInfo) { // 登录
  444. $user = \app\common\model\User::get($userInfo["id"]);
  445. if (!$user) {
  446. $this->error("网络错误!请稍后重试");
  447. }
  448. $user->save(["logintime" => time()]);
  449. $res = $auth->direct($user->id);
  450. $is_register = 0;
  451. } else { // 注册
  452. // 先随机一个用户名,随后再变更为u+数字id
  453. $username = Random::alnum(20);
  454. $password = Random::alnum(6);
  455. Db::startTrans();
  456. try {
  457. // 默认注册一个会员
  458. $result = $auth->register($username, $password, "", $extend);
  459. if (!$result) {
  460. return false;
  461. }
  462. $user = $auth->getUser();
  463. $fields = ['username' => 'u' . $user->id];
  464. // 更新会员资料
  465. $user = \app\common\model\User::get($user->id);
  466. $user->save($fields);
  467. Db::commit();
  468. } catch (PDOException $e) {
  469. Db::rollback();
  470. $auth->logout();
  471. return false;
  472. }
  473. // 写入登录Cookies和Token
  474. $res = $auth->direct($user->id);
  475. $is_register = 1;
  476. }
  477. $userInfo = $auth->getUserinfo();
  478. $userInfo["is_register"] = $is_register;
  479. if ($res) {
  480. $this->success("登录成功!", $userInfo);
  481. } else {
  482. $this->error("登录失败!");
  483. }
  484. // 用户登录逻辑 === 结束
  485. } else {
  486. $this->error("解密失败!", ["code" => $errCode]);
  487. }
  488. }
  489. /**
  490. * json 请求
  491. * @param $url
  492. * @return mixed
  493. */
  494. private function getJson($url)
  495. {
  496. $ch = curl_init();
  497. curl_setopt($ch, CURLOPT_URL, $url);
  498. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  499. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  500. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  501. $output = curl_exec($ch);
  502. curl_close($ch);
  503. return json_decode($output, true);
  504. }
  505. /**
  506. * 运营商一键登录
  507. */
  508. public function onLogin()
  509. {
  510. $accessToken = $this->request->param('accessToken');// 运营商预取号获取到的token
  511. $token = $this->request->param('tokenT');// 易盾返回的token
  512. if (!$accessToken || !$token) {
  513. $this->error("参数获取失败!");
  514. }
  515. $params = array(
  516. // 运营商预取号获取到的token
  517. "accessToken" => $accessToken,
  518. // 易盾返回的token
  519. "token" => $token
  520. );
  521. // 获取密钥配置
  522. $configInfo = config("onLogin");
  523. $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);
  524. $ret = $onlogin->check($params);
  525. // $ret = [];
  526. // $ret["code"] = 200;
  527. // $ret["msg"] = "ok";
  528. // $ret["data"] = [
  529. // "phone" => "17574504021",
  530. // "resultCode" => 0
  531. // ];
  532. if ($ret["code"] == 200) {
  533. $data = $ret["data"];
  534. $phone = $data["phone"];
  535. if (empty($phone)) {
  536. // 取号失败,建议进行二次验证,例如短信验证码
  537. $this->error("取号登录失败,请用验证码方式登录!");
  538. } else {
  539. // 取号成功, 执行登录等流程
  540. // 用户登录逻辑 === 开始
  541. $userModel = new \app\common\model\User();
  542. $auth = \app\common\library\Auth::instance();
  543. $userInfo = $userModel->where(["mobile" => $phone])->find();
  544. // 用户信息不存在时使用
  545. $extend = ["mobile" => $phone];
  546. // 判断用户是否已经存在
  547. if ($userInfo) { // 登录
  548. $user = \app\common\model\User::get($userInfo["id"]);
  549. if (!$user) {
  550. $this->error("网络错误!请稍后重试");
  551. }
  552. if ($user->status != 'normal') {
  553. $this->error(__('Account is locked'));
  554. }
  555. $user->save(["logintime" => time()]);
  556. $res = $auth->direct($user->id);
  557. $is_register = 0;
  558. } else { // 注册
  559. // 先随机一个用户名,随后再变更为u+数字id
  560. $username = Random::alnum(20);
  561. $password = Random::alnum(6);
  562. Db::startTrans();
  563. try {
  564. // 默认注册一个会员
  565. $result = $auth->register($username, $password, "", $extend);
  566. if (!$result) {
  567. return false;
  568. }
  569. $user = $auth->getUser();
  570. $fields = ['username' => 'u' . $user->id];
  571. // 更新会员资料
  572. $user = \app\common\model\User::get($user->id);
  573. $user->save($fields);
  574. Db::commit();
  575. } catch (PDOException $e) {
  576. Db::rollback();
  577. $auth->logout();
  578. return false;
  579. }
  580. // 写入登录Cookies和Token
  581. $res = $auth->direct($user->id);
  582. $is_register = 1;
  583. }
  584. $userInfo["userinfo"] = $auth->getUserinfo();
  585. $userInfo["is_register"] = $is_register;
  586. if ($res) {
  587. $this->success("登录成功!", $userInfo);
  588. } else {
  589. $this->error("登录失败!");
  590. }
  591. // 用户登录逻辑 === 结束
  592. }
  593. } else {
  594. $this->error("登录失败,请用验证码方式登录!");
  595. }
  596. }
  597. /**
  598. * 注销账号
  599. *
  600. * @param string $mobile 手机号
  601. * @param string $captcha 验证码
  602. */
  603. public function cancleUser()
  604. {
  605. $user = $this->auth->getUser();
  606. $user->status = "cancel";
  607. unset($user->power);
  608. $user->save();
  609. $this->success("账号注销成功!");
  610. }
  611. /**
  612. * 用户举报
  613. *
  614. * @param string $mobile 手机号
  615. * @param string $captcha 验证码
  616. */
  617. public function report()
  618. {
  619. $type = $this->request->param('type');// 类型描述
  620. $content = $this->request->param('content');// 内容
  621. $images = $this->request->param('images');// 图片
  622. $ruser_id = $this->request->param('ruser_id');// 被举报用户ID
  623. if (!$type || !$content || !$images || !$ruser_id) {
  624. $this->error("请完成举报内容!");
  625. }
  626. $user_id = $this->auth->id;
  627. $data = [];
  628. $data["user_id"] = $user_id;
  629. $data["ruser_id"] = $ruser_id;
  630. $data["type"] = $type;
  631. $data["content"] = $content;
  632. $data["images"] = $images;
  633. $data["createtime"] = time();
  634. $res = \app\common\model\UserReport::insert($data);
  635. if ($res) {
  636. $this->success("举报内容提交成功!");
  637. } else {
  638. $this->error("网络错误,请稍后重试!");
  639. }
  640. }
  641. /**
  642. * 获取昵称
  643. * @return string
  644. */
  645. public function getNickName()
  646. {
  647. $nicheng_tou = array('快乐的', '冷静的', '醉熏的', '潇洒的', '糊涂的', '积极的', '冷酷的', '深情的', '粗暴的', '温柔的', '可爱的', '愉快的', '义气的', '认真的', '威武的', '帅气的', '传统的', '潇洒的', '漂亮的', '自然的', '专一的', '听话的', '昏睡的', '狂野的', '等待的', '搞怪的', '幽默的', '魁梧的', '活泼的', '开心的', '高兴的', '超帅的', '留胡子的', '坦率的', '直率的', '轻松的', '痴情的', '完美的', '精明的', '无聊的', '有魅力的', '丰富的', '繁荣的', '饱满的', '炙热的', '暴躁的', '碧蓝的', '俊逸的', '英勇的', '健忘的', '故意的', '无心的', '土豪的', '朴实的', '兴奋的', '幸福的', '淡定的', '不安的', '阔达的', '孤独的', '独特的', '疯狂的', '时尚的', '落后的', '风趣的', '忧伤的', '大胆的', '爱笑的', '矮小的', '健康的', '合适的', '玩命的', '沉默的', '斯文的', '香蕉', '苹果', '鲤鱼', '鳗鱼', '任性的', '细心的', '粗心的', '大意的', '甜甜的', '酷酷的', '健壮的', '英俊的', '霸气的', '阳光的', '默默的', '大力的', '孝顺的', '忧虑的', '着急的', '紧张的', '善良的', '凶狠的', '害怕的', '重要的', '危机的', '欢喜的', '欣慰的', '满意的', '跳跃的', '诚心的', '称心的', '如意的', '怡然的', '娇气的', '无奈的', '无语的', '激动的', '愤怒的', '美好的', '感动的', '激情的', '激昂的', '震动的', '虚拟的', '超级的', '寒冷的', '精明的', '明理的', '犹豫的', '忧郁的', '寂寞的', '奋斗的', '勤奋的', '现代的', '过时的', '稳重的', '热情的', '含蓄的', '开放的', '无辜的', '多情的', '纯真的', '拉长的', '热心的', '从容的', '体贴的', '风中的', '曾经的', '追寻的', '儒雅的', '优雅的', '开朗的', '外向的', '内向的', '清爽的', '文艺的', '长情的', '平常的', '单身的', '伶俐的', '高大的', '懦弱的', '柔弱的', '爱笑的', '乐观的', '耍酷的', '酷炫的', '神勇的', '年轻的', '唠叨的', '瘦瘦的', '无情的', '包容的', '顺心的', '畅快的', '舒适的', '靓丽的', '负责的', '背后的', '简单的', '谦让的', '彩色的', '缥缈的', '欢呼的', '生动的', '复杂的', '慈祥的', '仁爱的', '魔幻的', '虚幻的', '淡然的', '受伤的', '雪白的', '高高的', '糟糕的', '顺利的', '闪闪的', '羞涩的', '缓慢的', '迅速的', '优秀的', '聪明的', '含糊的', '俏皮的', '淡淡的', '坚强的', '平淡的', '欣喜的', '能干的', '灵巧的', '友好的', '机智的', '机灵的', '正直的', '谨慎的', '俭朴的', '殷勤的', '虚心的', '辛勤的', '自觉的', '无私的', '无限的', '踏实的', '老实的', '现实的', '可靠的', '务实的', '拼搏的', '个性的', '粗犷的', '活力的', '成就的', '勤劳的', '单纯的', '落寞的', '朴素的', '悲凉的', '忧心的', '洁净的', '清秀的', '自由的', '小巧的', '单薄的', '贪玩的', '刻苦的', '干净的', '壮观的', '和谐的', '文静的', '调皮的', '害羞的', '安详的', '自信的', '端庄的', '坚定的', '美满的', '舒心的', '温暖的', '专注的', '勤恳的', '美丽的', '腼腆的', '优美的', '甜美的', '甜蜜的', '整齐的', '动人的', '典雅的', '尊敬的', '舒服的', '妩媚的', '秀丽的', '喜悦的', '甜美的', '彪壮的', '强健的', '大方的', '俊秀的', '聪慧的', '迷人的', '陶醉的', '悦耳的', '动听的', '明亮的', '结实的', '魁梧的', '标致的', '清脆的', '敏感的', '光亮的', '大气的', '老迟到的', '知性的', '冷傲的', '呆萌的', '野性的', '隐形的', '笑点低的', '微笑的', '笨笨的', '难过的', '沉静的', '火星上的', '失眠的', '安静的', '纯情的', '要减肥的', '迷路的', '烂漫的', '哭泣的', '贤惠的', '苗条的', '温婉的', '发嗲的', '会撒娇的', '贪玩的', '执着的', '眯眯眼的', '花痴的', '想人陪的', '眼睛大的', '高贵的', '傲娇的', '心灵美的', '爱撒娇的', '细腻的', '天真的', '怕黑的', '感性的', '飘逸的', '怕孤独的', '忐忑的', '高挑的', '傻傻的', '冷艳的', '爱听歌的', '还单身的', '怕孤单的', '懵懂的');
  648. $nicheng_wei = array('嚓茶', '凉面', '便当', '毛豆', '花生', '可乐', '灯泡', '哈密瓜', '野狼', '背包', '眼神', '缘分', '雪碧', '人生', '牛排', '蚂蚁', '飞鸟', '灰狼', '斑马', '汉堡', '悟空', '巨人', '绿茶', '自行车', '保温杯', '大碗', '墨镜', '魔镜', '煎饼', '月饼', '月亮', '星星', '芝麻', '啤酒', '玫瑰', '大叔', '小伙', '哈密瓜,数据线', '太阳', '树叶', '芹菜', '黄蜂', '蜜粉', '蜜蜂', '信封', '西装', '外套', '裙子', '大象', '猫咪', '母鸡', '路灯', '蓝天', '白云', '星月', '彩虹', '微笑', '摩托', '板栗', '高山', '大地', '大树', '电灯胆', '砖头', '楼房', '水池', '鸡翅', '蜻蜓', '红牛', '咖啡', '机器猫', '枕头', '大船', '诺言', '钢笔', '刺猬', '天空', '飞机', '大炮', '冬天', '洋葱', '春天', '夏天', '秋天', '冬日', '航空', '毛衣', '豌豆', '黑米', '玉米', '眼睛', '老鼠', '白羊', '帅哥', '美女', '季节', '鲜花', '服饰', '裙子', '白开水', '秀发', '大山', '火车', '汽车', '歌曲', '舞蹈', '老师', '导师', '方盒', '大米', '麦片', '水杯', '水壶', '手套', '鞋子', '自行车', '鼠标', '手机', '电脑', '书本', '奇迹', '身影', '香烟', '夕阳', '台灯', '宝贝', '未来', '皮带', '钥匙', '心锁', '故事', '花瓣', '滑板', '画笔', '画板', '学姐', '店员', '电源', '饼干', '宝马', '过客', '大白', '时光', '石头', '钻石', '河马', '犀牛', '西牛', '绿草', '抽屉', '柜子', '往事', '寒风', '路人', '橘子', '耳机', '鸵鸟', '朋友', '苗条', '铅笔', '钢笔', '硬币', '热狗', '大侠', '御姐', '萝莉', '毛巾', '期待', '盼望', '白昼', '黑夜', '大门', '黑裤', '钢铁侠', '哑铃', '板凳', '枫叶', '荷花', '乌龟', '仙人掌', '衬衫', '大神', '草丛', '早晨', '心情', '茉莉', '流沙', '蜗牛', '战斗机', '冥王星', '猎豹', '棒球', '篮球', '乐曲', '电话', '网络', '世界', '中心', '鱼', '鸡', '狗', '老虎', '鸭子', '雨', '羽毛', '翅膀', '外套', '火', '丝袜', '书包', '钢笔', '冷风', '八宝粥', '烤鸡', '大雁', '音响', '招牌', '胡萝卜', '冰棍', '帽子', '菠萝', '蛋挞', '香水', '泥猴桃', '吐司', '溪流', '黄豆', '樱桃', '小鸽子', '小蝴蝶', '爆米花', '花卷', '小鸭子', '小海豚', '日记本', '小熊猫', '小懒猪', '小懒虫', '荔枝', '镜子', '曲奇', '金针菇', '小松鼠', '小虾米', '酒窝', '紫菜', '金鱼', '柚子', '果汁', '百褶裙', '项链', '帆布鞋', '火龙果', '奇异果', '煎蛋', '唇彩', '小土豆', '高跟鞋', '戒指', '雪糕', '睫毛', '铃铛', '手链', '香氛', '红酒', '月光', '酸奶', '银耳汤', '咖啡豆', '小蜜蜂', '小蚂蚁', '蜡烛', '棉花糖', '向日葵', '水蜜桃', '小蝴蝶', '小刺猬', '小丸子', '指甲油', '康乃馨', '糖豆', '薯片', '口红', '超短裙', '乌冬面', '冰淇淋', '棒棒糖', '长颈鹿', '豆芽', '发箍', '发卡', '发夹', '发带', '铃铛', '小馒头', '小笼包', '小甜瓜', '冬瓜', '香菇', '小兔子', '含羞草', '短靴', '睫毛膏', '小蘑菇', '跳跳糖', '小白菜', '草莓', '柠檬', '月饼', '百合', '纸鹤', '小天鹅', '云朵', '芒果', '面包', '海燕', '小猫咪', '龙猫', '唇膏', '鞋垫', '羊', '黑猫', '白猫', '万宝路', '金毛', '山水', '音响');
  649. $nicheng = $nicheng_tou[array_rand($nicheng_tou, 1)] . $nicheng_wei[array_rand($nicheng_wei, 1)] . rand(0,99);
  650. $result['nickname'] = $nicheng; //输出生成的昵称
  651. $this->success('获取成功',$result);
  652. }
  653. //微信登录
  654. public function wechatlogin(){
  655. $code = $this->request->param('code','');
  656. if(!$code){
  657. $this->error(__('Invalid parameters'));
  658. }
  659. //微信
  660. $wechat = new Wechat();
  661. $wxuserinfo = $wechat->getwxuserinfo($code);
  662. Log::error('code:'.$code.',wxuserinfo:'.json_encode($wxuserinfo));
  663. if(!$wxuserinfo){
  664. $this->error('openid获取失败');
  665. }
  666. $openid = $wxuserinfo['openid'];
  667. $user = Db::name('user')->where('openid',$openid)->find();
  668. if ($user) {
  669. if ($user['status'] != 'normal') {
  670. $this->error(__('Account is locked'));
  671. }
  672. //如果已经有账号则直接登录
  673. $ret = $this->auth->direct($user['id']);
  674. $is_register = 0;
  675. $userInfo = $this->auth->getUserinfo();
  676. } else {
  677. //记录code和openid,绑定手机号的时候更新openid
  678. $wechatCodeData = [
  679. 'code' => $code,
  680. 'openid' => $openid,
  681. 'createtime' => time(),
  682. ];
  683. $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
  684. if (empty($wechatCode)) {
  685. Db::name('wechat_code')->insertGetId($wechatCodeData);
  686. } else {
  687. Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
  688. }
  689. $ret = true;
  690. $is_register = 1;
  691. $userInfo = [];
  692. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  693. $this->success('获取信息成功', $data, 2);
  694. }
  695. if ($ret) {
  696. $data = ['code'=>$code,'is_register' => $is_register, 'userinfo' => $userInfo];
  697. $this->success(__('Logged in successful'), $data);
  698. } else {
  699. $this->error($this->auth->getError());
  700. }
  701. }
  702. //获取openid
  703. public function getopenid() {
  704. //code
  705. $code = $this->request->post('code', '', 'trim');// code值
  706. if (!$code) {
  707. $this->error(__('Invalid parameters'));
  708. }
  709. $config = config('wxMiniProgram');
  710. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  711. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  712. $openidInfo = json_decode($openidInfo,true);
  713. if(!isset($openidInfo['openid'])) {
  714. $this->error('用户openid获取失败', $openidInfo);
  715. }
  716. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  717. //$openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  718. $this->success('获取成功', $openidInfo);
  719. }
  720. //生成海报
  721. public function createposter() {
  722. // $image = input('image', '', 'trim');
  723. // if (!$image) {
  724. // $this->error('您的网络开小差啦~');
  725. // }
  726. $image = config('site.intro_imges');
  727. $haibao = $this->haibao($this->auth->id,['invite_no'=>$this->auth->invite_no, 'background' => $image]);
  728. return $haibao;
  729. // $this->success('success', $haibao);
  730. }
  731. //海报
  732. public function haibao($player_id,$data){
  733. //下载页二维码,没必要保留
  734. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  735. $params = [
  736. 'text' => $httpStr.'/index/index/download?code=' . $data['invite_no'],
  737. 'size' => 90,
  738. 'logo' => false,
  739. 'label' => false,
  740. 'padding' => 0,
  741. ];
  742. $qrCode = \addons\qrcode\library\Service::qrcode($params);
  743. $qrcode_path = 'uploads/hbplayer/'.date('Ymd');
  744. mk_dir($qrcode_path);
  745. $download_qrcode = $qrcode_path.'/download'.$player_id.'.png';
  746. $qrCode->writeFile($download_qrcode);
  747. //海报
  748. $result['url'] = $this->createhaibao($download_qrcode,$player_id,$data);
  749. $this->success('获取成功',$result);
  750. }
  751. public function createhaibao($download_qrcode,$player_id,$sub_data){
  752. //二维码
  753. $httpStr = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
  754. $download_qrcode= $httpStr.'/'.$download_qrcode;
  755. $data = [
  756. /*[
  757. "left" => "15px",
  758. "top" => "400px",
  759. "type" => "img",
  760. "width" => "58px",
  761. "height" => "58px",
  762. "src" => one_domain_image($this->auth->avatar),
  763. ],
  764. [
  765. "left" => "81px",
  766. "top" => "400px",
  767. "type" => "nickname",
  768. "width" => "80px",
  769. "height" => "24px",
  770. "size" => "12px",
  771. "color" => "#000",
  772. "content" => $this->auth->nickname
  773. ],
  774. [
  775. "left" => "81px",
  776. "top" => "400px",
  777. "type" => "nickname",
  778. "width" => "80px",
  779. "height" => "24px",
  780. "size" => "12px",
  781. "color" => "#000",
  782. "content" => $this->auth->invite_no
  783. ],*/
  784. [
  785. "left" => "18px",
  786. "top" => "410px",
  787. "type" => "text",
  788. "width" => "80px",
  789. "height" => "24px",
  790. "size" => "16px",
  791. "color" => "#123354",
  792. "content" => 'GG语音'
  793. ],
  794. [
  795. "left" => "18px",
  796. "top" => "445px",
  797. "type" => "text",
  798. "width" => "80px",
  799. "height" => "24px",
  800. "size" => "10px",
  801. "color" => "#123354",
  802. "content" => '更多现金奖励等你来拿'
  803. ],
  804. [
  805. "left" => "210px",
  806. "top" => "385px",
  807. "type" => "img",
  808. "width" => "95px",
  809. "height" => "95px",
  810. "src" => $download_qrcode//"https://metavision.oss-cn-hongkong.aliyuncs.com/uploads/20220615/f00cb545deb4c4e7296f444239d83e84.jpg"
  811. ]
  812. ];
  813. $data = json_encode($data, 320);
  814. $poster = [
  815. 'id' => $player_id,
  816. 'title' => 'GG语音',
  817. 'waittext' => '您的专属海报正在拼命生成中,请等待片刻...',
  818. 'bg_image' => $sub_data['background'] ? cdnurl($sub_data['background']) : '/assets/img/inviteposter.png',
  819. 'data' => $data,
  820. 'status' => 'normal',
  821. 'weigh' => 0,
  822. 'createtime' => 1653993709,
  823. 'updatetime' => 1653994259,
  824. ];
  825. $image = new \addons\poster\library\Image();
  826. $imgurl = $image->createPosterImage($poster, $this->auth->getUser());
  827. if (!$imgurl) {
  828. $this->error('生成海报出错');
  829. }
  830. // $imgurl = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"] . '/' . $imgurl;
  831. return $httpStr.'/' . $imgurl;
  832. }
  833. //申请真人认证
  834. public function realauth()
  835. {
  836. try {
  837. $realName = $this->request->param('real_name','');
  838. $idCard = $this->request->param('id_card','');
  839. if ($this->auth->is_auth == 2) {
  840. $this->error('您已经真人认证过了~');
  841. }
  842. if (empty($realName)) {
  843. throw new Exception('请输入姓名');
  844. }
  845. if (empty($idCard)) {
  846. throw new Exception('请输入身份证号');
  847. }
  848. $userAuthWhere['user_id'] = ['neq',$this->auth->id];
  849. $userAuthWhere['idcard'] = $idCard;
  850. // 获取用户已经实名认证的数量
  851. $authenticatedCount = model('UserAuth')->where(['idcard' => $idCard])->count();
  852. // 如果已经实名认证的数量不超过3个
  853. if ($authenticatedCount > 3) {
  854. throw new Exception('您当前身份证号已经认证过3次');
  855. }
  856. /*$userAuth = model('UserAuth')->where($userAuthWhere)->find();
  857. if (!empty($userAuth)) {
  858. throw new Exception('该身份证号已被其他用户实名验证过');
  859. }*/
  860. /*$userService = new UserService();
  861. $faceParams = [
  862. 'real_name' => $realName,
  863. 'id_card' => $idCard,
  864. 'user_id' => $this->auth->id,
  865. ];
  866. $res = $userService->faceAuth($faceParams);
  867. if (!$res['status']) {
  868. $this->error('您的网络开小差啦5~');
  869. }
  870. $rs = $res['data'];
  871. if (!$rs || $rs['code'] != 0) {
  872. $this->error('您的网络开小差啦6~');
  873. }
  874. $user_auth = [
  875. 'user_id' => $this->auth->id,
  876. 'realname' => $realName,
  877. 'idcard' => $idCard,
  878. 'certify_id' => isset($rs['result']['faceId']) ? $rs['result']['faceId'] : '',
  879. 'out_trade_no' => isset($rs['result']['orderNo']) ? $rs['result']['orderNo'] : '',
  880. 'status' => 0,
  881. 'createtime' => time(),
  882. 'updatetime' => time()
  883. ];*/
  884. $userService = new UserService();
  885. $aliParams = [
  886. 'id_card' => $idCard,
  887. 'real_name' => $realName,
  888. ];
  889. $aliCheckRes = $userService->aliCheck($aliParams);
  890. if (!$aliCheckRes['status']) {
  891. throw new Exception($aliCheckRes['msg']);
  892. }
  893. $user_auth = [
  894. 'user_id' => $this->auth->id,
  895. 'realname' => $realName,
  896. 'idcard' => $idCard,
  897. 'certify_id' => '',
  898. 'out_trade_no' => '',
  899. 'status' => 1,
  900. 'createtime' => time(),
  901. ];
  902. //开启事务
  903. Db::startTrans();
  904. //查询是否认证过
  905. $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  906. if ($info) {
  907. $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
  908. } else {
  909. $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
  910. }
  911. if (!$auth_rs) {
  912. Db::rollback();
  913. $this->error('您的网络开小差啦7~');
  914. }
  915. //修改用户表认证状态
  916. $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', 2);
  917. if ($user_rs === false) {
  918. Db::rollback();
  919. $this->error('您的网络开小差啦8~');
  920. }
  921. Db::commit();
  922. /*$return_data = [
  923. 'face_id' => $user_auth['certify_id'],
  924. 'order_no' => $user_auth['out_trade_no'],
  925. 'user_id' => (string)$this->auth->id,
  926. 'nonce' => $rs['nonce'],
  927. 'sign' => $rs['sign'],
  928. ];*/
  929. $this->success('验证成功');
  930. } catch (Exception $e) {
  931. $this->error($e->getMessage());
  932. }
  933. }
  934. //查询真人认证结果
  935. public function getrealauthresult() {
  936. $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
  937. if (!$user_auth) {
  938. $this->success('尚未认证');
  939. }
  940. if ($user_auth['status'] == 1) {
  941. $this->success('真人认证通过');
  942. }
  943. if (!$user_auth['certify_id']) {
  944. $this->success('请先进行真人认证');
  945. }
  946. $tencentConfig = config('tencent_yun');
  947. $sercrtId = isset($tencentConfig['SecretId']) ? $tencentConfig['SecretId'] : '';
  948. $sercrtKey = isset($tencentConfig['SecretKey']) ? $tencentConfig['SecretKey'] : '';
  949. //获取token
  950. $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.$sercrtId.'&secret='.$sercrtKey.'&grant_type=client_credential&version=1.0.0';
  951. $token_result = file_get_contents($token_url);
  952. if (!$token_result) {
  953. $this->error('您的网络开小差啦1~');
  954. }
  955. $token_result = json_decode($token_result, true);
  956. if ($token_result['code'] != 0) {
  957. $this->error('您的网络开小差啦2~');
  958. }
  959. $token = $token_result['access_token'];
  960. //获取签名鉴权参数ticket
  961. $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.$sercrtId.'&access_token='.$token.'&type=SIGN&version=1.0.0';
  962. $ticket_result = file_get_contents($ticket_url);
  963. if (!$ticket_result) {
  964. $this->error('您的网络开小差啦3~');
  965. }
  966. $ticket_result = json_decode($ticket_result, true);
  967. if ($ticket_result['code'] != 0) {
  968. $this->error('您的网络开小差啦4~');
  969. }
  970. $ticket = $ticket_result['tickets'][0]['value'];
  971. //获取签名
  972. $sign_data = [
  973. 'wbappid' => $sercrtId,
  974. 'orderNo' => $user_auth['out_trade_no'],
  975. 'version' => '1.0.0',
  976. 'ticket' => $ticket,
  977. 'nonce' => Random::alnum(32)
  978. ];//p($sign_data);
  979. asort($sign_data); //p($sign_data);//排序
  980. $sign_string = join('', $sign_data);//p($sign_string);
  981. $sign = sha1($sign_string);//p($sign);
  982. //人脸核身结果查询
  983. $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
  984. $data = [
  985. 'appId' => $sercrtId,
  986. 'version' => '1.0.0',
  987. 'nonce' => $sign_data['nonce'],
  988. 'orderNo' => $user_auth['out_trade_no'],
  989. 'sign' => $sign
  990. ];
  991. $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
  992. if (!$rs) {
  993. $this->error('您的网络开小差啦5~');
  994. }
  995. $rs = json_decode($rs, true);
  996. if (!$rs || $rs['code'] != 0) {
  997. $this->error($rs['msg']);
  998. }
  999. if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
  1000. $edit_data['status'] = 2;
  1001. $msg = '真人认证成功';
  1002. } else {
  1003. $edit_data['status'] = -1;
  1004. $edit_data['certify_id'] = '';
  1005. $edit_data['out_trade_no'] = '';
  1006. $msg = '真人认证失败';
  1007. }
  1008. $edit_data['updatetime'] = time();
  1009. //开启事务
  1010. Db::startTrans();
  1011. //修改认证信息
  1012. $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
  1013. if (!$result) {
  1014. Db::rollback();
  1015. $this->error('查询认证结果失败2');
  1016. }
  1017. //修改用户信息
  1018. $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('is_auth', $edit_data['status']);
  1019. if (!$rs) {
  1020. Db::rollback();
  1021. $this->error('查询认证结果失败3');
  1022. }
  1023. if ($edit_data['status'] == 2) { //通过
  1024. //tag任务赠送金币
  1025. //真人认证奖励
  1026. /*$task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,20);
  1027. if($task_rs === false){
  1028. Db::rollback();
  1029. $this->error('完成任务赠送奖励失败');
  1030. }*/
  1031. //系统消息
  1032. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
  1033. } else {
  1034. //系统消息
  1035. $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
  1036. }
  1037. Db::commit();
  1038. $this->success($msg);
  1039. }
  1040. /**
  1041. * 微信注册来的,绑定手机号
  1042. *
  1043. * @ApiMethod (POST)
  1044. * @param string $mobile 手机号
  1045. * @param string $captcha 验证码
  1046. */
  1047. public function bindmobile()
  1048. {
  1049. Db::startTrans();
  1050. try {
  1051. $code = $this->request->param('code');
  1052. $mobile = $this->request->param('mobile');
  1053. $captcha = $this->request->param('captcha');
  1054. if (!$mobile || !$captcha || !$code) {
  1055. throw new Exception(__('Invalid parameters'));
  1056. }
  1057. if (!Validate::regex($mobile, "^1\d{10}$")) {
  1058. throw new Exception(__('Mobile is incorrect'));
  1059. }
  1060. $result = Sms::check($mobile, $captcha, 'changemobile');
  1061. if (!$result) {
  1062. throw new Exception(__('Captcha is incorrect'));
  1063. }
  1064. $where['mobile'] = $mobile;
  1065. $userData = model('User')->where($where)->find();//老用户
  1066. $wechatCodeWhere['code'] = $code;
  1067. $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
  1068. if (empty($wechatCode)) {
  1069. throw new Exception('请先微信登录');
  1070. }
  1071. if (!empty($userData)) {
  1072. if (empty($userData['openid'])) {
  1073. model('User')->update(['openid' => $wechatCode['openid']],$where);//老用户更新openid
  1074. } else {
  1075. if ($userData['openid'] != $wechatCode['openid']) {
  1076. throw new Exception('该手机号已被其他用户绑定');
  1077. }
  1078. }
  1079. $ret = $this->auth->direct($userData['id']);
  1080. } else {
  1081. $extend = [
  1082. 'openid' => $wechatCode['openid'],
  1083. ];
  1084. $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
  1085. }
  1086. if (!$ret) {
  1087. throw new Exception($this->auth->getError());
  1088. }
  1089. Sms::flush($mobile, 'changemobile');
  1090. Db::commit();
  1091. $this->success('success',$this->userInfo('return'));
  1092. } catch (Exception $e) {
  1093. Db::rollback();
  1094. $this->error($e->getMessage());
  1095. }
  1096. }
  1097. /**
  1098. * 手机注册来的,绑定微信
  1099. *
  1100. * @ApiMethod (POST)
  1101. * @param string $wechat_openid
  1102. */
  1103. public function bindopenid()
  1104. {
  1105. Db::startTrans();
  1106. try {
  1107. $code = $this->request->param('code','');
  1108. if(!$code){
  1109. throw new Exception(__('Invalid parameters'));
  1110. }
  1111. //微信
  1112. $wechat = new Wechat();
  1113. $openid = $wechat->getOpenid($code);
  1114. if(!$openid){
  1115. throw new Exception('openid获取失败');
  1116. }
  1117. $user = model('User')->find($this->auth->id);
  1118. if(!empty($user['openid']) && $openid != $user['openid']){
  1119. throw new Exception('已经绑定了微信号');
  1120. }
  1121. $otherUserWhere['openid'] = $openid;
  1122. $otherUserWhere['id'] = ['neq',$this->auth->id];
  1123. $otherUser = model('User')->where($otherUserWhere)->find();
  1124. if (!empty($otherUser)) {
  1125. throw new Exception('该微信已被其他用户绑定过');
  1126. }
  1127. $user->openid = $openid;
  1128. $userRes = $user->save();
  1129. if (!$userRes) {
  1130. throw new Exception('绑定微信失败');
  1131. }
  1132. Db::commit();
  1133. $this->success('success',$this->userInfo('return'));
  1134. } catch (Exception $e) {
  1135. Db::rollback();
  1136. $this->error($e->getMessage());
  1137. }
  1138. }
  1139. //用户详细资料
  1140. public function userInfo($type = 1){
  1141. $info = $this->auth->getUserinfo();
  1142. if($type == 'return'){
  1143. return $info;
  1144. }
  1145. $this->success(__('success'),$info);
  1146. }
  1147. /**
  1148. * 微信解绑
  1149. * @return void
  1150. */
  1151. public function clearopenid()
  1152. {
  1153. try {
  1154. $userId = $this->auth->id;
  1155. $where['id'] = $userId;
  1156. $data['openid'] = '';
  1157. $user = model('User')->update($data,$where);
  1158. $this->success('解绑成功');
  1159. } catch (Exception $e) {
  1160. $this->error($e->getMessage());
  1161. }
  1162. }
  1163. }