views:

2745

answers:

2

When a user visits my site which contains a facebook app the first time, it requires him to allow it and he gets promted to do that, then I get the code which I can convert to an access_token. So far so good.

But how do I get the token once the user has already visited the site? As long as this token form the first time is active everything is fine. But how do I get another token when the user had already allowed the app a week ago and is only visiting my page again?

A: 

I use the cookie method to store the access_token on the user's computer.

FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});

In your facebook.php file you need to set cookieSupport to true then:

private $cookieSupport = true;

Or use the get_facebook_cookie function found here: Single sign-on with the JavaScript SDK

The access_token is then stored in a cookie called "fbs_APPID" (with expire). If you want the cookie to last more then a couple of hours you need to ask the extended permission 'offline_access':

Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.

Jens
So the only way to recognize a user is to save the token in a cookie?
hoktar
If you inspect the getSession() function inside facebook.php you see that they build the session from $_GET or $_COOKIE.
Jens
A: 

using php

session_start();
// Create our Application instance.
$facebook = new Facebook(array(
                'appId' => FACEBOOK_APP_ID,
                'secret' => FACEBOOK_APP_SECRET,
                'cookie' => true,
                'domain' => 'example.com'

));

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
    try {
        $uid = $facebook->getUser();
        $me = $facebook->api('/me');
        $_SESSION['me'] = $me;
        $_SESSION['uid'] = $uid;
        $_SESSION['session'] = $session;

    } catch (FacebookApiException $e) {
        error_log($e);
    }
}

you can reference the access_token via $_SESSION['session']['access_token'] within your app,, for more theres tutorials over at fbdevtutorials.com

Phil

related questions