|
|
|
@ -2,8 +2,12 @@ |
|
|
|
|
|
|
|
namespace app\controller\wechat; |
|
|
|
|
|
|
|
use app\model\WechatUser; |
|
|
|
use app\service\user\LoginService; |
|
|
|
use app\util\ReturnCode; |
|
|
|
use think\facade\Cache; |
|
|
|
use think\facade\Request; |
|
|
|
use think\Response; |
|
|
|
|
|
|
|
class Login extends Base |
|
|
|
{ |
|
|
|
@ -51,6 +55,69 @@ class Login extends Base |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
public function getWxCode() { |
|
|
|
$state = md5(uniqid() . time()); |
|
|
|
cache($state, $state, 300); |
|
|
|
|
|
|
|
return $this->buildSuccess([ |
|
|
|
'appId' => env('wechat.appid'), |
|
|
|
'redirectUri' => urlencode(env('wechat.redirect_uri')), |
|
|
|
'state' => $state |
|
|
|
]); |
|
|
|
} |
|
|
|
|
|
|
|
public function wx(): Response { |
|
|
|
validate($this->valid)->scene('wxLogin')->check(Request::post()); |
|
|
|
$state = $this->request->post('state', ''); |
|
|
|
$code = $this->request->post('code', ''); |
|
|
|
|
|
|
|
//验证合法性 |
|
|
|
$cacheData = Cache::has($state); |
|
|
|
if (!$cacheData) { |
|
|
|
return $this->buildFailed(ReturnCode::SESSION_TIMEOUT, 'state已过期'); |
|
|
|
} else { |
|
|
|
cache($state, null); |
|
|
|
} |
|
|
|
|
|
|
|
//获取AccessToken |
|
|
|
$getAccessTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . |
|
|
|
env('wechat.appid') . '&secret=' . env('app.appsecret') . '&code=' . $code . |
|
|
|
'&grant_type=authorization_code'; |
|
|
|
|
|
|
|
$tokenArr = file_get_contents($getAccessTokenUrl); |
|
|
|
$accessTokenArr = json_decode($tokenArr, true); |
|
|
|
|
|
|
|
//获取openId |
|
|
|
$getUserIdUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessTokenArr['access_token'] . '&openid=' . $accessTokenArr['openid']; |
|
|
|
$userIdArr = file_get_contents($getUserIdUrl); |
|
|
|
$userIdArr = json_decode($userIdArr, true); |
|
|
|
|
|
|
|
return $this->doLogin($userIdArr['openid'], [ |
|
|
|
'nickname' => $userIdArr['nickname'], |
|
|
|
'head_img' => $userIdArr['headimgurl'] |
|
|
|
]); |
|
|
|
} |
|
|
|
|
|
|
|
private function doLogin(string $openid, array $userDetail): Response { |
|
|
|
$userInfo = (new WechatUser())->where('openid', $openid)->find(); |
|
|
|
if (empty($userInfo)) { |
|
|
|
$userInfo = WechatUser::create([ |
|
|
|
'nickname' => $userDetail['nickname'], |
|
|
|
'openid' => $openid, |
|
|
|
'create_time' => time(), |
|
|
|
'headimgurl' => $userDetail['head_img'], |
|
|
|
]); |
|
|
|
} else { |
|
|
|
if (!$userInfo['status']) { |
|
|
|
return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户已被封禁,请联系管理员'); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
$data = $userInfo->toArray(); |
|
|
|
unset($data['delete_time'],$data['status']); |
|
|
|
return $this->buildSuccess($data, '登录成功'); |
|
|
|
} |
|
|
|
|
|
|
|
public function userLogout() |
|
|
|
{ |
|
|
|
|
|
|
|
|