<?php
declare (strict_types = 1);

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class WxAppCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     *
     */
    public function handle($request, \Closure $next)
    {
        $token=request()->header('token');

        //验证token
        $res=checkToken_s($token);

        //对返回结果进行判断
        if (!is_numeric($res)){
            return json(['code'=>1,'message'=>$res]);
        }
        //保存用户ID
        $request->uid=$res;
        return $next($request);

    }

}

function checkToken_s($token)
{
    $key = 'zbcazbc';
    $key = new Key($key, 'HS256');
    $status = array("code" => 2);
//    echo $token;
    try {
        JWT::$leeway = 60;//当前时间减去60，把时间留点余地
        $decoded = JWT::decode($token, $key, array('HS256')); //HS256方式，这里要和签发的时候对应
        $arr = (array)$decoded;
//        print_r($arr);
        $res['code'] = 1;
        $res['data'] = $arr['data'];
        return $res['data']->uid;
    } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
        $status['msg'] = "签名不正确";
        return $status['msg'];
    } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
        $status['msg'] = "token失效";
        return $status['msg'];
    } catch (\Firebase\JWT\ExpiredException $e) { // token过期
        $status['msg'] = "token失效";
        return $status['msg'];
    } catch (\Exception $e) { //其他错误
        $status['msg'] = "未知错误";
        return $status['msg'];
    }
}
