Using facebook off-line access to post on user's wall
Notice: This article is updated (july 2011) after initial publish because of changes in facebook API.
This is simplified and robust example how you can post on user's wall when she/he is not currently logged in or not using your application. It's achieved by by using stored access_token. Access tokens are needed to make calls on facebook graph api. Before that user has to allow offline_access permissions to your app. But let's take it step by step.
Also you may check out my previous post where I shared simple example of facebook iframe app with new php-sdk API. That would be good starting point if you are not familiar with facebook app development yet. And here is example app which uses this offline access permission.
This article uses $facebook object in examples. So before trying any of this out, create new facebook instance at the beginning of the script. It should look something like this.
//add php-sdk require './facebook.php'; //Create facebook instance. $facebook = new Facebook(array( 'appId' => 'application ID', 'secret' => 'application secret', 'cookie' => true, ));
Authorising url
First we need user to accept off-line access. When creating authorise url for your app, add 'offline_access' permission along others. This will grant permission to make such calls. This specific url is just a example but important part is here is req_perms parameter.
$loginUrl = $facebook->getLoginUrl(array( 'canvas' => 1, 'fbconnect' => 0, 'req_perms' => 'publish_stream,offline_access', 'next' => 'APP CANVAS URL IN FACEBOOK', 'cancel_url' => 'URL WHERE TO REDIRECT WHEN ACCESS NOT GRANTED', ));If using newer verions of facebook PHP SDK (v.3.0.0) (and up) use next one instead. Notice, that req_perms changed to scope
$loginUrl = $facebook->getLoginUrl(array( 'canvas' => 1, 'fbconnect' => 0, 'scope' => 'offline_access,publish_stream' ));
Getting the token
If session is established, you can obtain it from session variables. That is all. Now you can store it in database or wherever you like and use it in your script when needed.
//get session
$session = $facebook->getSession();
//print out token stored in session
//using this you can do api calls even if
//user is not currently interacting with your app
if ($session) {
echo $session['access_token'];
}
And if using newer verions of facebook PHP SDK (v.3.0.0) (and up) use next one instead
$user = $facebook->getUser();
if($user){
echo $facebook->getAccessToken();
}
Using token for posting
Now the actual offline posting part. This is very simple. You only need that token gained earlier. This example shows how to post message on user's wall and get user's data. Also $res variable (array) will hold post ID if successfully posted. Code would be following.
//create message with token gained before
$post = array(
'access_token' => 'TOKEN HERE',
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);
//For example this can also be used to gain user data
//and this time only token is needed
$token = array(
'access_token' => 'TOKEN HERE'
);
$userdata = $facebook->api('/me', 'GET', $token);
Done! Nothing to add.
Categories:
Programming
- Facebook
How do we actually post message on user wall? the line "$res = $facebook->api('/me/feed', 'POST', $post);"
will only store some data returned by api. Can you please explain little more with some more code sample.
"Fatal error: Uncaught OAuthException: Error validating access token. thrown in facebook.php on line 543"
Any ideas? Do I need to store the "&expires_in=0" from the access_token somewhere?
I think you can do it using "/YOUR_PAGE_NAME_OR_ID/feed" instead of "/me/feed" when posting used in my example.
Replace YOUR_PAGE_NAME_OR_ID with your page ID or alias.
So posting query becomes something like this:
$res = $facebook->api('/YOUR_PAGE_NAME_OR_ID/feed', 'POST', $post);
I tried both the things ..But it's not working.. I have send u the code Pls check it.
Check out article http://developers.facebook.com/docs/authentication/ There is a subheading "Page Login". I would start there.
Now i want to post the image in the wall. Can u Please send me the code ...Thanks in Advance.
Something like this would work ...
$post = array(
'access_token' => 'TOKEN HERE',
'picture' => 'picture url here',
'link' => 'url',
'name' => 'title',
'caption' => 'caption',
'message' => 'message',
'description' => 'description'
);
$res = $facebook->api('/me/feed', 'POST', $post);
I have a question, everything works fine but the content that i add to facebook via php (wall post, new albums, images, etc.) are all only visible by me. Does someone know why ?
This post helps me a lot ..
Information is very clean and neat.
Thanks
{ Web-Farmer }
Fatal error: Uncaught OAuthException: (#15) The method you are calling must be called with an app secret signed session thrown in______
As in the code : "/me/feed/"...
that meant that the user entered the script gets msg 2 feed.
I want to make an script that will run weekly, and than post on the user's feed, without the need of him to enter the app.
how to run the script weekly is no prob, but how to post to the offline user is.
PLEASE help...
thanks Tzook
I hope it helps :)
I am trying to create a cron that updates multiple users status' using the access tokens I have stored in mysql.
I feel that modifying something like this would be where to start:
//Retrieve user access_token from database
$results = mysql_query("SELECT access_token FROM demographic ORDER BY access_token ASC");
while($access_token_array = mysql_fetch_assoc($results)) {
$list_access_token[] = $access_token_array['access_token']; // to store results in an array
}
$comma_separated = implode(",", $list_access_token);
//print_r ($comma_separated);
//Array to post to wall
$post = array(
'access_token' => $comma_separated,
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//Actual post to wall
$facebook->api('/me/feed', 'POST', $post);
any suggestions would be appreciated.
thanks a lot.
I considered using php if, [like if( thursday = post on wall, else don't] sort of thing. but It would have to be open to know wouldn't it?
To: smiles, Use cron for that.
I can post status in the wall, but when use cron not work... Already try everything and cannot to use cron for automatize. Can be anything permission? if not use cron work!
My code:
api_client->session_key = FB_SESSION;
$fetch = array('friends' =>
array('pattern' => '.*',
'query' => "select uid2 from friend where uid1={uid}"));
echo $facebook->api_client->admin_setAppProperties(array('preload_fql' => json_encode($fetch)));
$sql = $base ->query('SELECT * FROM wall WHERE DATE_FORMAT( data_agendada, "%H:%i" ) = DATE_FORMAT("' . date('Y-m-d H:i:s') . '", "%H:%i") ');
while ($result = $base ->tupla($sql)) {
echo $result ['text_facebook']."";
echo "sign in";
if ($facebook->api_client->stream_publish($resultado['text_faceboon]." Testing cron"))
echo "Added on test FB Wall";
}
} catch (Exception $e) {
echo $e . "";
}
?>
I can post status in the wall, but when use cron not work... Already try everything and cannot to use cron for automatize. Can be anything permission? if not use cron work!
My code:
api_client->session_key = FB_SESSION;
$fetch = array('friends' =>
array('pattern' => '.*',
'query' => "select uid2 from friend where uid1={uid}"));
echo $facebook->api_client->admin_setAppProperties(array('preload_fql' => json_encode($fetch)));
$sql = $base ->query('SELECT * FROM wall WHERE DATE_FORMAT( data_agendada, "%H:%i" ) = DATE_FORMAT("' . date('Y-m-d H:i:s') . '", "%H:%i") ');
while ($result = $base ->tupla($sql)) {
echo $result ['text_facebook']."";
echo "sign in";
if ($facebook->api_client->stream_publish($resultado['text_faceboon]." Testing cron"))
echo "Added on test FB Wall";
}
} catch (Exception $e) {
echo $e . "";
}
?>
bcoz i am not getting $session .please help me.
Thnxx.
I want to develop a simple gift app . When the user selects a friend and send a image . The selected image should be posted on the sender and receiver wall. Do u have any idea about this . It will be so useful for me please help if u know . Thanks in Advcance
$token,
'message' => 'message here.'
);
//Actual Post
$facebook->api('/me/feed', 'POST', $post);
}
?>
i manged it to work only for posting in my wall ??
can you help me ??
where do i put the code (php script)
in cron_job ?
tnx for the help
https://graph.facebook.com/oauth/access_token?client_id=" . Conf::$FB_APP_ID . "&client_secret=" . Conf::$FB_APP_SECRET . "&grant_type=client_credentials
very helpful! I am going to store the token in DB but I cannot find what the length is... do you know if there is a maximum access_token length stated in the OAuth 2.0 specification. I haven't found it yet.
I was going through the code but found that the 'cookie' parameter needs to be disabled, otherwise authenticating with facebook doesn't work.
'application ID',
'secret' => 'application secret',
// 'cookie' => true,
));
?>
I'm using Facebook PHP SDK 3.0.1
Have you made a tut similar to this for twitter and php?
to bRy:
I haven't done it myself yet. So you probably are better off by googling around a bit. I am almost sure it is very much discussed topic.
I have a problem ..
$ token = array (
'access_token' => 'TOKEN HERE'
);
$ userdata = $ facebook-> api ('/ me', 'GET', $ token);
This code creates me a 500 error on the server, it can be?
I'm trying to get information from a user with a token.
Thanks
The link is posted on the wall, no problem there. But when you click on it nothing will happen. If another FB user is clicking on that link facebook is asking that user to give offline access to the app?
Does anybody have an idea how to prefend this?
Its up to you what you display for user who accesses your application. For people who have not allowed you app yet it will ask permissions and its normal.
Yes- trough app it's possible. Current blog post is one example of that.
But trough page- as far as I know it's not possible. Also not seeing such token @ http://developers.facebook.com/docs/reference/api/permissions/
very easy and useful post, thanks alot :)
Thanks! all it's Clear!
'secret' => 'my sec',
'cookie' => true,
);
$facebook = new Facebook($config);
$facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'offline_access,publish_stream'
));
$user = $facebook->getUser();
if($user){
$mytoken=$facebook->getAccessToken();
}
$post = array(
'access_token' => $mytoken,
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
$res = $facebook->api('/me/feed', 'POST', $post);
?>
Hello this is my code but its not run while i use offline_access ,but i get the access token its mean the $facebook->api('/me/feed', 'POST', $post) does't work please someone help me its urgent
I would like to post on the company wall but the script still posting on my wall. The company wall is still empty.
How can i grand privilegies to to application, to posting on my wall? I filled /COMPANY_ID/feed (replaced COMPANY_ID), but still posting on my wall.
Could you give me some help please?
Thank you
here is my code
$facebook->api('/me/feed', 'POST',array('access_token'=>$access_token,'link' => 'www.funmx.com','message' => 'myposting'));
I looked on the autorization.
Everythink is ok, but when I admin more company pages, I dont want to grand privileges to all this pages.
Is it possible to choose one, where can I post on the wall?
Thank you much
im getting errors on my log message
OAuthException: Error validating access token: Session has expired at unix time (number) . The current unix time is (number).
ive readarticles about this and i found out FB team are makingchanges with there apps. and ive read, the error is when a user is offline
everytime i make a job i get this
how can i edit FB apps so it can post to offline users
thanks