如何知道访问令牌是否在Google Api PHP中过期

Rob*_*tan 2 php curl google-api access-token

我怎么知道我的访问令牌是否已过期.

我正在使用try和catch

try {
$result = file_get_contents('https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token='.$accesstoken);
print_r($result);
}
catch(Exception $e){
echo "Get new token";
}
Run Code Online (Sandbox Code Playgroud)

但仍然从file_get_contents获取错误然后打印"获取新令牌"

如果我想使用卷曲

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token='.$accesstoken);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

那么我该怎么做才能在这里发现错误?

//if error because access token is invalid,
  do here

// my fixed solution

 $response= json_decode($result);
 if($response->error){ // if result has errors
   echo "Get new token";
 }
Run Code Online (Sandbox Code Playgroud)

FxI*_*III 12

探究这个网址:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
Run Code Online (Sandbox Code Playgroud)

会给你:

{
  "audience":<your_client_id>,
  "user_id":<user_id_if_userinfo.profile_was_authorized>,
  "scope":"<authorized_scope_1> <authorized_scope_1>",
  "expires_in":<time_to_live>
}
Run Code Online (Sandbox Code Playgroud)

或错误:

{"error":"invalid_token"}
Run Code Online (Sandbox Code Playgroud)