发票管理apiadmin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

82 lines
2.5 KiB

<?php
namespace app\middleware;
use app\util\ReturnCode;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Response;
class WechatAuth
{
/**
* 后台登录验证
* @param $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next): Response {
$header = config('apiadmin.CROSS_DOMAIN');
$token = $request->header('token', '');
$response = $next($request);
$response->header($header);
if ($token) {
$userInfo = $this->checkToken($token);
if ($userInfo['code'] == 2) {
return json([
'code' => ReturnCode::AUTH_ERROR,
'msg' => $userInfo['msg'],
'data' => []
])->header($header);
} else {
$request->wechat_user = $userInfo['data'];
$request->wechat_user_id = $userInfo['data']['id'];
}
return $response;
} else {
return json([
'code' => ReturnCode::AUTH_ERROR,
'msg' => '缺少token',
'data' => []
])->header($header);
}
}
/**
* 验证token
* @param $token
* @return array|int[]
*/
private function checkToken($token): array
{
$key = config('jwt.key');
$status = array("code" => 2);
try {
JWT::$leeway = 60; //当前时间减去60,把时间留点余地
$decoded = JWT::decode($token, new Key($key, 'HS384')); //同上的方式,这里要和签发的时候对应
$arr = (array)$decoded;
$res['code'] = 200;
$res['data'] = $arr['data'];
$res['data'] = json_decode(json_encode($res['data']), true);//将stdObj类型转换为array
return $res;
} catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
$status['msg'] = "签名不正确";
return $status;
} catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
$status['msg'] = "token失效";
return $status;
} catch (\Firebase\JWT\ExpiredException $e) { // token过期
$status['msg'] = "token失效";
return $status;
} catch (\Exception $e) { //其他错误
$status['msg'] = "未知错误";
return $status;
}
}
}