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/
Related
I am trying to post to a Facebook account (with permissions) using the PHP
API. I am giving our users two options - posting to the Feed, and posting
to a specific facebook page. I am getting an error in the first case, but
not in the second case. In the code below:
$access_token is the access token I got back from linking to my app. It's of type
"User", and has the following permissions:
email
pages_show_list
business_management
pages_read_engagement
pages_manage_metadata
pages_read_user_content
pages_manage_ads
pages_manage_posts
pages_manage_engagement
public_profile
Where $page_token is, well, a "Page" type token, with the same set of permissions.
When I post to the page, it works fine. But when I try to post to the timeline, I get
the error:
Graph Error 200 : [Timeline]: [(#200) If posting to a group, requires app being
installed in the group, and either publish_to_groups permission with user token,
or both pages_read_engagement and pages_manage_posts permission with page token;
If posting to a page, requires both pages_read_engagement and pages_manage_posts
as an admin with sufficient administrative permission]
I'm not trying to post to a group, I'm posting to an account's timeline. And, per the
access token debugger, I have the permissions requested anyway. What's going on?
My code is below:
$linkData = [
'link' => $link_to_post,
'appsecret_proof' => $app_secret_proof
];
if ( POSTING TO TIMELINE )
{
$token = $access_token;
$post_to = "/me/feed";
}
else
{
$page_id = $page_id;
$token = $page_token;
$post_to = "/$page_id/feed";
}
// THIS THROWS THE EXCEPTION:
$response = $this->fb->post($post_to, $linkData, $token);
You can not post to a personal timeline via API any more, that was removed ages ago already. (With introduction of API v2.4, if I remember correctly.)
You can only use the Share or the Feed dialog, to offer the user a way to actively share / make a post themselves, https://developers.facebook.com/docs/sharing/web
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! :)
im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/
I am currently using the fitbit library with a laravel wrapper (see https://github.com/popthestack/fitbitphp).
I am attempting to store the access token once a user authenticates and then subsequently reuse that token instead of having to make a separate request for a new token each time. Is it possible using fitbits oauth 1 implementation to reuse the access tokens or will I need to make a new request using request tokens etc. each time. I apologize in advance, I have a fairly visceral understanding of oauth in the first place but fitbit in particular has been tripping me up. Thanks.
here is the function I have that requests info from fitbit...
public function getFitbit() {
// get data from input
$code = Input::get( 'oauth_token' );
// get fb service
$fb = fitbitOauth::consumer( 'Fitbit' );
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from fitbit, get the token
$fb->requestAccessToken(
$_GET['oauth_token'],
$_GET['oauth_verifier']
);
// Send a request now that we have access token
$result = json_decode($fb->request('user/-/profile.json'));
print_r($result);
}
// if not ask for permission first
else {
// get fb authorization
$token = $fb->requestRequestToken();
$url = $fb->getAuthorizationUri(array('oauth_token' => $token->getRequestToken()));
// return to facebook login url
return Redirect::to( (string)$url );
}
}
I can run through the above example. Direct a user to the page where they can authenticate their account. This then redirects to a page that displays their info. If I reload the page with the 'token' and 'verifier' set already it fails. I want to be able to save off their token to a DB and reference it in the future.
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;
}