开发语言
后端:thinkphp5+easywechat3+php-jwt
前端:html
实现思路
需要授权登录页面,在页面加载完成时,判断是否登录,如果未登录访问后台授权登录链接
前端代码(主要js代码)
var domain = "http://mmys.com/api/";
$(function () {
//判断本地是否有token,没有就获取
console.log(localStorage.getItem('token'))
if(!localStorage.getItem('token')){
getToken();
}
//获取token,用于需要鉴权的接口
function getToken(){
$.post(domain+"user/getToken",{},function (res) {
if(res.code){
console.log(res.data);
//将token存入本地缓存
localStorage.setItem('token',res.data.token);
}else{
//登录,跳转到后台登录方法,target_url传本页面地址
location.href = domain+"user/login?target_url=index.html";
}
})
}
}
后端代码(主要方法)
/**
* 获取token
*/
public function getToken()
{
if(!session('wechat_user')){
$this->error('请先登录');
}else{
//保存用户信息
$wx_user = self::saveUser();
$this->success('已登录',$wx_user);
}
}
/**
* 网页授权登录(直接访问链接)
*/
public function login()
{
$target_url = request()->param('target_url');
$target_url = "http://{$_SERVER['SERVER_NAME']}/wap/$target_url";
self::wxLogin($target_url);
}
//微信登录
static function wxLogin($target_url='')
{
$options = Config::get('wechat');
$app = new Application($options);
$oauth = $app->oauth;
// 未登录
if (empty(session('wechat_user'))) {
session('target_url',$target_url);
$oauth->redirect()->send();
}
}
//保存用户信息
static function saveUser()
{
// 已经登录过
$user = session('wechat_user');
//存入数据库
$wxUser = new WxUser();
$wx_user = $wxUser->where('openid',$user['id'])->find();
$user_data = [
'openid' => $user['id'],
'nickname' => $user['nickname'],
'avatar' => $user['avatar'],
'address' => $user['original']['province'].$user['original']['city']
];
$is_update = false;
if($wx_user){
//更新
$wxUser->where('id',$wx_user['id'])->update($user_data);
}else{
//添加
$wx_user = WxUser::create($user_data);
}
$wx_user = $wx_user->toArray();
$jwt_auth = new auth();
$token = $jwt_auth->_setJwtToken($wx_user);
$wx_user['token'] = $token;
return $wx_user;
}
//授权回调
public function oauth_callback(){
$options = Config::get('wechat');
$app = new Application($options);
$oauth = $app->oauth;
// 获取 OAuth 授权结果用户信息
$user = $oauth->user();
$user = $user->toArray();
session('wechat_user',$user);
$targetUrl = empty(session('target_url')) ? '/' : session('target_url');
header('location:'. $targetUrl);
}