I am using the following URL to get a Facebook Auth Token for managing Pages and Page Events...
https://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECTURL&scope=manage_pages,create_event&response_type=token
This goes through the authorization process and returns the token, which gets saved in my database. I then try to do the following to retrieve the thumbnail images of people attending one of the Page's Events...
function fbEventRSVPPhotos($eventID){
$authToken = eto_get_option('eto_auth_fbauthtoken') //pulled from database;
$json = file_get_contents("https://graph.facebook.com/" . $eventID ."/attending?access_token=" . $authToken);
$attendees = json_decode($json, true);
echo '<div class=attendee-photos>';
foreach($attendees['data'] as $attendee) {
echo '<img class="facebook-thumb toggleTooltip" title="' . $attendee['name'] . ' is attending" src="https://graph.facebook.com/' . $attendee['id'] . '/picture?type=square">';
}
echo '</div>';
}
This function works great for when I am logged in to Facebook, however once I log out I get the following...
Warning: file_get_contents(https://graph.facebook.com/MYEVENTID/attending?access_token=MYTOKEN) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in PATHTOSCRIPT on line 94
Warning: Invalid argument supplied for foreach() in PATHTOSCRIPT on line 97
And then it continues to show this PHP error even after logging back in. I essentially have to regenerate the auth token every time I log back in.
Can someone help me understand why this is happening and how to fix?
You want to destroy the session $facebook->destroySession(), not invalidate the token. Logging out is one of the ways to invalidate the token. This is the expected action.
Destroying the session will log the user out of the app but not invalidate the token. Seeing that you are saving it to a database, you are probably requesting access longer than two hours which is past the limitation of a short lived token.
Also as you are using a page you can use scenario 5 at https://developers.facebook.com/roadmap/offline-access-removal/
When a user grants an app the manage_pages permission, the app is able
to obtain page access tokens for pages that the user administers by
querying the [User ID]/accounts Graph API endpoint. With the migration
enabled, when using a short-lived user access token to query this
endpoint, the page access tokens obtained are short-lived as well.
Exchange the short-lived user access token for a long-lived access
token using the endpoint and steps explained earlier. By using a
long-lived user access token, querying the [User ID]/accounts endpoint
will now provide page access tokens that do not expire for pages that
a user manages. This will also apply when querying with a non-expiring
user access token obtained through the deprecated offline_access
permission.
Related
I want to get the each user's FB posts by commandline.
like
whitebear#bear.com
blackbear#bear.com
yellowbear#bear.com
These are my code.
$secret = 'xxxxx';
$key = 'xxxx';
$url = "https://graph.facebook.com/oauth/access_token?client_id="
. $key . "&client_secret=" . $secret . "&grant_type=client_credentials";
print $url. "\n";
$json = json_decode(file_get_contents($url),true);
var_dump($json['access_token']); // success
$url2 = "https://graph.facebook.com/me?fields=posts&access_token=" .$json['access_token'];
$json2 = json_decode(file_get_contents($url2),true);
var_dump($json2); //
Warning: file_get_contents(https://graph.facebook.com/me?fields=posts&access_token=4887415xxxxxxxxxxxxxxx): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I succeed to get the access_token, however I think it is facebook app's accesstoken?? not user's??
I think I should indicate the who is the user before loading me? api.
However how should I do?
I let every user login on web application AOuth and stored each users facebook_access_token in DataBase (but it valid a few hours????)
If you need to store a User Token, you should use an Extended User Token
You cannot get a User Token programmatically, only on user interaction with a proper login process
You can debug Tokens to see if it is an App or User Token in the Token Debugger
More Information: https://developers.facebook.com/docs/facebook-login/access-tokens/
grant_type=client_credentials generates an app token.
App access tokens are used to make requests to Facebook APIs on behalf of an app rather than a user. This can be used to modify the parameters of your app, create and manage test users, or read your apps's insights.
Some user data that would normally be visible to an app making a request with a user access token isn't always visible with an app access token. If you're reading user data and using it in your app, you should use a user access token instead of an app access token.
You can not use app tokens to access me or fetch most data about individual users.
I'm working on getting a fb auth working on my site. I have code in already to get the token and store it in a session variable. On a new page I have this:
echo $_SESSION['facebook_access_token']
That puts out a long auth token that I can paste into this site :
https://developers.facebook.com/tools/explorer/145634995501895/
I paste the string in to the top Access token box and can access the fields that I asked permissions for in an earlier step.
Back to the code, I pass this line:
$response = $fb->get('/me?fields=id,name','$_SESSION["facebook_access_token"]');
and get the following:
Invalid OAuth access token.' in /{web root}/facebook/src/Facebook/Exceptions
Now what the heck is going on here? How can I troubleshoot this?
I've searched for a Laravel Facebook SDK and I found this package that works with Laravel 4.2 (my laravel app version). I use this just to get my facebook page posts but I got into a problem, my access token expires every 2 hours or in some cases because of other reasons like facebook logout, etc.
I found out that there are 2 ways to handle expired access tokens, either to extend the access token, either to request a new one using the old access token.
The questions is how to request a new access token because I store it into my database and I need to get my facebook page posts all the time?
I've followed this instructions but for me it does not work.
When I use this code:
try
{
$token = Facebook::getTokenFromRedirect();
echo "Success<br>";
print_r($token);
}
catch (FacebookQueryBuilderException $e)
{
// Failed to obtain access token
echo 'Error:' . $e->getMessage();
}
the only thing what I see on the screen is Success and that is all, it's like the $token is empty.
I've also checked Facebook Query Builder which is included into SammyK LaravelFacebookSdk and tried to use getTokenFromCanvas() insted of getTokenFromCanvas() but I get this error: Method getTokenFromCanvas does not exist.
Any idea to make this work?
By default Facebook will return a user access token that expires after 2 hours. You can extend it for a long-lived access token that'll last 60 days.
Once you obtain an AccessToken entity in Laravel Facebook SDK 1.2, you can extend it like it shows in the example:
try {
$token = $token->extend();
} catch (SammyK\FacebookQueryBuilder\FacebookQueryBuilderException $e) {
dd($e->getPrevious()->getMessage());
}
In your GitHub issue you mentioned:
What I want to achieve is to get the posts from my facebook page
You can use a page access token to grab your page posts. You can obtain a page access token from the /me/accounts endpoint.
If you use a long-lived user access token to obtain the page access token, the page access token will never expire so it's ideal to store in your database to pull posts from a page.
See more about handling access tokens. Good luck! :)
On facebook documentation page, there is written:
Facebook::getAccessToken()
Get the current access token being used by the SDK. This may be a user access token or an application access token. See the permissions page for more information on access tokens.
But there is no explanation how to force the method to return app token, not the user token. It is not exmplained nor on permission page.
Cn anybody help, how this method works?
The App access_token is usually just APP_ID|APP_SECRET. In my code, I tend to just do this:
$app_token = APP_ID . '|' . APP_SECRET;
I've this error, but not always. (I use PHP SDK, latest version).
If I'm logged into facebook and i try to register and login, then the app say it's ok!
Also if i'm not logged into facebook, the app redirect me to login url, and here it's all ok.
But sometimes the app say this exception: OAuthException: An active access token must be used to query information about the current user. and the script redirect the user to loginUrl with a loop-redirect (because the access token isn't valid and user need always of loginUrl)
In the web some say that Facebook create a duplicate of Access Token and then access token of php sdk don't is = facebook.
For fix, the user must deletes cookies, how I can fix this?
Thanks a lot for reply, if code is need reply and I'll post it, have a good day! :)
Try to destroy the Facebook session, then redirect the user to login URI if you receive this error, this way you will get a fresh access token.
Notice: Access token expire after a very short, you can get a long living access token. The latest PHP SDK contains a public function called : setExtendedAccessToken()
you can call this function to automatically exchange the 2-3 hours living access token for a 60 days access token
Eg:
try {
$user = $this->facebooknew->api('/me');
$this->facebooknew->setExtendedAccessToken();
$access_token = $this->facebooknew->getAccessToken();
}
catch(FacebookApiException $e){
$this->facebooknew->destroySession();
header('Location: ' . $this->facebooknew->getLoginUrl($params));
//echo $e;
}