Jwt.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shaoguo
  5. * Date: 2019-03-07
  6. * Time: 17:25
  7. */
  8. namespace app\common\plugin;
  9. use Firebase\JWT\BeforeValidException;
  10. use Firebase\JWT\ExpiredException;
  11. use \Firebase\JWT\JWT as JWTP;
  12. use Firebase\JWT\SignatureInvalidException;
  13. class Jwt extends JWTP
  14. {
  15. static private $key='VKcZGQQ4zjAzjc0yZsa0';
  16. static private $type=['HS256'];
  17. /**
  18. * @name 获取token
  19. * @param $openid
  20. * @param $major
  21. * @return array|false|\PDOStatement|string|Model
  22. * @throws \think\db\exception\DataNotFoundException
  23. * @throws \think\db\exception\ModelNotFoundException
  24. * @throws \think\exception\DbException
  25. */
  26. static public function getToken($user_id,$major='aaa'){
  27. $time=time();
  28. //$user=db('wx_user')->where(['wx_openid'=>$openid])->find();
  29. $token=[
  30. 'iss'=>url("/"),
  31. 'iat'=>$time,
  32. 'exp'=>$time+7200*24*3600,
  33. 'data'=>[
  34. 'userid'=>$user_id,
  35. 'major'=>$major
  36. ]
  37. ];
  38. return self::encode($token,static::$key);
  39. }
  40. static public function verify($token){
  41. $message=[];
  42. try{
  43. self::$leeway=60;
  44. $decoded=self::decode($token,static::$key,static::$type);
  45. $arr=(array)$decoded;
  46. $message=[
  47. 'code'=>1,
  48. 'message'=>$arr
  49. ];
  50. }catch (SignatureInvalidException $e){
  51. $message=[
  52. 'code'=>0,
  53. 'message'=>"签名错误"
  54. ];
  55. } catch (BeforeValidException $e){
  56. $message=[
  57. 'code'=>0,
  58. 'message'=>"签名在某个时段才能运行"
  59. ];
  60. }catch(ExpiredException $e){
  61. $message=[
  62. 'code'=>0,
  63. 'message'=>"登录过期"
  64. ];
  65. }catch (\Exception $e){
  66. $message=[
  67. 'code'=>0,
  68. 'message'=>'签名异常错误'
  69. ];
  70. }
  71. return $message;
  72. }
  73. }