2012-01-21 39 views
2

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

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

但仍从的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); 

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

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

什么是你的问题?你是否想知道什么时候要求新的访问令牌或如何申请新的访问令牌? – Shadow

+0

@shadow是的,我想知道我的访问令牌是否已过期。我用我的解决方案编辑了我的帖子。请随时提出任何建议。 –

回答

12

探测这个网址:

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

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

+1

我非常怀疑'file_get_contents()'抛出*任何* HTTP状态码的异常。 – ThiefMaster

+0

我已经尝试了可以​​捕获异常的try和catch,但是如果我在“try {}”上使用file_get_contents,它将不会在未经授权的情况下进入catch异常。 –

+0

所以我读了关于file_get_contents(),并且它从不抛出HTTP错误。如果您无法加载数据,则结果的值为FALSE。这意味着您应该使用其他功能,因为Google API调用可能由于多种原因而失败。为什么不在此处使用Google API PHP客户端库http://code.google.com/p/google-api-php-client/source/browse/ – Shadow

相关问题