1.引入php-jwt包
composer require firebase/php-jwt
2.代码
<?php
namespace app\api\controller;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\Exception;
class Jwt
{
/**
* 根据json web token设置的规则生成token
* @return \think\response\Json
*/
public static function createjwt($id)
{
$key = md5('dd'); //jwt的签发密钥,验证token的时候需要用到
$time = time(); //签发时间
$expire = $time + 14400; //过期时间
$token = array(
"user_id" => $id,
"iss" => "http://www.1909A.com/",//签发组织
"aud" => "lmp", //签发作者
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
$jwt = JWTUtil::encode($token,$key);
return $jwt;
}
/**
* 验证token
* @return \think\response\Json
*/
public static function verifyjwt($jwt)
{
$key = md5('dd'); //jwt的签发密钥,验证token的时候需要用到
try{
$jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
$authInfo = json_decode($jwtAuth,true);
if (!$authInfo['user_id']){
throw new Exception("用户不存在");
}
return json($authInfo);
}catch (ExpiredException $e){
throw new Exception("token过期了");
}catch (\Exception $e){
return dump($e->getMessage());
}
}
public static function getRequestToken()
{
if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
return false;
}
$header = $_SERVER['HTTP_AUTHORIZATION'];
$method = 'bearer';
//去除token中可能存在的bearer标识
return trim(str_ireplace($method, '', $header));
}
}
PHP 常用的公共配置
<?php
// 应用公共文件
if(!function_exists('fail'))
{
function fail($msg,$data="",$code=500)
{
$info = [
'data'=>$data,
'code'=>$code,
'msg'=>$msg,
];
return json($info);
}
}
if(!function_exists('success'))
{
function success($msg,$data="",$code=200)
{
$info = [
'data'=>$data,
'code'=>$code,
'msg'=>$msg,
];
return json($info);
}
}
if(!function_exists("recursion")){
//
function recursion($list,$pid=0,$f=0){
//声明一个静态数组存储处理后的数据
static $arr = [];
foreach($list as $val){
if($val['pid']==$pid){
$val['level'] = $f;
$arr[]=$val;
get_cate_list($list,$val['id'],$f+1);
}
}
return $arr;
}
}