Facebook4J支持交换访问令牌

时间:2013-08-16 12:25:46

标签: facebook oauth facebook-access-token

我正在寻找一种方法来交换短期访问令牌,以便在我们的后端使用长期访问令牌,如Facebook here所述。如何用facebook4j做到这一点?

2 个答案:

答案 0 :(得分:1)

我做了类似这样的事情来交换新令牌的旧令牌:

private AccessToken refreshToken(Facebook facebook, AccessToken currentToken) throws Exception {
    String clientId = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTID);
    String clientSecret = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTSECRET);

    Map<String, String> params = new HashMap<String, String>();
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("grant_type", "fb_exchange_token");
    params.put("fb_exchange_token", currentToken.getToken());

    RawAPIResponse apiResponse = facebook.callGetAPI("/oauth/access_token", params);

    String response = apiResponse.asString();
    AccessToken newAccessToken = new AccessToken(response);

    facebook.setOAuthAccessToken(newAccessToken);

    return newAccessToken;
}

我认为这可以在每次登录后完成,因此即使访问令牌仍然有效,也会刷新访问令牌 - 您只需获得具有60天有效期的新令牌。

您怎么看?

答案 1 :(得分:0)

我正在扩展Facebook课程。他们提供的方法不起作用。所以我写了另一个函数,它确实提供了一个长期存在的令牌,但它在某种程度上是无效的(我尝试使用token_debug测试新令牌并试图用它生成client_code)!如果我能解决这个问题,我会更新你的。如果你能解决,请更新我。

请记住我没有清理代码,因为我还在写它。

public function GetExtendedAccessToken()
{
    //global $CONFIGURATIONS;
    //$info=$this->api($path,'GET',$args);//doesn't work as api overrides method to post

    $string=file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".$this->getAppId()
                            ."&client_secret=".$this->getAppSecret()
                            ."&fb_exchange_token=".$this->getAccessToken()
                            ."&grant_type=fb_exchange_token"
                            ."&redirect_uri=".$redirectUri);
    var_dump($string);
    $tokenInfo=explode('&',$string);

    $exAccessToken=str_replace('access_token=', '', $tokenInfo[0]);
    $expiresAt=str_replace('expires=', '', $tokenInfo[1]);
    echo "expires in ". (time()-$expiresAt);
    var_dump($exAccessToken);     
    return $exAccessToken;  
}

现在有效。有时我因为没有提供redirect_uri而收到错误。