offline fb posting not working - php

I have to post on a users wall when he is offline. I went through number of posting and checked the code written below seems ok and also not throwing error and complete successful yet I am unable to see posting on users wall. Pl help.
$facebook = new Facebook(
array(
'appId' => "446262598768110",
'secret' => "<REMOVED>",
)
);
$facebook->setAccessToken("<REMOVED>");
//create message with token gained before
echo " lets try posting";
$access_token = $facebook->getAccessToken();
$user_id = $facebook->getUser();
echo "\ndone3..... $access_token.-----.$user_id.----new\n";
$post = array(
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api("/me/feed", 'GET', $post); //have tried both Post and Get method but result remain same

offline access was removed quite a few months ago. also, you do have to "POST" to facebook graph, everytime you want to publish something.
without seeing the result of the facebook graph, it's kind of impossible to help you at all.
nevertheless: double check, that you're using the correct access token. you have to extend the short lived access tokens by your own (https://developers.facebook.com/docs/howtos/login/extending-tokens/), so that the access token itself is still valid when you want to post by cron-job.
if you're trying to post by using the app access token, you can't use "/me/feed" at all.

Related

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use

Facebook social graph API call for authenticated user

I'm trying to grab data about a user in Facebook that can only be fetched if the app is authenticated (for example /likes).
However, I can't seem to grab this data despite the fact that the user has authenticated the Facebook app (and the applicable specific permissions). I can only get data from a public context.
I'm assuming I must be missing some sort of authentication step, but I can't figure out how. When I call $fb->getAccessToken(), it returns a string value, so it seems like it does get an access token for making requests. I see some solutions to force the user to click on a login URL to authenticate, but hasn't that already been done if they have authenticated the FB dialog previous (via Javascript)?
Besides that, I need the script to run without any input from the user.
Current code:
$fbConfig = array(
'appId' => 'xx',
'secret' => 'xx',
);
//get facebook configuration parameters defined in admin backend
$fb = new facebook($fbConfig);
$access_token = $fb->getAccessToken();
$fbUid = '123456789'; // Known Facebook User Id
$likes = $fb->api('/' . $fbUid . '/likes&access_token=' . $access_token);
var_dump($likes);
// Result is always: array(0) { }
Here you just want to get a likes of user of your application, i m giving you some code which have been created from me and it's working, i test it. you don't have need to get access token because it will be taken at every time.
<?php
set_time_limit(0);
include_once '../src/facebook.php';
$config=array(
'appId'=>"xxxxxxx",
'secret'=>"xxxxxxx",
'cookie'=>true
);
$facebook = new Facebook($config);
$user=$facebook->getUser();
$accessToken=$facebook->getAccessToken();
$likes=$facebook->api('/me/likes');
var_dump($likes);
?>
Here, set time limit=0 because it'll take more time to get a every likes of user.

Post to Facebook Page Wall without logged in user

I have a Facebook app that I want to use to post on my customer's Facebook Page Walls on their behalf. I have it setup now so that when they authenticate my app I get the Access token, but when I go to post to the wall I am getting the following error: "OAuthException: Error validating access token: The session is invalid because the user logged out."
How can I post from my script without being logged in?
Here is my code:
include_once('fb-php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
try {
$page_id = '215133535279290'; //page id of the customer's facebook page
$args = array(
'access_token' => 'XXX', //access token received when user authenticated app
'message' => 'A test message'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} catch (FacebookApiException $e) {
echo "Error:" . $e;
}
The new facebook API has what is called an extended access token (it replaces offline access: https://developers.facebook.com/roadmap/offline-access-removal/ I think) which I believe lasts upto 60 days (or something like that). To use it simply get the access token when the logs in through your website:
$token = $facebook->getAccessToken();
Save it to Db and use this token later:
$facebook = new Facebook();
$facebook->setAccessToken($accessTokenFromDB);
Then you should be able to continue as though the user is logged in.
As for the user being logged out part, make sure you are using the latest version of the API and not an old version and also make sure the stuff under the "Scenario 2: If you have been previously requesting offline_access - updated 4/30/2012" heading of the page I linked.
You could carry on using offline_access until 3rd of October, but then why if it's being turned off for real in 2 months time and would have to rewrite your code.
Get the publish_stream extended permission. Once you have this permission you can post feed stories using your app access token while the user is offline. There is no need for offline_access permissions or saving and using a user access token in this scenario.

Access token on facebook is invalid - even after making it

I'm writing a facebook application in PHP with the facebook SDK.
The important parts in my code are:
$facebook = new Facebook(array(
'appId' => $ApplicationID,
'secret' => $ApplicationSecret,
'cookie' => true, // enable optional cookie support
));
$user = $facebook->getUser();
$post = $facebook->api('/' . $user . '/feed', 'post', array(
stuff
));
$_SESSION['finish'] = false;
$_SESSION['inside'] = 'yes';
$_SESSION['uid'] = $user;
$token = $facebook->getAccessToken();
echo 'Access token: ' .$token;
$_SESSION['friends'] = $facebook->api('/me/friends?access_token'.$token);
You can see I am echoing the access token.
At first, I haven't added the access_token into the query - I just added it for checking.
The problem is that the last like (with the /me/friends/) throws an exception:
OAuthException: An active access token must be used to query information about the current user.
Although I did a login, and the feed post did work (I checked at my wall, it's there). Then, my try catch block handles the exception by redirecting to the login link, this way:
catch(Exception $e) {
$login_url_params = array(
'scope' => 'stuff',
'fbconnect' => 1,
'redirect_uri' => $ApplicationURL
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
echo ("EXCPETION! " . $e . "<script> top.location.href='" . $login_url . "'</script>");
exit();
}
The code writing the exception is obviously only for debugging purposes.
Well, the first time I run the application a similar code is executed by a if(!$user) condition. Then it asks for my permission and I give it. Then, again, it says the access token is invalid (but does post to my wall).
Please note that I've compared the access_tokens, and even after removing the application and doing it all again - it stayed the same.
This is very awkward behavior and I fail to understand it. May anyone please shred some light on this?
Edit: For some weird reason, the token doesn't change even after going to a different user. But the post on the wall is still made... (And the exception thrown when accessing the friends list)
For some weird reason, the token doesn't change even after going to a different user. But the post on the wall is still made... (And the exception thrown when accessing the friends list)
That sounds to me as if you don’t actually have a user currently logged in, so the SDK is just using your app access token, which is always the default token it will use before it receives another, more “specific” one.
What format does your access token have – does is look something like your_app_id|your_app_secret or your_app_id|some_random_characters? If it’s starting with your app id, it’s most definitively an app access token.

Post to facebook page wall as a page

I want to post to facebook page wall as a page using PHP. I've got access_token by below links.
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=123456789&redirect_uri=http%3A%2F%2Fmysite.net&scope=publish_stream,manage_pages,offline_access
https://graph.facebook.com/me/accounts?access_token=...
I'm using this simple code:
$appid = "";
$secret = "";
$pageid = "";
$access_token = "";
require_once("facebook-php-sdk/src/facebook.php");
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret
));
try {
$args = array(
'access_token' => $access_token,
'message' => 'Test',
'link' => 'http://www.test.com',
'description' => 'Test'
);
$post_id = $facebook->api("/$pageid/feed","post",$args);
} catch (FacebookApiException $e) {
error_log($e);
}
And that's the error I'm getting:
OAuthException: (#200) Posts where the actor is a page cannot also include a target_id
But posting /me/feed won't work neither. All solutions I've googled don't work anymore, official documentation didn't help. I got it working when posting as a user (not a page) and with javascript api (required 'share' click action by a user).
Anyone knows the solution for automatic post to a fb page as a page? Spent couple of frustrating days trying to figure it out -_-
Thanks,
A.
I've had the same problem. The reason was that I was an admin of more than one page, and I tried to post with the token of another page.
Pages cannot post to user's walls (that's why you're getting the OAuthException that says "as a page, you cannot set the target_id"). You'll have to first create an application and get the user's permission (publish_stream) to post to their feed via said app.
I assume you have some knowledge of app and how posting work.
1.You have to get Page access token and use this on array.
2.you use this
"/$pageid/feed"
try use this
$facebook->api($pageID . '/feed','POST'
Thanks...

Categories