2012-01-21 100 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

相關問題