<?php
/**
 * PHP实现jwt
 */
class Jwt {
 
    //头部
    private static $header=array(
        'alg'=>'HS256', //生成signature的算法
        'typ'=>'JWT'    //类型
    );
 
    //使用HMAC生成信息摘要时所使用的密钥
    private static $key = "yer";
 
    public function __construct()
    {
        //实际开发中，如果不是做动态登录token，而是做某个接口token验证，可以把$key设置成分配好权限的随机值
        self::$key = "yer";
    }
 
    public static function getToken(array $payload)
    {
        if(is_array($payload))
        {
            $header=urlencode(json_encode(self::$header,true));
            $payload=urlencode(json_encode($payload,true));
            $token=$header.'.'.$payload.'.'.urlencode($header . $payload . self::$key . self::$header['alg']);
            return $token;
 
            //实际开发时，将token和expireTime放到user表，setTime放到日志表
            /*
                 $user_id = 1;
                $setTime = time();
                $expireTime = time() + 7200;
                $sql1 = "update user  where user_id = $user_id set setTime = $expireTime";
                $sql2 = "insert into log (user_id, set_time) values ($user_id, $setTime)";
            */
        }else{
            return false;
        }
    }
 
 
    public static function verifyToken($Token)
    {
        $tokens = explode('.', $Token);
        if (count($tokens) != 3)
            return false;
 
        list($header, $payload, $sign) = $tokens;
 
        //获取jwt算法
        if (empty(json_decode(urldecode($header), true)['alg'])){
        	
            $res = array('code'=>'90004','msg'=>'签名算法不匹配');//签名算法不匹配
            //return '签名算法不匹配';
        }
 
        //签名验证
        if (urlencode($header . $payload . self::$key  . self::$header['alg']) !== $sign){
            //return '签名错误'; 
            $res = array('code'=>'90002','msg'=>'签名不正确');//token错误验证失败
        }
        $payload = json_decode(urldecode($payload), JSON_OBJECT_AS_ARRAY);
     	//return  $payload;
        /*实际开发时，验证当前时间是否比user表中的expireTime大*/
        if (isset($payload['expireTime']) && $payload['expireTime'] < time()){
           // return '签名失效'; 
            $res = array('code'=>'90003','msg'=>' token过期');//token长时间未使用而过期，需重新登陆
        	
        }
       if(!isset($res)||empty($res)){
           return $payload;
    	
        }else{
        	
        	return $res;
        }
    }
 
 
}
 
//echo "<pre>";
//$payload = array('username'=>'i am username','password'=>'i am password');//规则可以自定义,本人喜欢用账号和密码
//var_dump($payload);
//$jwt = new Jwt;
//$token = $jwt->getToken($payload);
//echo $token;
 
//对token进行验证签名
//$getPayload = $jwt->verifyToken($token);
//echo "<br><br>";
//var_dump($getPayload);
//echo "<br><br>";
//接下来
//开发中先判断$getPayload中是否存在自定义规则的指定字段，不存在失败
//然后去验证当前用户的username，password，token是否在user表中存在记录，不存在失败
 