php - 如何知道访问 token 是否在 Google Api PHP 中过期

标签 php curl google-api access-token

我如何知道我的访问 token 是否已过期。

我正在使用 try and 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";
}

但它仍然从 file_get_contents 中得到错误,然后打印“获取新 token ”

如果我想使用curl

$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);

那我应该怎么做才能捕捉到这里的错误呢?

//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";
 }

最佳答案

探测这个 url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

会给你:

{
  "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>
}

或错误:

{"error":"invalid_token"}

关于php - 如何知道访问 token 是否在 Google Api PHP 中过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8953195/

相关文章:

php - 命名空间声明中的别名命名空间,而不是 PHP 中的命名空间导入可能吗?

php - nginx fastcgi_pass 支持变量吗?

curl - 仅从 FTP 下载二进制文件的 header

c - POSTFIELD 应该是什么样子的?

php - 如何使用 Curl 从 URL 访问文件

google-analytics - Google Discovery API 请求缺少有效的 API key

PHP + Youtube API - 如何允许用户将视频上传到我自己的 channel ?

javascript - google maps api中带有图像和数字的标记

google-api - 如何在身份验证后获取 YouTube channel 名称和 URL

php - 如何让我的 div 仅在内容已满时才可滚动?