微信小程序生成laravel生成token
composer require firebase/php-jwt=5.5
<?php
namespace App\Service;
use Firebase\JWT\JWT;
class Token
{
protected $key;
public function __construct()
{
$this->key = 'lizichen';
}
/**
* 生成token
*/
public function createToken($uid)
{
$time = time();
$payload = array(
"iss" => "",
"aud" => "",
"iat" => $time,
"nbf" => $time,
"exp" => $time+7200,
"uid" => $uid
);
$token = JWT::encode($payload,$this->key);
return $token;
}
/**
* 验证token
*/
public function validateToken($token)
{
try {
$decoded = JWT::decode($token, $this->key, array('HS256'));
return $decoded->uid;
}catch (\Exception $e){
return 'token过期';
}
}
}
<?php
namespace App\Http\Middleware;
use App\Service\Token;
use Closure;
use Illuminate\Http\Request;
class JwtToken
{
/**
* Handle an incoming request.
*
* [@param](/user/param) \Illuminate\Http\Request $request
* [@param](/user/param) \Closure $next
* [@return](/user/return) mixed
*/
public function handle(Request $request, Closure $next)
{
$token = $request->header('token');
if(empty($token)){
return response()->json(['code'=>40001,'msg'=>'请先登录','data'=>'']);
}
$res = (new Token())->validateToken($token);
if(!is_numeric($res)){
return response()->json(['code'=>40002,'msg'=>$res,'data'=>'']);
}
$request['uid'] = $res;
return $next($request);
}
}