use Firebase\JWT\JWT as CreateJwt;
public static function signToken($openid)
{
$key = '15553242780';
$token = array(
"iss"=>$key,
"aud"=>'',
"iat"=>time(),
"nbf"=>time()+3,
"exp"=>time()+200,
"data"=>[
'uid'=>$openid,
]
);
$jwt = CreateJwt::encode($token,$key,"HS256");
return $jwt;
}
public static function checkToken($token)
{
$key = '15553242780';
$status = array("code"=>2);
try {
CreateJwt::$leeway = 60;
$decoded = CreateJwt::decode($token, $key, array('HS256'));
$arr = (array)$decoded;
$res['code'] = 1;
$res['data'] = $arr['data'];
return $arr['data']->uid;
} catch (\Firebase\JWT\SignatureInvalidException $e) {
$status['msg'] = "q";
return $status;
} catch (\Firebase\JWT\BeforeValidException $e) {
$status['msg'] = "token失效";
return $status;
} catch (\Firebase\JWT\ExpiredException $e) {
$status['msg'] = "token失效";
return $status;
} catch (\Exception $e) {
$status['msg'] = "未知错误";
return $status;
}
}
public static function weChat($code)
{
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx9ac45f3e3ff54e5f&secret=84aedacc8aa13e723b22119758ce15c1&js_code=$code&grant_type=authorization_code";
$userInfo = json_decode(file_get_contents($url),true);
return $userInfo;
}
public function handle($request, \Closure $next)
{
$token = $request->header('token');
$userInfo = JWT::checkToken($token);
if ($userInfo == null){
return json(['code'=>400,'msg'=>'不可访问']);
}
$u_id = user::where('openid','=',$userInfo)->find()->value('id');
$request->u_id = $u_id;
return $next($request);
}
|