一.安装
通过 composer 安装
运行以下命令进入JWT:
composer require firebase/php-jwt
创建server层:
<?php
namespace app\api\server;
use app\Request;
use Firebase\JWT\JWT;
class Token
{
protected $salt;
public function __construct()
{
$this->salt = config('jwt.salt');
}
/**
* 生成token
* @param $uid
* @return mixed
*/
function generateToken($uid)
{
//获取当前时间戳
$currentTime = time();
$data = array(
"iss" => 'keZuo', //签发者 可以为空
"aud" => '', //面象的用户,可以为空
"iat" => $currentTime, //签发时间
"nbf" => $currentTime, //立马生效
"exp" => $currentTime + 7200, //token 过期时间 两小时
"data" => [ //记录的userid的信息,这里是自已添加上去的,如果有其它信息,可以再添加数组的键值对
'uid' => $uid,
]
);
//生成token
$token = JWT::encode($data, $this->salt, "HS256"); //根据参数生成了 token
return $token;
}
/**
* 校验token时效性
*/
public function chekToken($token)
{
$status=array("code"=>2);
try {
JWT::$leeway = 60;//当前时间减去60,把时间留点余地
$decoded = JWT::decode($token, $this->salt, array('HS256')); //HS256方式,这里要和签发的时候对应
$arr = (array)$decoded;
$res['code']=1;
$res['data']=$arr['data'];
return $res;
} catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
$status['msg']="签名不正确";
return $status;
}catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
$status['msg']="token失效";
return $status;
}catch(\Firebase\JWT\ExpiredException $e) { // token过期
$status['msg']="token失效";
return $status;
}catch(\Exception $e) { //其他错误
$status['msg']="未知错误";
return $status;
}
}
}
comtroller层:
public function login(Request $request)
{
//echo 1234;die();
//获取code码
$code = $request->get('code');
//获取微信授权url
$url = sprintf(config('wx.wxLoginUrl'),config('wx.AppID'),config('wx.AppSecret'),$code);
//获取openid
$data = curlGet($url);
//进行查询数据库里面是否有该用户,如果没有,则进行新增
$user = UserModel::where('openid',$data['openid'])->find();
//如果没有用户进行创建
if (empty($user)){
$user = UserModel::create([
'openid'=>$data['openid']
]);
}
//生成token,保存用户登录状态
$token = (new TokenServer())->generateToken($user->id);
//将token
print_r($token);die();
return json(['token'=>$token,'error_code'=>0,'msg'=>'登录成功','openid'=>$user['openid']]);
}
common:
function curlGet($url){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
return $output;
}
|