Since Facebook is now using OAuth 2.0 to authenticate apps to access user information. the SDK of Facebook has provided developers some useful functions to get authentication done. For example, in PHP SDK, there are getAccessToken(), getLoginUrl() etc. But unfortunately, for me I cannot use getAccessToken() method to get the user access token, it only returns me the app access token. Finally I gave up this approach to get access token for the time being. I may later retry this approach if I have time.
Today I show you another way to get the access token, which is explained on Facebook's developer website. We should use the signed_request . Since OAuth is a two way authentication mechanism, the first time, when the canvas page is loaded, a signed_request will be POSTed to the canvas page, user can use $_REQUEST["signed_request"] to access this object. At the first time,, the signed_request will contain limited information, then the page will be redirected to the Facebook login page and authorization page. Once the authorization is done, the page will be redirected to the redirect_url and this time it will again send a signed_request object to the canvas page, and now the signed_request object will contain the access token.
An example code snippet below :
define('APPID','XXX'); define('APPSECRET','XXXX'); define('CANVAS_URL','http://apps.facebook.com/appname/'); $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . APPID . "&redirect_uri=" . urlencode(CANVAS_URL)."&scope=user_relationships,user_relationship_details"; $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = @explode('.', $signed_request, 2); //DECODE THE DATA WHICH CONTAINS THE ACCESS TOKEN $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); } $access_token=$data["oauth_token"];
The code above is quite straightforward, after getting the $data object, it will check whether the user_id exists or not, if it doesn't exist, it will be redirected to the $auth_url page. After authorization, the page will be redirected back to the CANVAS_URL page and now the user_id should have been set and the access token is available.
Now we can use access_token to get some information of the user using the Graph API . One example :
$user_str=file_get_contents('https://graph.facebook.com/me?access_token='.$access_token); $user=json_decode($user_str,true); var_dump($user);
Ok, it's done. Later I will explain how to use FQL to get gender of a friend.