<?php
/**
 * Created by PhpStorm.
 * User: shaoguo
 * Date: 2019-03-07
 * Time: 17:25
 */

namespace app\common\plugin;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use \Firebase\JWT\JWT as JWTP;
use Firebase\JWT\SignatureInvalidException;
class Jwt extends JWTP
{
    static private $key='VKcZGQQ4zjAzjc0yZsa0';

    static private $type=['HS256'];

    /**
     * @name 获取token
     * @param $openid
     * @param $major
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function getToken($user_id,$major='aaa'){
        $time=time();
        //$user=db('wx_user')->where(['wx_openid'=>$openid])->find();
        $token=[
            'iss'=>url("/"),
            'iat'=>$time,
            'exp'=>$time+7200*24*3600,
            'data'=>[
                'userid'=>$user_id,
                'major'=>$major
            ]
        ];
        return self::encode($token,static::$key);
    }

   static public function verify($token){
        $message=[];
        try{
            self::$leeway=60;
            $decoded=self::decode($token,static::$key,static::$type);
            $arr=(array)$decoded;
            $message=[
                'code'=>1,
                'message'=>$arr
            ];

        }catch (SignatureInvalidException $e){
            $message=[
                'code'=>0,
                'message'=>"签名错误"
            ];
        } catch (BeforeValidException $e){
            $message=[
                'code'=>0,
                'message'=>"签名在某个时段才能运行"
            ];
        }catch(ExpiredException $e){
            $message=[
                'code'=>0,
                'message'=>"登录过期"
            ];
        }catch (\Exception $e){
            $message=[
                'code'=>0,
                'message'=>'签名异常错误'
            ];
        }

        return $message;

    }
}