2012-01-24 18 views
17

我使用Koala寶石上的Ruby on Rails應用程序續訂Facebook的訪問令牌與考拉

而且我對我通過使用考拉的數據模型下面的代碼:

@graph = Koala::Facebook::GraphAPI.new(token_secret) 
friends = @graph.get_connections("me", "friends") 

其中token_secret來自我的users表的一個字段,保存在登錄名上。

它工作正常,但一對夫婦分鐘後,我得到:

Koala::Facebook::APIError (OAuthException: Error validating access token: Session has expired at unix time 1327438800. The current unix time is 1327442037.): 

我找到了方法來更新此令牌與來自Facebook JS SDK方法的前面,但這種方法在那裏我得到的名單朋友在控制器上被調用。

如何使用考拉續訂token_secret?這可能嗎?

+0

看到這個問題http://stackoverflow.com/questions/6710425/how-do-you-renew-an-expired-facebook-access-token – Gazler

回答

0

如果您嘗試獲取Facebook網站應用程序的oauth_token,則需要使用基於重定向的Oauth進程。這有點複雜。對於一個畫布應用程序,它更簡單。您仍然可以對畫布應用使用基於重定向的流程,但最好從signed_request解析它。

每次用戶在Facebook上加載您的應用程序時,它們都會以「signed_request」參數登錄您的第一頁。這個加密的字符串必須在你的控制器中用一個考拉對象進行解析。從結果中,你可以得到一個新的oauth_token,它應該在兩個小時內有效。這是我如何做到的。

#Create a new koala Oauth object. 
oauth = Koala::Facebook::OAuth.new(APP_ID, APP_SECRET) 

#Get the new oauth_token from the signed request. 
your_new_oauth_token = oauth.parse_signed_request(params[:signed_request])["oauth_token"] 
+0

這就是問題所在,應用程序不在Facebook內部加載,它只是一個使用Facebook登錄的Web應用程序,並且在某些時候我使用考拉來檢索朋友的名單,但如果我不加載任何其他頁面在我的應用程序,但「朋友」頁e令牌不會更新,因爲我通過FB.getLoginStatus(...)''''做這個' –

19

我想我會回答這個,因爲這是我剛剛遇到的需要做的事情。

考拉添加交換訪問令牌支持前一段時間,在這裏: https://github.com/arsduo/koala/pull/166

所以我的用戶模型現在也有類似以下內容:

def refresh_facebook_token 
    # Checks the saved expiry time against the current time 
    if facebook_token_expired? 

    # Get the new token 
    new_token = facebook_oauth.exchange_access_token_info(token_secret) 

    # Save the new token and its expiry over the old one 
    self.token_secret = new_token['access_token'] 
    self.token_expiry = new_token['expires'] 
    save 
    end 
end 

# Connect to Facebook via Koala's oauth 
def facebook_oauth 
    # Insert your own Facebook client ID and secret here 
    @facebook_oauth ||= Koala::Facebook::OAuth.new(client_id, client_secret) 
end 
+0

我會嘗試一個,看起來非常好。但在我嘗試之前,我仍然有幾個問題:1.我使用Graph API'@graph = Koala :: Facebook :: API.new(accessToken)'......我可以在那裏使用'exchange_access_token_info'或者我應該有使用'Koala :: Facebook :: OAuth'來代替? –

+0

'exhange_access_token_info'在'Koala :: Facebook :: OAuth'上定義,所以你必須在那裏使用它。 – sevenseacat

+6

我想指出,在上面的代碼(當我剛剛考拉考拉1.6.0時),new_token ['expiry']是一個整數秒的字符串,直到令牌過期...你可能需要將其轉換爲令牌將在保存時過期的時間。類似於(Time.now + new_token ['expires'] .to_i) HTH –