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! :)
Related
I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();
I am building a restful API (PHP) to serve iOS and Android applications and I would like to implement facebook login on both apps.
The flaw is like the following :
Clients ( ios or Android ) login with facebook and send an access_token to the restful api
verify if the access_token is authorized to use the application
If token is valid, get user data from graph.
Merge accounts and generate token for different queries.
For security purpose to avoid getting random tokens thatthey don't belong to my APP, I would like to make a test call to check if a token is authorized and valid or not ?
I know many similar questions might be already answered but none of them really give me the right answer and I don't really have experience with facebook graph.
I found this solution :
https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=SECRET_APP_ID&grant_type=fb_exchange_token&fb_exchange_token=ACCESS_TOKEN
This works somehow .. it whether give me an error, or an access token (string format not JSON) and I am not sure if this is the best way to test or not.
Note: I am still in early stage of development, if you have any suggestion on my flow please let me know, I might be doing things the wrong way ?
What works for my application (code with explanation below)...
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXX',
'app_secret' => 'XXXXXXX',
'default_graph_version' => 'v2.5',
]);
// My app pulls users' access tokens & page ID from a database here and stores in $fb_access_token & $fb_page_id variables
$fb_access_token = 'YOU OR YOUR USERS ACCESS TOKEN GOES HERE';
$fb_page_id = 'ID OF FACEBOOK PAGE OR USER';
$fb->setDefaultAccessToken($fb_access_token);
// CHECK IF ACCESS TOKEN SITLL WORKS
try{
$page = $fb->get('/'.$fb_page_id.'?fields=id', $fb_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
$graphError = 'Yes';
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
$sdkError = 'Yes';
}
// IF ACCESS TOKEN STILL WORKS...CONTINUE WITH SCRIPT. THIS PREVENTS ACCESS TOKEN FAILURE FROM BREAKING SCRIPT.
if(!isset($graphError) && !isset($sdkError)){
// CONTINUE WITH SCRIPT
}
Explanation: you are taking the access token in question, and attempting to make a GET Request to the Facebook API. Only continue with the rest of your script IF there are NO ERRORS.
You could also add an ELSE statement at the end to maybe redirect the user to a page where they can re-authenticate their account/access token, depending on what your app is doing.
My app uses a couple of WHILE Loops to go through my database of users, and depending on certain column/cell values, it POSTS to their Facebook page for them...
Before this solution...when the Loop came across an invalid Access Token, it "broke" and did not execute the script for the rows following the "unauthenticated user" because it was making a failed request.
Hope this helps someone!
“Random” tokens would not work anyway. (Tokens issued by Facebook are encrypted, so the API can tell whether a token is genuine, or just "random". At most you'd need to worry about what a user possible could using a token for a different app, or one they themselves granted more permissions than you asked them for.)
Just request the user details using the access token you got - if it is not valid because someone tried to “fake” it, then the API response will tell you so.
The docs have a chapter about securing API requests, go check that out as well: https://developers.facebook.com/docs/graph-api/securing-requests
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'm trying to create a cron job with a php script for retrieving info about stats of a Fan Pages and I have some questions:
have I to log a user to get the access token and use the Facebook API?
Which kind of token must to use? App token? Page Token?
I've read in several posts in Stackoverflow that only the Page Access token is necessary, but I have no success:
Request: /419788471442322/?fields=access_token
Response: Unsupported get request.
This is the code
//get the app access token
$facebook->setAccessToken($facebook->getAccessToken());
//Format the api call
$fields = array('access_token');
$page_info = $facebook->getInsights($id,"",$fields);
//display the result
print_r($page_info);
public function getInsights($id, $nameapi, $fields = array(), $limit = null)
{
if (isset($fields)) $fields = implode(",",$fields);
if (isset($limit)) $limit = "&limit=".$limit;
try {
echo '/'.$id.'/'.$nameapi.'?fields='.$fields.$limit;
$fbdata = $this->facebook->api('/'.$id.'/'.$nameapi.'?fields='.$fields.$limit);
} catch (FacebookApiException $e) {
$fbdata = $e->getMessage();
}
return $fbdata;
}
By default, the App Access Token will be used and you don´t need to set it with setAccessToken.
The App Access Token is good enough for basic infos and the Page feed, but for getting access to the Insights you need a Page Access Token and that´s a bit more complicated. Actually, in a Cron Job you would need a Page Access Token that is valid forever, basic ones are only valid for 2 hours. "Extended Page Access Token" is exactly what you need.
More info about Access Tokens and how to get an Extended Page Access Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
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;
}