Using facebook off-line access to post on user's wall
Important notice! There was change in API in May 1, 2012. "offline_access" permission was deprecated. Quote: "For existing apps, there are no changes required for your app, but you should consider using the new endpoint". I have to re-write or add fallow up articles to my posts about "offline_access" permission about that suggestion/change. I also have to modify my example and live apps. But AFAIK - there is no hurry, because nothing gets broken that day. Read more about it here
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
The user enters the application.
sample access_token: EYDMJF54FGDFG
Facebook user closes the session and re-enters.
new sample access_token: JGJGJ6FGHFB
Why is it changing?
Can anybody help me please..???
I have a fan page on the facebook- https://www.facebook.com/YouarewithmeDear
and I want to upload a gif/animated picture on the wall,
how is it possible,Can any body tell me please.
Here is a example of animated pictures on the wall
https://www.facebook.com/pogo.official
Can anybody help me please??/
Is the possible with live stream, ui:fb stream
or how?
Thanks in advance
actually I want to post Gif/animated picture on the wall of a fan page(the name of the page is https://www.facebook.com/YouarewithmeDear) so anybody can Like and share them .
how is it possible to post any Gif/animated picture on wall, can you please tell me. Because directly we can not upload the GIF/Animated picture on the fan page wall.
I saw on one page 3 days ago(Here you can see-https://www.facebook.com/2share,
with this heading-
There is a cat, who is moving his face left and right.
hahaha x'D HipHop Cat :D
Share LOL! )
when i select this picture and i saw selection source,
this is showing in html or may be java scrip
hahaha x'D HipHop Cat :D
hahaha x'D HipHop Cat :D
You should google your problem instead. Doesn't that answer your question?
http://melroz.blogspot.com/2011/05/loading-animated-gif-onto-your-wall-in.html
https://www.facebook.com/pages/Joel-Nagy-com/126165237425344?sk=app_7146470109.
this is an animated picture, If i want to post it to my page's wall with my page's link .how i can add this?
I listen from my friend that there is a some option on facebook developer page like- ui:fb stream, feed, live stream etc, where i can creat an application for gif/animation pictures.
please tell me how i can add the gif/animated picture on the wall of my fan page to show my page's fan.
Great stuff!
If I want to get status from the wall of a fan of my app.
How can I do?
instead of :
$userdata = $facebook->api('/me', 'GET', $token);
do:
$userdata = $facebook->api('ID OF THE FAN', 'GET', $token);
??
I guess there will be a trouble with the token?
Because the token will be provide for me not for the ID OF THE FAN I want?
Hope you have the answer!!
Cheers
Answer is still same.
No it's not the same question at all.
I didn't want to post a feed.
I wanted to GET status with my app from people who like my appli.
I had the answer from Facebook.
It's possible to get the message from the fan page linked with an appli BUT NOT from the wall of others.
That means I can't do what I wanted to... :-(
And how to show it to the user and its relation to these requests
Can you please tell me what exactly does it mean and how to resolve it?
die("API call failed");
to this:
die( "API call failed: ". $e->getMessage() );
to get what error/exception happened.
Another question, can I use the derived offline token to post on people's wall?
How to do that?
Check out the part "Using token for posting"
for example.
$post = array(
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$response = $facebook->api('/me/feed', 'POST', $post);
This code works perfect
Disabled" so it works. else not.
Thanks!
Please help!!
When I am posting via my app to a page,then it is only visible to me,not even manager of the page able to view.
can we send that permission user wall also ?
As you said, I post a request using the following codes:
function publishCustomAction($facebook,$url,$action,$fb_id,$access_token) {
$app_namespace=[my namespace];
$post=array('nikeshoes' => $url,'access_token' => $access_token,'message' => 'This message is posted with access token ');
$ret_obj = $facebook->api('/'.$fb_id.'/'.$app_namespace.':'.$action, 'post', $post);
return $ret_obj['id'];
}
But I got this error:
OAuthException: An active access token must be used to query information about the current user.
The access_token and fb_id is get from mysql database.
I have not idea why it happened.
help me
Thx
Etom: As your program states, there is problem with given token. Once again I can't guess what is wrong because there can be various reasons that could generate this outcome. I don't know what you have done. Where you got those tokens? Did they included "offline_access". Maybe user changed it's facebook password - and so on.
Generally you should reauthorize the user. Preferably you should use new way of doing that explained here - http://developers.facebook.com/roadmap/offline-access-removal/ "offline_access" is deprecated and should not to be used anymore.
Try debugging with help of google also.
I tested it using my FB account. and the offline access permission is required while login in my website with FB account.
Access token was written into mysql database after login:
$access_token=$facebook->getAccessToken();
I think the access token is effective because I got the same access token when I login and reauthorize again.
function publishCustomAction($facebook,$url,$action,$fb_id) {
$app_namespace='...';
$post=array('my object' => $url,'message' => 'This message is posted with access token ');
//var_dump($post);
$ret_obj = $facebook->api('/'.$fb_id.'/'.$app_namespace.':'.$action, 'post', $post);
return $ret_obj['id'];
}
$facebook->setAccessToken($access_token);
$story_id = publishCustomAction($facebook,$url,$action,$fb_id);
Fatal error: Call to undefined method Facebook::getSession()
Unable to fix this, Please help me. Thanks in advance
when a new post added publish the new post to users's of facebook application wall
Is there any way to be able to post offline?
But yes- there is a way - there is a link top of this post.
{
"error": {
"message": "This authorization code has expired.",
"type": "OAuthException",
"code": 100
}
}
i understand that code...
bt found error...
help me...
Fatal error: Uncaught OAuthException: Error validating access token: The session is invalid because the user logged out. thrown in /home/addonn79/public_html/dev/tutorial/Amruta/offline post/src/base_facebook.php on line 1238
$session = $facebook->getSession();
:(