Facebook PHP SDK - php

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;
}

Related

Check an User token with Facebook API with 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.

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

Retrieving user information with access token - Facebook developer

I'm developing a Facebook application, and I want to retrieve some of the user's information on a side server while they are using the application.
In order to make that possible, I store the users access token in my database and pass it to the other server.
However, I am not sure how to use the access token to retrieve the user information. I am using the PHP SDK, and here is the usual code:
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
// Get User ID
$user = $facebook->getUser();
Where can I declare the access token?
It's very simple. If you enter a url like https://graph.facebook.com/me?access_token=theuseraccesstoken (in your browser) you will receive a json file with the user information.
I'm pretty sure the facebook php sdk have a built in mechanism to do that (I'm a c# coder), but you are looking in the wrong place, because no api key or secret is necessary to access user information using a access token.
UPDATE1:
I think it works like this in the sdk
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
UPDATE2:
Or like this
$user = $facebook->api('me?access_token='.$access_token);
If the user is logged in, make:
$facebook->api('/me');
I will give you an array with information about the 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.

Facebook PHP SDK 3 issue in access_token

I am using facebook PHP SDK. After the user allows my application, facebook redirects to may web page.
Following is the URL
http://Mydowmain.com/facebook.htm?state=d96afbb9ea550fg81c287b7822cee0af1&code=AQDtl7Rd7qgCp6S_dXwOCxxfXo1dEh75ZJqrCINMawCUzxOYs9JnpmWKMoYTgjuNhQx2nk8pleCdvGqSt39F2pHKMHt3aNxwqoIah2oshPKKC0MnWycPSU0yLAKMYVQV2g3jRQdEMf2dWTVUrk_ammSpGaYbfFQ3GeccZ1vGqfVazsaQ_1Lxz7GjITlqgCxrOlc#_=_
I need to fetch the access_token
Following is the code
if($_GET['code'] != '')
{
$access_token = $facebook->getAccessToken();
When i try to use this $access_token to get the user details.
$user_profile = 'https://graph.facebook.com/me/?access_token='.$access_token;
It gives the following error
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
}
I dnt what i am doing wrong, it was working with SDK 2 but not working with SDK3
$access_token = $facebook->getAccessToken();
this Call Returns the following, in which fistpart before "|" is App ID and After "|" is App Secret..
187997367916887|9d87d7a2d26485fd926a000b0c3b2f87
Check this link out, scroll down to the answer with the following in bold: "When using your Facebook Application's token", hope it helps.
Facebook access_token invalid?
Change your graph call's api ('/me') by ('/[number or name id]')

Categories