composer安装jwt
composer require firebase/php-jwt
安装好以后 直接创建一个文件在自己模块下面来调用生成token
写入代码 复制过去改一改命名空间就可以了
<?php
namespace app\api\Server;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class Token
{
private $key = "mini-program-api";
/**
* 生成令牌
* @param $uid
* @return string
*/
public static function createToken($uid){
$payload = [
'iss' => 'http://example.org',
'aud' => 'http://example.com',
'iat' => time(),
'nbf' => time(),
'expire' => time() + 86400,
'uid' => $uid
];
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
return JWT::encode($payload, (new self())->key, 'HS256');
}
/**
* 验证token
* @return false|mixed
*/
public static function verifyToken(){
try {
if (!isset($_SERVER["HTTP_AUTHORIZATION"])) {
return false;
}
$token = $_SERVER["HTTP_AUTHORIZATION"];
if (is_numeric(strrpos($token,"Bearer"))) {
$token = trim(str_replace("Bearer"," ",$token));
}
if (empty($token)) {
return false;
}
$decoded = JWT::decode($token, new Key((new self())->key, 'HS256'));
$decoded = (array)$decoded;
if (!isset($decoded['uid']) && $decoded['expire'] < time()) {
return false;
}
return $decoded['uid'];
}catch (\Exception $exception){
return false;
}
}
}
然后是登录调用获取token
//小程序登录
public function login(Request $request){
$code=$request->get('code');
$appid="wx16b33e4050733263";
$appSecret="3a1ab0ba5e5d2c40159dbf858b67e4bc";
$url="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
$data=file_get_contents($url);
$data=json_decode($data,true);
$user = User::where('openid',$data['openid'])->find();
//如果没有用户进行创建
if($user){
$user=User::create(['openid'=>$data['openid']]);
$uid=$user->id;
}else{
$uid=$user->id;
}
$token=Token::createToken($uid);
return json(['code'=>200,'msg'=>'登录成功','token'=>$token]);
}
找个方法比之前的那个好多简洁