【问题标题】:How to know if Access Token expires in Google Api PHP如何知道访问令牌是否在 Google Api PHP 中过期
【发布时间】:2012-02-15 17:08:22
【问题描述】:

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

我正在使用 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 得到错误,然后打印“获取新令牌”

如果我想使用 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";
 }

【问题讨论】:

  • 您的问题是什么?你想知道什么时候要求新的访问令牌或如何要求新的访问令牌?
  • @shadow 是的,我想知道我的访问令牌是否已过期。我已经用我的解决方案编辑了我的帖子。请随时提出任何建议。

标签: php curl google-api access-token


【解决方案1】:

捕捉异常。检查 HTTP 错误代码是否为 401(未授权)。这意味着您的访问令牌已过期,并且是您刷新访问令牌的时间。

【讨论】:

  • 我非常怀疑file_get_contents() 会为 any HTTP 状态码抛出异常。
  • 我已经尝试过捕获异常的 try 和 catch,但如果我在“try{}”上使用 file_get_contents,如果未经授权,它不会进入 catch 异常。
  • 所以我阅读了有关 file_get_contents() 的内容,实际上它从不抛出 HTTP 错误。如果您无法加载数据,则结果的值为 FALSE。这意味着您应该使用其他一些功能,因为 Google API 调用可能由于多种原因而失败。为什么不在这里使用 Google API PHP 客户端库code.google.com/p/google-api-php-client/source/browse
【解决方案2】:

探测这个网址:

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

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2014-05-13
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2012-11-30
    • 2018-04-26
    • 1970-01-01
    相关资源
    最近更新 更多