I want to get user access token rather than application access token - facebook

I want to get user access token because I need to get user's posts and comments.
When I use Graph API Explorer, the access token it generates is correct one and shows me my posts and comments and some other data. But when try to get posts and comments by using this code than it does not return me posts and comments and return some other data only which i don't need.
require_once('facebook.php');
$config = array(
'appId' => '383128895071077',
'secret' => '6a9ab479186f53db5c531a3fa5f91be0',
);
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
$result = $facebook->api('/me/feed/', array('access_token' => $access_token));
I searched all the google and get access token by different ways but I could not get posts and comments of me. I must be doing something wrong and need to sort out this as soon as possible.
Thanks in advance.

You should check this example
Facebook php sdk example
you should check whether we have user access token like this
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
Once we get the user details, you can ensure that user is logged into app and authorized the app.
For feeds
You should have extended permissions read_stream
then you can read the wall feed.

Related

Unable to get friends despite permissions

I am making an application which needs to get friends of the current user
if ($user) {
$user_profile = $facebook->api('/me');
$friends= $facebook->api('/me/friends');
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array('scope' => 'user_status,publish_stream,user_photos, user_friends');
$loginUrl = $facebook->getLoginUrl( $params);
}
Now, the problem I am facing is that the friends list returns empty for my current app. For an older app, albeit it works fine. The new app is public and I checked in the Status and Reciew area where it says that the app has user_friends permission by default. I can't seem to understand what's wrong with this/
Per https://developers.facebook.com/docs/apps/changelog#v2_0_login, user_friends now only gives access to friends using the same app, not all friends.

Checking if user is a member of a specific facebook group

Do you have an example of how to confirm that the person trying to access the content of your app is a member of a specific facebook group, using php? I've read through the developer docs and all it managed to do was confuse me even more. I've seen posts similar to this one but they only show me how to print a list of members...
I need to know how to get the list and see if the user trying to access the app is a member of the group so that I can either a: allow access or b: deny access and re-direct the user to the group page so they can request membership...
Yes its pretty simple, you just need to know the ID of the group you want to do that and ask for the scope user_groups permission, so you can query the groups the user have.
With the PHP SDK you can do this:
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $facebook->api('/me?fields=id,name,groups','GET');
$user_belongs_to_group= FALSE;
foreach($user_profile['groups']['data'] as $group){
if($group['id']==YOUR_GROUP_ID)
$user_belongs_to_group=TRUE;
}
if($user_belongs_to_group){
//Alright! the user belongs to the group
}
else{
//Oh snap you don't belong here, but you can if want to
}
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
Some of this code I grabbed from the facebook, you can see the data that is returned when query for groups here: https://developers.facebook.com/tools/explorer
Press the plus sign after the name go to connections, choose groups and press send
You are in a catch-22, you will need the user to grant permission to his groups via the user_groups permission.

How to publish photos on behalf of the user with application access token ? (not with user access token)

I want my application to publish photos, user has already registered my app with publish_stream permission and is currently disconnected from facebook.
Documentation https://developers.facebook.com/docs/publishing/ said :
To publish a 'photo' object you need
a valid access token
publish_stream permission
I tried a HTTP POST request :
https://graph.facebook.com/<USER_ID>/photos?access_token=<APPLICATION_ACCESS_TOKEN>
POST param : "url":"<link_to_some_picture>"
And i got an exception :
content={"error":{"message":"A user access token is required to request this resource.","type":"OAuthException","code":102}}
To publish photos on behalf of user i cannot pass a user access token... Why i can post links but not photos with my application access token?
Your title states that you are using an application access token - the error you are getting clearly states the problem. You need a user access token.
You'll need to extend your users access token in order to perform actions on his/her behalf when they are not connected to Facebook.
Here is a good resource for information about dealing with expired tokens and how to refresh them -
https://developers.facebook.com/docs/authentication/access-token-expiration/
When user registered your application then you can store the user's user access token after you can used that access token to post on behalf of user.When user come to your application next time you can update that access token.
You can use following function to get extended access token:
public function getExtendedAccessToken(){
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array( 'client_id' => $this->getAppId(),
'client_secret' => $this->getApiSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken(),
));
} catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
return $response_params['access_token'];
}
$fid = $row[1];
echo "fid = $fid\n";
$message =$row[2];
echo "msg = $message\n";
$friends = $facebook->api("/$user/friends?fields=id");
$args= array(
'app_id' => $facebook->getAppId(),
'to' => $fid,
'link' => 'http://www.facebook.com',
'message'=>$message,
);
$post_id = $facebook->api('/fid /feed', 'POST', $args);
var_dump($post_id);

How to get user access_token if I have his/her oauth_token?

When user opens my canvas app I get a signed_request from Facebook, from which I derive the user_id and oauth_token. How can I then get the access_token and check/get user permissions and other data?
The oauth_token you're talking about is also the users access_token, they should be exactly the same.
To check the users permissions you can make a GET call to /me/permissions this should return a data array similar to the below
{
"data": [
{
"installed": 1,
"read_stream": 1,
"manage_notifications": 1,
"manage_pages": 1,
"user_likes": 1,
"user_activities": 1,
"user_interests": 1,
"user_photos": 1,
"user_about_me": 1,
"type": "permissions"
}
]
}
Depending on what the other data you wish to access you will need to ask for more permissions and then call the appropriate API end points. For example to get the users basic information make a call to /me or to get a list of their friends /me/friends
You can find all the permissions you can ask for at https://developers.facebook.com/docs/reference/api/permissions/
And all the information about where to call in the API for retrieving the different bits of data you require here https://developers.facebook.com/docs/reference/api/
When you say you have their 'oauth token' - are you sure that isn't the access token? Can you try making an API call to /me/permissions with that token and see if it's working? It should return a list of the permissions the user has granted your app (which are usable via that token)
<?php
include '../../src/config.php';
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
$access_token = $facebook->getAccessToken();
$user_xml = "<?xml version=\"1.0\"?>\n";
$user_xml .= "<roots>\n";
$user_xml .= "<access>\n";
$user_xml .= "<token>" . $access_token . "</token>\n";
$user_xml .= "</access>\n";
$user_xml .= "</roots>\n";
echo $user_xml;
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>

Facebook-PHP SDK 3.0 : How do I store a session in the database once the user has logged in and provided the access?

I am using Facebook PHP SDK 3.0
I would like to know how could I store the session of the user in the database so that once the user provides access and logs in, I could store the access tokens in the database and use it next time so that the user doesn't require to log in again. Right now I am using the following code
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => SECRET,
'cookie' => true
));
$user = $facebook->getUser();
if(!$user)
{
$loginUrl = $facebook->getLoginUrl();
echo anchor($loginUrl,"login");
}
//print_r($_SESSION);
$user = $facebook->getUser();
if($user)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
//print_r($user_profile);
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
Any help appreciated thanks
Facebook access keys expire after a while. Even if you do store them, and they have not expired yet, they will not work if the user is not logged in. If you want to access the users Facebook account while the user is offline, you need the 'offline_access' permmission.