User.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 fast\Random;
  7. use think\Config;
  8. use think\Validate;
  9. use think\Db;
  10. use miniprogram\wxBizDataCrypt;
  11. use alipaysdkphpallmaster\aop\AopClient;
  12. use alipaysdkphpallmaster\aop\request\AlipaySystemOauthTokenRequest;
  13. /**
  14. * 会员接口
  15. */
  16. class User extends Api
  17. {
  18. protected $noNeedLogin = ['login','appmobilelogin', 'getAlipayUserid','AlipayMiniProgramLogin','aliminimobilelogin','mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','getAppOpenid','wxMiniProgramLogin','wxAPPLogin'];
  19. protected $noNeedRight = '*';
  20. public function _initialize()
  21. {
  22. parent::_initialize();
  23. if (!Config::get('fastadmin.usercenter')) {
  24. $this->error(__('User center already closed'));
  25. }
  26. }
  27. /**
  28. * 手机验证码登录。app端用的
  29. *
  30. * @ApiMethod (POST)
  31. * @param string $mobile 手机号
  32. * @param string $captcha 验证码
  33. */
  34. public function aliminimobilelogin(){
  35. $mobile = $this->request->post('mobile');
  36. $captcha = $this->request->post('captcha');
  37. $openid = $this->request->post('user_id');
  38. $introcode = $this->request->post('introcode','');
  39. if (!$mobile || !$captcha || !$openid) {
  40. $this->error(__('Invalid parameters'));
  41. }
  42. if (!Validate::regex($mobile, "^1\d{10}$")) {
  43. $this->error(__('Mobile is incorrect'));
  44. }
  45. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  46. $this->error(__('Captcha is incorrect'));
  47. }
  48. // 获取openid和sessionkey
  49. $openidInfo = Db::name('user_sessionkey_alipay')->where(['user_id'=>$openid])->find();
  50. if(!$openidInfo){
  51. $this->error('user_id获取失败');
  52. }
  53. //
  54. $check_user = Db::name('user')->where('ali_user_id',$openidInfo['user_id'])->where('mobile','neq',$mobile)->find();
  55. if($check_user){
  56. $this->error('已经绑定手机号'.$check_user['mobile'].',请使用该手机号登录');
  57. }
  58. //
  59. $intro_uid = 0;
  60. if(!empty($introcode)){
  61. $intro_uid = Db::name('user')->where('introcode',$introcode)->value('id');
  62. if(empty($intro_uid)){
  63. $this->error('请填写正确的邀请码或者不填');
  64. }
  65. }
  66. //登录与注册
  67. $user = \app\common\model\User::getByMobile($mobile);
  68. if ($user) {
  69. if ($user->status == 0) {
  70. $this->error(__('Account is locked'));
  71. }
  72. if ($user->status == 2) {
  73. $this->error('该用户已注销');
  74. }
  75. if (!empty($user->ali_user_id)){
  76. if($user->ali_user_id != $openidInfo['user_id']){
  77. $this->error('请使用初始注册的支付宝账号进行登录');
  78. }
  79. }
  80. //修改最新的openid。其他渠道注册,本渠道第一次来就赋值
  81. /*$user->ali_user_id = $openid;
  82. $user->save();*/
  83. //如果已经有账号则直接登录
  84. $ret = $this->auth->direct($user->id);
  85. } else {
  86. // 用户信息不存在时使用
  87. $extend = [
  88. 'ali_user_id' => $openid,
  89. 'intro_uid' => $intro_uid,
  90. ];
  91. $ret = $this->auth->register_mobile($mobile, Random::alnum(), '', $mobile, $extend);
  92. //注册赠送积分
  93. $register_gift_score = intval(config('site.register_gift_score'));
  94. if($register_gift_score > 0){
  95. $wallet = new \app\common\model\Wallet;
  96. $wallet_rs = $wallet->lockChangeAccountRemain($this->auth->id,'score',$register_gift_score,22,'注册赠送积分','user',$this->auth->id);
  97. }
  98. }
  99. if ($ret) {
  100. Sms::flush($mobile, 'mobilelogin');
  101. $data = ['userinfo' => $this->getUserinfo('return')];
  102. $this->success(__('Logged in successful'), $data);
  103. } else {
  104. $this->error($this->auth->getError());
  105. }
  106. }
  107. /**
  108. * 手机验证码登录。app端用的
  109. *
  110. * @ApiMethod (POST)
  111. * @param string $mobile 手机号
  112. * @param string $captcha 验证码
  113. */
  114. public function appmobilelogin(){
  115. $mobile = $this->request->post('mobile');
  116. $captcha = $this->request->post('captcha');
  117. $openid = $this->request->post('openid');
  118. $introcode = $this->request->post('introcode','');
  119. if (!$mobile || !$captcha || !$openid) {
  120. $this->error(__('Invalid parameters'));
  121. }
  122. if (!Validate::regex($mobile, "^1\d{10}$")) {
  123. $this->error(__('Mobile is incorrect'));
  124. }
  125. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  126. $this->error(__('Captcha is incorrect'));
  127. }
  128. // 获取openid和sessionkey
  129. $openidInfo = Db::name('user_sessionkey')->where(['app_openid'=>$openid])->find();
  130. if(!$openidInfo){
  131. $this->error('openid获取失败');
  132. }
  133. //
  134. $check_user = Db::name('user')->where('unionid',$openidInfo['unionid'])->where('mobile','neq',$mobile)->find();
  135. if($check_user){
  136. $this->error('该微信已经绑定手机号'.$check_user['mobile'].',请使用该手机号登录');
  137. }
  138. //
  139. $intro_uid = 0;
  140. if(!empty($introcode)){
  141. $intro_uid = Db::name('user')->where('introcode',$introcode)->value('id');
  142. if(empty($intro_uid)){
  143. $this->error('请填写正确的邀请码或者不填');
  144. }
  145. }
  146. //登录与注册
  147. $user = \app\common\model\User::getByMobile($mobile);
  148. if ($user) {
  149. if ($user->status == 0) {
  150. $this->error(__('Account is locked'));
  151. }
  152. if ($user->status == 2) {
  153. $this->error('该用户已注销');
  154. }
  155. if (!empty($user->unionid)){
  156. if($user->unionid != $openidInfo['unionid']){
  157. $this->error('请使用初始注册的微信账号进行登录');
  158. }
  159. }else{
  160. //修改最新的openid。其他渠道注册,本渠道第一次来就赋值
  161. $user->unionid = $openidInfo['unionid']; //支付宝注册来的,就得给赋值
  162. $user->app_openid = $openid;
  163. $user->save();
  164. }
  165. //如果已经有账号则直接登录
  166. $ret = $this->auth->direct($user->id);
  167. } else {
  168. // 用户信息不存在时使用
  169. $extend = [
  170. 'app_openid' => $openid,
  171. 'unionid' => $openidInfo['unionid'],
  172. 'intro_uid' => $intro_uid,
  173. ];
  174. $ret = $this->auth->register_mobile($mobile, Random::alnum(), '', $mobile, $extend);
  175. //注册赠送积分
  176. $register_gift_score = intval(config('site.register_gift_score'));
  177. if($register_gift_score > 0){
  178. $wallet = new \app\common\model\Wallet;
  179. $wallet_rs = $wallet->lockChangeAccountRemain($this->auth->id,'score',$register_gift_score,22,'注册赠送积分','user',$this->auth->id);
  180. }
  181. }
  182. if ($ret) {
  183. Sms::flush($mobile, 'mobilelogin');
  184. $data = ['userinfo' => $this->getUserinfo('return')];
  185. $this->success(__('Logged in successful'), $data);
  186. } else {
  187. $this->error($this->auth->getError());
  188. }
  189. }
  190. /**
  191. * 手机验证码登录。小程序端用的
  192. *
  193. * @ApiMethod (POST)
  194. * @param string $mobile 手机号
  195. * @param string $captcha 验证码
  196. */
  197. public function mobilelogin()
  198. {
  199. $mobile = $this->request->post('mobile');
  200. $captcha = $this->request->post('captcha');
  201. $openid = $this->request->post('openid');
  202. $introcode = $this->request->post('introcode','');
  203. if (!$mobile || !$captcha || !$openid) {
  204. $this->error(__('Invalid parameters'));
  205. }
  206. if (!Validate::regex($mobile, "^1\d{10}$")) {
  207. $this->error(__('Mobile is incorrect'));
  208. }
  209. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  210. $this->error(__('Captcha is incorrect'));
  211. }
  212. // 获取openid和sessionkey
  213. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  214. if(!$openidInfo){
  215. $this->error('openid获取失败');
  216. }
  217. //
  218. $check_user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->where('mobile','neq',$mobile)->find();
  219. if($check_user){
  220. $this->error('该微信已经绑定手机号'.$check_user['mobile'].',请使用该手机号登录');
  221. }
  222. //
  223. $intro_uid = 0;
  224. if(!empty($introcode)){
  225. $intro_uid = Db::name('user')->where('introcode',$introcode)->value('id');
  226. if(empty($intro_uid)){
  227. $this->error('请填写正确的邀请码或者不填');
  228. }
  229. }
  230. //登录与注册
  231. $user = \app\common\model\User::getByMobile($mobile);
  232. if ($user) {
  233. if ($user->status == 0) {
  234. $this->error(__('Account is locked'));
  235. }
  236. if ($user->status == 2) {
  237. $this->error('该用户已注销');
  238. }
  239. if (!empty($user->unionid)){
  240. if($user->unionid != $openidInfo['unionid']){
  241. $this->error('请使用初始注册的微信账号进行登录');
  242. }
  243. }else{
  244. //修改最新的sessionkey和openid。其他渠道注册,本渠道第一次来就赋值
  245. // $user->unionid = $openidInfo['unionid']; //支付宝注册的,就得赋值
  246. $user->mini_openid = $openid;
  247. $user->mini_sessionkey = $openidInfo['sessionkey'];
  248. $user->save();
  249. }
  250. //如果已经有账号则直接登录
  251. $ret = $this->auth->direct($user->id);
  252. } else {
  253. // 用户信息不存在时使用
  254. $extend = [
  255. 'mini_openid' => $openid,
  256. 'mini_sessionkey'=> $openidInfo['sessionkey'],
  257. // 'unionid' => $openidInfo['unionid'],
  258. 'intro_uid' => $intro_uid,
  259. ];
  260. $ret = $this->auth->register_mobile($mobile, Random::alnum(), '', $mobile, $extend);
  261. //注册赠送积分
  262. $register_gift_score = intval(config('site.register_gift_score'));
  263. if($register_gift_score > 0){
  264. $wallet = new \app\common\model\Wallet;
  265. $wallet_rs = $wallet->lockChangeAccountRemain($this->auth->id,'score',$register_gift_score,22,'注册赠送积分','user',$this->auth->id);
  266. }
  267. }
  268. if ($ret) {
  269. Sms::flush($mobile, 'mobilelogin');
  270. $data = ['userinfo' => $this->getUserinfo('return')];
  271. $this->success(__('Logged in successful'), $data);
  272. } else {
  273. $this->error($this->auth->getError());
  274. }
  275. }
  276. /**
  277. * 退出登录
  278. * @ApiMethod (POST)
  279. */
  280. public function logout()
  281. {
  282. if (!$this->request->isPost()) {
  283. $this->error(__('Invalid parameters'));
  284. }
  285. $this->auth->logout();
  286. $this->success(__('Logout successful'));
  287. }
  288. //注销用户
  289. public function cancellation(){
  290. Db::name('user')->where('id',$this->auth->id)->update(['status'=>2]);
  291. $this->auth->logout();
  292. $this->success('注销成功');
  293. }
  294. //用户详细资料
  295. public function getUserinfo($type = 1){
  296. $info = $this->auth->getUserinfo();
  297. if($type == 'return'){
  298. return $info;
  299. }
  300. $this->success(__('success'),$info);
  301. }
  302. /**
  303. * 修改会员个人信息
  304. *
  305. * @ApiMethod (POST)
  306. * @param string $avatar 头像地址
  307. * @param string $username 用户名
  308. * @param string $nickname 昵称
  309. * @param string $bio 个人简介
  310. */
  311. public function profile()
  312. {
  313. $user = $this->auth->getUser();
  314. $nickname = $this->request->post('nickname','');
  315. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  316. if(!empty($nickname)){
  317. $user->nickname = $nickname;
  318. }
  319. if(!empty($avatar)){
  320. $user->avatar = $avatar;
  321. }
  322. $user->updatetime = time();
  323. $user->save();
  324. $this->success();
  325. }
  326. /*
  327. * 获取阿里小程序user_id 类似于 unionid
  328. array(7) {
  329. ["access_token"] => string(40) "authbseB9a88caaf0c4f431e853b3f47c7c2bX55"
  330. ["alipay_user_id"] => string(32) "20881082573776119399662512314555"
  331. ["auth_start"] => string(19) "2023-03-27 16:50:11"
  332. ["expires_in"] => int(31536000)
  333. ["re_expires_in"] => int(31536000)
  334. ["refresh_token"] => string(40) "authbseBd9f5b3f1f07145a3b734a9ca08c8dF55"
  335. ["user_id"] => string(16) "2088802394079558"
  336. }
  337. * */
  338. public function getAlipayUserid(){
  339. // code值
  340. $code = $this->request->param('code');
  341. if (!$code) {
  342. $this->error(__('Invalid parameters'));
  343. }
  344. $openidInfo = $this->alipay_oauthtoken($code);
  345. if(!isset($openidInfo['access_token'])) {
  346. $this->error('access_token获取失败',$openidInfo);
  347. }
  348. if(!isset($openidInfo['user_id'])) {
  349. $this->error('用户user_id获取失败',$openidInfo);
  350. }
  351. $user_id = $openidInfo['user_id'];
  352. $check = Db::name('user_sessionkey_alipay')->where('user_id',$user_id)->find();
  353. if($check){
  354. $res = Db::name('user_sessionkey_alipay')->where('user_id',$user_id)->update($openidInfo);
  355. }else{
  356. $res = Db::name('user_sessionkey_alipay')->insertGetId($openidInfo);
  357. }
  358. $result = [
  359. 'user_id' => $user_id,
  360. ];
  361. if($res !== false) {
  362. $this->success('获取成功',$result);
  363. } else {
  364. $this->error('获取失败');
  365. }
  366. }
  367. /**
  368. * 阿里小程序登录
  369. */
  370. public function AlipayMiniProgramLogin() {
  371. $openid = $this->request->request('user_id');// openid值
  372. if (!$openid) {
  373. $this->error(__('Invalid parameters'));
  374. }
  375. // 用户登录逻辑 === 开始
  376. $user_sessionkey = Db::name('user_sessionkey_alipay')->where('user_id',$openid)->find();
  377. $userInfo = Db::name('user')->where(['ali_user_id'=>$user_sessionkey['user_id']])->find();
  378. // 判断用户是否已经存在
  379. if($userInfo) { // 登录
  380. if ($userInfo['status'] == 0) {
  381. $this->error(__('Account is locked'));
  382. }
  383. if ($userInfo['status'] == 2) {
  384. $this->error('该用户已注销');
  385. }
  386. $update = [
  387. 'logintime' => time(),
  388. ];
  389. Db::name('user')->where('id',$userInfo['id'])->update($update);
  390. $res = $this->auth->direct($userInfo['id']);
  391. } else {
  392. //这里不在给注册,而是只能mobilelogin来注册
  393. $this->error('登录失败,请先使用手机号注册','',-1);
  394. }
  395. $userInfo = $this->getUserinfo('return');
  396. if($res) {
  397. if(empty($userInfo['mobile'])){
  398. $this->success("登录成功!",$userInfo,-1);
  399. }
  400. $this->success("登录成功!",$userInfo);
  401. } else {
  402. $this->error("登录失败!");
  403. }
  404. }
  405. //获取阿里授权
  406. private function alipay_oauthtoken($code = '')
  407. {
  408. $config = config('Alimini');
  409. $aop = new AopClient ();
  410. $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  411. $aop->appId = $config['appId'];
  412. $aop->rsaPrivateKey = $config['rsaPrivateKey'];
  413. $aop->alipayrsaPublicKey=$config['alipayrsaPublicKey'];
  414. $aop->signType = 'RSA2';
  415. $request = new AlipaySystemOauthTokenRequest ();
  416. $request->setGrantType("authorization_code");
  417. $request->setCode($code);
  418. $request->setRefreshToken('');
  419. $result = $aop->execute ( $request);
  420. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  421. /*$resultCode = $result->$responseNode->code;
  422. //dump($resultCode);
  423. if(!empty($resultCode)&&$resultCode == 10000){
  424. echo "成功";
  425. } else {
  426. echo "失败";
  427. }*/
  428. return (array)$result->$responseNode;
  429. }
  430. //获取app用户的access_token和unionid
  431. /*
  432. {
  433. "code":1,
  434. "msg":"获取成功",
  435. "time":"1677578250",
  436. "data":{
  437. "access_token":"66_p3_21ZTj9yWf6urG5OVBctFCFSyd0uvAxVrhWybtdTugxLgkJXM48PreDtD8HM5vrpNRKKjzWcqnvB01P7NYKS8iqwr8u2hnryiNILFeUGo",
  438. "expires_in":7200,
  439. "refresh_token":"66_NpmP0-lNl0ek1Nsad8OGAjuwznMG0KSq_8d3rmrkKNhvFmW2_K5oxlwr0kNFOsvM90s6ODc3bONvbF1zmqYIx9JLlG9By7vf94YWJk3602E",
  440. "openid":"oCvQ560NwtAZf-g4EqoYSypastJ8",
  441. "scope":"snsapi_userinfo",
  442. "unionid":"oOPcI6Jzozsffndh4CzVGXmwLejU"
  443. }
  444. }
  445. */
  446. public function getAppOpenid(){
  447. // code值
  448. $code = $this->request->param('code');
  449. if (!$code) {
  450. $this->error(__('Invalid parameters'));
  451. }
  452. $config = config('wechatlogin');
  453. $wechat = new \app\common\library\Wechat($config['AppID'],$config['AppSecret']);
  454. $openidInfo = $wechat->getAccessToken($code);
  455. if(!isset($openidInfo['access_token'])) {
  456. $this->error('access_token获取失败',$openidInfo);
  457. }
  458. if(!isset($openidInfo['openid'])) {
  459. $this->error('用户openid获取失败',$openidInfo);
  460. }
  461. if(!isset($openidInfo['unionid'])){
  462. $this->error('unionid不存在',$openidInfo);
  463. }
  464. // 获取的结果存入数据库
  465. $find = Db::name('user_sessionkey')->where(['unionid'=>$openidInfo['unionid']])->find();
  466. if($find) {
  467. $update = [];
  468. $update['createtime'] = time();
  469. $update['access_token'] = $openidInfo['access_token'];
  470. $update['app_openid'] = $openidInfo['openid'];
  471. $res = Db::name('user_sessionkey')->where(['unionid'=>$openidInfo['unionid']])->update($update);
  472. } else {
  473. $insert = [];
  474. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  475. $insert['createtime'] = time();
  476. $insert['access_token'] = $openidInfo['access_token'];
  477. $insert['app_openid'] = $openidInfo['openid'];
  478. $res = Db::name('user_sessionkey')->insertGetId($insert);
  479. }
  480. if($res !== false) {
  481. $this->success('获取成功',$openidInfo);
  482. } else {
  483. $this->error('获取失败');
  484. }
  485. }
  486. //微信app授权登录,
  487. public function wxAPPLogin(){
  488. $openid = $this->request->request('openid');// openid值
  489. if (!$openid) {
  490. $this->error(__('Invalid parameters'));
  491. }
  492. // 用户登录逻辑 === 开始
  493. $user_sessionkey = Db::name('user_sessionkey')->where('app_openid',$openid)->find();
  494. $userInfo = Db::name('user')->where(['unionid'=>$user_sessionkey['unionid']])->find();
  495. // 判断用户是否已经存在
  496. if($userInfo) { // 登录
  497. if ($userInfo['status'] == 0) {
  498. $this->error(__('Account is locked'));
  499. }
  500. if ($userInfo['status'] == 2) {
  501. $this->error('该用户已注销');
  502. }
  503. $update = [
  504. 'app_openid' => $user_sessionkey['app_openid'],//已经有的不需要更新
  505. 'logintime' => time(),
  506. ];
  507. Db::name('user')->where('id',$userInfo['id'])->update($update);
  508. $res = $this->auth->direct($userInfo['id']);
  509. } else {
  510. //这里不在给注册,而是只能mobilelogin来注册
  511. $this->error('登录失败,请先使用手机号注册','',-1);
  512. }
  513. $userInfo = $this->getUserinfo('return');
  514. if($res) {
  515. if(empty($userInfo['mobile'])){
  516. $this->success("登录成功!",$userInfo,-1);
  517. }
  518. $this->success("登录成功!",$userInfo);
  519. } else {
  520. $this->error("登录失败!");
  521. }
  522. }
  523. /**
  524. * 获取用户openid
  525. */
  526. public function getUserOpenid_old() {
  527. // code值
  528. $code = $this->request->param('code');
  529. if (!$code) {
  530. $this->error(__('Invalid parameters'));
  531. }
  532. $config = config('wxMiniProgram');
  533. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  534. $openidInfo = $this->getJson($getopenid);
  535. if(!isset($openidInfo['openid'])) {
  536. $this->error('用户openid获取失败',$openidInfo);
  537. }
  538. if(!isset($openidInfo['unionid'])){
  539. $this->error('unionid不存在',$openidInfo);
  540. }
  541. // 获取的结果存入数据库
  542. $find = Db::name('user_sessionkey')->where(['unionid'=>$openidInfo['unionid']])->find();
  543. if($find) {
  544. $update = [];
  545. $update['openid'] = $openidInfo['openid'];
  546. $update['sessionkey'] = $openidInfo['session_key'];
  547. $update['createtime'] = time();
  548. $res = Db::name('user_sessionkey')->where(['unionid'=>$openidInfo['unionid']])->update($update);
  549. } else {
  550. $insert = [];
  551. $insert['openid'] = $openidInfo['openid'];
  552. $insert['sessionkey'] = $openidInfo['session_key'];
  553. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  554. $insert['createtime'] = time();
  555. $res = Db::name('user_sessionkey')->insertGetId($insert);
  556. }
  557. if($res !== false) {
  558. $this->success('获取成功',$openidInfo);
  559. } else {
  560. $this->error('获取失败');
  561. }
  562. }
  563. public function getUserOpenid() {
  564. // code值
  565. $code = $this->request->param('code');
  566. if (!$code) {
  567. $this->error(__('Invalid parameters'));
  568. }
  569. $config = config('wxMiniProgram');
  570. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  571. $openidInfo = $this->getJson($getopenid);
  572. if(!isset($openidInfo['openid'])) {
  573. $this->error('用户openid获取失败',$openidInfo);
  574. }
  575. /*if(!isset($openidInfo['unionid'])){
  576. $this->error('unionid不存在',$openidInfo);
  577. }*/
  578. // 获取的结果存入数据库
  579. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  580. if($find) {
  581. $update = [];
  582. $update['openid'] = $openidInfo['openid'];
  583. $update['sessionkey'] = $openidInfo['session_key'];
  584. $update['createtime'] = time();
  585. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  586. } else {
  587. $insert = [];
  588. $insert['openid'] = $openidInfo['openid'];
  589. $insert['sessionkey'] = $openidInfo['session_key'];
  590. // $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  591. $insert['createtime'] = time();
  592. $res = Db::name('user_sessionkey')->insertGetId($insert);
  593. }
  594. if($res !== false) {
  595. $this->success('获取成功',$openidInfo);
  596. } else {
  597. $this->error('获取失败');
  598. }
  599. }
  600. /**
  601. * 微信小程序授权登录
  602. */
  603. public function wxMiniProgramLogin() {
  604. $openid = $this->request->request('openid');// openid值
  605. if (!$openid) {
  606. $this->error(__('Invalid parameters'));
  607. }
  608. // 用户登录逻辑 === 开始
  609. $user_sessionkey = Db::name('user_sessionkey')->where('openid',$openid)->find();
  610. $userInfo = Db::name('user')->where(['mini_openid'=>$user_sessionkey['openid']])->find();
  611. // 判断用户是否已经存在
  612. if($userInfo) { // 登录
  613. if ($userInfo['status'] == 0) {
  614. $this->error(__('Account is locked'));
  615. }
  616. if ($userInfo['status'] == 2) {
  617. $this->error('该用户已注销');
  618. }
  619. $update = [
  620. 'mini_openid' => $user_sessionkey['openid'],//已经有的不需要更新
  621. 'mini_sessionkey' => $user_sessionkey['sessionkey'],
  622. 'logintime' => time(),
  623. ];
  624. Db::name('user')->where('id',$userInfo['id'])->update($update);
  625. $res = $this->auth->direct($userInfo['id']);
  626. } else {
  627. //这里不在给注册,而是只能mobilelogin来注册
  628. $this->error('登录失败,请先使用手机号注册','',-1);
  629. }
  630. $userInfo = $this->getUserinfo('return');
  631. if($res) {
  632. if(empty($userInfo['mobile'])){
  633. $this->success("登录成功!",$userInfo,-1);
  634. }
  635. $this->success("登录成功!",$userInfo);
  636. } else {
  637. $this->error("登录失败!");
  638. }
  639. }
  640. /**
  641. * json 请求
  642. * @param $url
  643. * @return mixed
  644. */
  645. private function getJson($url){
  646. $ch = curl_init();
  647. curl_setopt($ch, CURLOPT_URL, $url);
  648. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  649. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  650. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  651. $output = curl_exec($ch);
  652. curl_close($ch);
  653. return json_decode($output, true);
  654. }
  655. }