How To Get Access Token For Publishing Action On Timeline

By | April 1, 2012

In my earlier tutorial on How to publish actions on timeline i showed you how to get access token manually in step 3, but the problem with this method is that the access token will expire after every two hours and you have to copy the token again and again.

To solve this problem i found this tutorial in Facebook developers blog which handles the following issues in which access token become invalid or expired.

Note: By default open graph settings access token is not necessary for publishing on users timeline if the action is for the same page from where it is triggered otherwise its necessary to have access token for publishing.

Token expires

{
error: {
type: “OAuthException”,
message: “Session has expired at unix time
SOME_TIME. The current unix time is SOME_TIME.”
},
}

User changes his password

{
error: {
type: “OAuthException”,
message: “The session has been invalidated because
the user has changed the password.”,
},
}

User de-authorizes your app

{
error: {
type: “OAuthException”,
message: “Error validating access token: USER_ID
has not authorized application APP_ID”,
},
}

User logs out of Facebook

{
“error”: {
“type”:”OAuthException”,”message”:”Error validating
access token: The session is invalid because the
user logged out.”
}
}

Solution

So the code below is the solution for all the issues listed above.

<?php
$app_id = “YOUR_APP_ID”;
$app_secret = “YOUR_APP_SECRET”;
$my_url = “YOUR_POST_LOGIN_URL”;

// known valid access token stored in a database
$access_token = “YOUR_STORED_ACCESS_TOKEN”;

$code = $_REQUEST["code"];

// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url=”https://graph.facebook.com/oauth/access_token?client_id=”
. $app_id . “&redirect_uri=” . urlencode($my_url)
. “&client_secret=” . $app_secret
. “&code=” . $code . “&display=popup”;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}

// Attempt to query the graph:
$graph_url = “https://graph.facebook.com/me?”
. “access_token=” . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);

//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== “OAuthException”) {
// Retrieving a valid access token.
$dialog_url= “https://www.facebook.com/dialog/oauth?”
. “client_id=” . $app_id
. “&redirect_uri=” . urlencode($my_url);
echo(“<script> top.location.href=’” . $dialog_url
. “‘</script>”);
}
else {
echo “other error has happened”;
}
}
else {
// success
echo(“success” . $decoded_response->name);
echo($access_token);
}

// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>

Now your publish action code(used in step 4 of How to publish actions on timeline tutorial) will be slightly different from the previous code because in this code instead of putting token manually you will get automatically from above.

<script type=”text/javascript”>
function read()
{
FB.api(‘/me/onlytipsandtricks:read_’ +
‘?article_=http://onlytipsandtricks.com/fbapps/fbonlytipsandtricks/test.html&access_token=<?echo $access_token;?>’,'post’,
function(response) {
var msg = ‘Error occured’;
if (!response || response.error) {
if (response.error) {
msg += “\n\nType: “+response.error.type+”\n\nMessage: “+response.error.message;
}
alert(msg);
}
else {
alert(‘Post was successful! Action ID: ‘ + response.id);
}
});
}
</script>

Solution for Infinite loop

Some people may face infinite loops while using the above code for handling expires access token, if you face the same problem you can use the following code but it requires Facebook PHP SDK.

<?php
// Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
require (‘php-sdk/facebook.php’);

define(‘FACEBOOK_APP_ID’,”Your app id “);
define(‘FACEBOOK_SECRET’,”Your app secret “);
define(‘REDIRECT_URI’,”Your app Namespace “);
define(‘PERMISSIONS_REQUIRED’, “publish_actions”);
$user = null;

$facebook = new Facebook(array(
‘appId’ => FACEBOOK_APP_ID,
‘secret’ => FACEBOOK_SECRET,
‘cookie’ => true
));

$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.

if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* – redirect_uri: the url to go to after a successful login
* – scope: comma separated list of requested extended perms
*/

$login_url = $facebook->getLoginUrl($params = array(‘redirect_uri’ => REDIRECT_URI,’scope’ => PERMISSIONS_REQUIRED));

echo (“<script> top.location.href=’”.$login_url.”‘</script>”);

} else {
// if the user is already connected, then fetch access_token and user’s information or show some content to logged in user.
try
{
$access_token = $facebook->getAccessToken(); // Gives you current user’s access_token

$user = $facebook->api(‘/me’); // Gets User’s information based on permissions the user has granted to your application.

} catch(FacebookApiException $e){
// Print results if you want to debug.
}

}
?>

The publish action code will remain the same as above.


Related Posts:



Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

9 thoughts on “How To Get Access Token For Publishing Action On Timeline

  1. Arif

    Hi !
    Thanks for sharing the code for getting the access token. Can you please tell me how we can extend the its expiry time. Let my user has used the app a week ago . Now If I want to publish something on his wall, I need his access token which is quite possible that accesstoken has become invalid or expired. If you have solution for this problem then please share it.

    Regards

    Reply
  2. Dracik

    Hi Hasnain, u can post here screen of setting ur apps ?
    Thanks

    Reply
    1. Hasnain Post author

      Which type of setting? Basic, Auth Dialogue or Advanced.

      Reply
    1. Hasnain Post author

      My POST_LOGIN_URL was the same page. Post_Login_URL means the URL where you want user to be redirected after authentication.

      Reply
  3. Mohammed Munawar

    $my_url = “YOUR_POST_LOGIN_URL”;

    // known valid access token stored in a database
    $access_token = “YOUR_STORED_ACCESS_TOKEN”;

    May I know what is “YOUR_POST_LOGIN_URL” & “YOUR_STORED_ACCESS_TOKEN” ?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *