Check an User token with Facebook API with PHP - php

I have a web app, where user are signing with facebook, then I save their access token in my database. I'm trying to check if their token are valid with the PHP SDK then if the token is valid , I'd like to extend it.
The problem is that I get an error message which tells me:
(#100) You must provide an app access token or a user access token that is an owner or developer of the app
Does that mean only app dev team member's can have their token extended or verified?
Here is my code:
FacebookSession::setDefaultApplication(
'my_client_id',
'my_client_secret'
);
$session = new FacebookSession($user_token);
try {
$resp = (new FacebookRequest(
$session, 'GET', '/debug_token', array(
'input_token' => $user_token
)
))->execute()->getGraphObject();
//profile ok
} catch(\Exception $exp) {
//profile ko
}

The debug API is for if you want to do things as the app, not as the user.

Related

How get access token from other users

I need to read the posts on facebook. I had create the application and the program works if I log with my credential. But when I log with another credential ( like another profile that I have just created) the program doesn't work anymore. This is my login page:
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if(!empty($_SESSION)) {
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
$access_token=$facebook->getAccessToken();
$facebook->setAccessToken($access_token);
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}
} else {
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
header("Location: ".$login_url);
}
when I login I obtain the access token and I call graph api:
https://graph.facebook.com/******/posts?access_token=**
This is operation work if I m who is logged in the application. If another login in the app this is not work.
Maybe it's a authentication problem. Maybe I forget some operation that I must do to authentica with another account. Anyone can help me?
You need to submit your App to Facebook then Facebook will check and pass you app then you can access you app other account. If you want to check App Functionality you can use Facebook App test user Id. Below I have Explained how to get test user
Goto App Page.
Click on Roles.
Click on to Right Corner Test users.
It will show your test user details.
Use this details and access you App.
You have to make your app public for all users from here: https://developers.facebook.com
have a look on it:
Use /me/feed instead of /me in your API call
see example below
Permissions
Your app needs user_posts permission from the person who created the post or the person tagged in the post. Then your app can read:
Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.
please read this thread https://stackoverflow.com/questions/30719556/read-post-from-facebook-home/30732874#30732874
READING
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */

facebook php sdk error - An active access token must be used to query information about the current user

FacebookSession::setDefaultApplication('1578373582426403', 'CENSORED');
$session = FacebookSession::newAppSession('1578373582426403', 'CENSORED');
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
when $request->execute() is called, i get the error:
An active access token must be used to query information about the current user.
Im not sure what im doing wrong... can anyone help?
If you are trying to access the current user's information,try this. Change the redirect login
// Call Facebook Session- App Id, App Secret
Facebook\FacebookSession::setDefaultApplication('1578373582426403', 'CENSORED');
//Facebook Redirect Helper
//Create a FB variable, Pass oAuth URL
$facebook= new Facebook\FacebookRedirectLoginHelper('http://localhost/fb/');
//
try
{
//To check method getSessionFromRedirect
if($session= $facebook->getSessionFromRedirect())
{
//store the token in a session variable
$_SESSION['facebook']=$session->getToken();
}
//If the session is already set
if(isset($_SESSION['facebook']))
{
//New Facebook Session; Pass the facebook token
$session= new \Facebook\FacebookSession($_SESSION['facebook']);
//Creating a fb request, pass the session, method, /me to get the user's details
$request= new \Facebook\FacebookRequest($session,'GET','/me');
//Execute the request
$request=$request->execute();
$user=$request->getGraphObject()->asArray();
// print_r($user);
}
}
catch(Facebook\FacebookRequestException $e)
{
//When FB returns an error
}
catch(\Exception $e)
{
//Normal exception
}
You are setting up a session, using an App Access token. That means that the access token only identifies your app; no users.
The call you are making, /me, is an alias for the current user ID of the used access token. But, there is no user ID for an app. And, with just an App Access token you can't request user information.
To make your script work, you should query /1578373582426403, which is the App ID.
Update: you can also query /app, which should be the alias for the app of an access token.

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

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.

Facebook PHP SDK

I would like to know whether the Facebook PHP SDK is up to date with regards to Facebooks Server Side Authentication (https://developers.facebook.com/docs/authentication/server-side/)
I am having difficulty obtaining an access_token when FB passes back my state and code.
Am I meant to programmatically add this functionality? Or is the SDK meant to handle the response from Facebook?
example:
I pass FB:
https://www.facebook.com/dialog/oauth?client_id=1234567890&redirect_uri=http%3A%2F%2Flocalhost%2F&state=ef8dba2dc8b4fa002973ffa5e29c67cb
Facebook returns:
http://localhost/?state=ef8dba2dc8b4fa002973ffa5e29c67cb&code=AQAhuVUqufbghj2bBLcCr5SdRJopdYaR-vAoZJzilvvDgiGYNuEPVKTRLqD9p9MPrPhIIubYPH0aka8RtBQU_vSGdkCI5DkQxhQpwWcADu1_jSQgOC9vBsF2oWardpcPcq4PzmNq-JYhdvEFyMD0K7vPY0WioUgLghhw28FJAhHis9K7dz6HyrNy0YXfjbK0AN0#_=_
However the SDK does not handle this response above from Facebook.
Facebook suggests you obtain and access token by passing back the code.
Exchange the code for a user access token
Once the user has authorized your app, you should make a server side request to exchange the code returned above for a user access token.
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID
&redirect_uri=YOUR_REDIRECT_URI
&client_secret=YOUR_APP_SECRET
&code=CODE_GENERATED_BY_FACEBOOK
Does the SDK not do this itself?
Try this :
$user = $facebook->getUser();
$url = $facebook->getLoginUrl(array(
'scope' => 'email,publish_stream,publish_actions',
'redirect_uri' => 'login.php', //give ur apropriate page
));
if($user){
$acestokn = $facebook -> getaccesstoken();
}else{
header('location:'.$url);
exit;
}

Categories