Getting facebook friends list - facebook

I made link of facebook login which requests an access token with permission to friends list:
<a href="https://www.facebook.com/dialog/oauth?response_type=token&scope=user_friends...>Login</a>
After the user passed the login successfully and accept these permissions and my app stored the access token, I tried to get his friends list by:
https://graph.facebook.com/me/friends?access_token={ACCESS_TOKEN}
But all I get is:
{
"data": [
],
"summary": {
"total_count": 245
}
}
Maybe I should request something else in the scope?
Thank you !

$request = new FacebookRequest(
$session,
'GET',
'/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
For example in CodeIgniter I use fb library and i get friends list like this:
public function get_user_friends() {
if ( $this->session ) {
try {
$fr = new FacebookRequest( $this->session, 'GET', '/me/friends' );
$request = $fr->execute();
$user_friends = $request->getGraphObject()->asArray();
return $user_friends;
} catch(FacebookRequestException $e) {
return false;
/*echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();*/
}
}
}
And dont forget that it has some conditions:
Permissions
A user access token with user_friends permission is required to view the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
More about: https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friends

Related

How to autopost to facebook page with app id

How to post to Facebook page with the App ID & Secret & Page ID without need to login with the user Admin of the page to get access token, the App owner who is the Admin of the page shouldn't be enough to auto post !?
I am using PHP & SDK4 of Facebook API.
You can´t post anywhere on Facebook without authorizing. If you want to post "as Page", you need to authorize a Page admin with the "publish_pages" permission and use a Page Token. You can´t get a User or Page Token without authorization, and of course you can´t automate the authorization process. Check out the docs for detailed information: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
You will also need to learn about Access Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
In fact all i wanted specifically to have permanent page access token so i can auto post forever without requiring authentication from the user each time for posting.
follow these steps to get it: Permanent Access Token
then use auto post code :
session_start();
define('FACEBOOK_SDK_V4_SRC_DIR', 'facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// Facebook App
$api_key = 'xxxxxxxxxxxxxxxx'; //App ID
$api_secret = 'xxxxxxxxxxxxxxxx'; //App Secret
$page_id = 'xxxxxxxxxxxxxxxx'; //Page ID
$page_token = 'from the steps in the url';
$fb_post = array(
'message'=> 'test message',
'name'=> '',
'link'=> 'http://www.example.com/',
'picture'=> 'http://www.example.com/image.jpg',
'caption'=> '',
);
// start a session for this App
FacebookSession::setDefaultApplication($api_key, $api_secret);
try {
$session = new FacebookSession($page_token);
} catch(FacebookRequestException $e) {
die(" Error : " . $e->getMessage());
} catch(\Exception $e) {
die(" Error : " . $e->getMessage());
}
try {
// Auto posting
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', $fb_post))->execute()->getGraphObject()->asArray();
// return post_id, optional
print_r( $page_post );
} catch (FacebookRequestException $e) {
// The Graph API returned an error
echo '<b style="color:blue;">'.$e->getMessage().'</b>';
} catch (\Exception $e) {
// Some other error occurred
echo '<b style="color:red;">'.$e->getMessage().'</b>';
}

Posting facebook api not as page

I've made facebook app, got appID and secret, and I am trying to post to a page as the page. I've granted the app permission.
But when I'm posting, new post creates "as user", not as page.
My code:
require '../lib/fb/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('APP_ID','SECRET');
$session = new FacebookSession('ACCESS_TOKEN');
try {
$response = (new FacebookRequest(
$session, 'POST', '/1429642034012499/feed', array(
'message' => 'test',
'link' => 'http://mylink',
)
))->execute()->getGraphObject();
print_r($response);
} catch (FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
} catch (\Exception $e) {
}
Page to view.
This Answer is for C#, using the .NET Facebook API Library. But Logic should be same in PHP.
You have to get the Page Access Token:
Go Here: developers.facebook.com/tools/
Then Go to this Link:
Then Click on: "Get Access Token"
Then Add these Permissions:
Then Copy New access Token:
Now in C# Class I do (This is the POST A Comment as Page):
var userClient = new FacebookClient("THE NEW ACCESS TOKEN YOU JUST GENERATED");
dynamic accountInfo = userClient.Get("USER_ID" + "/accounts");
//USER_ID Should be Digits, this is the UserID when you do: facebook.com/USERID it should come up with the Admin Profile
var pageAccessToken = accountInfo.data[0].access_token;
var pageClient = new FacebookClient(pageAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = model.Message;
dynamic pageResult = pageClient.Post(string.Format("{0}/comments",), parameters);

get the facebook reviews return error

I first get page token with facebook api
function createSession($app_id,$app_secret){
FacebookSession::setDefaultApplication(
$app_id,$app_secret
);
$testUserPermissions = array('user_actions.books','user_actions.fitness','user_actions.music','user_actions.news','user_actions.video','user_birthday','user_games_activity','user_groups','user_hometown','user_interests','user_location','user_relationship_details','user_religion_politics','user_tagged_places','user_videos','user_work_history','read_friendlists','read_page_mailboxes','manage_notifications','read_mailbox','publish_actions','read_stream', 'user_photos','manage_pages','public_profile','user_friends','email','user_about_me','user_activities','user_education_history','user_events','user_likes','user_relationships','user_status','user_website','read_insights','rsvp_event');
$testUserPath = '/' . $app_id . '/accounts/test-users';
#$testUserPath = '/100008488695640/accounts/test-users';
$params = array(
'installed' => true,
'name' => 'User test',
'locale' => 'zh_TW',
'permissions' => implode(',', $testUserPermissions),
);
echo var_dump($params);
$request = new FacebookRequest(new FacebookSession($app_id . '|' .$app_secret), 'POST', $testUserPath, $params);
$response = $request->execute()->getGraphObject();
echo var_dump($response);
#$testUserId = $response->getProperty('id');
$testUserAccessToken = $response->getProperty('access_token');
return new FacebookSession($testUserAccessToken);
}
this is my get token
then i use this token to get reviews
https://graph.facebook.com/v2.2/185342243407/ratings?field=open_graph_story&access_token=$token_value
but it return
{
"error": {
"message": "(#210) This call requires a Page access token.",
"type": "OAuthException",
"code": 210
}
}
how i can get the page token?
the token is not used?
Make sure you are REALLY using a Page Token. Put the Token in the Debugger and see if it´s a Page Token: https://developers.facebook.com/tools/debug/
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
When you request multiple permissions, some of them may work with the endpoint you are calling, and some of them may not, causing this 210 error.
In my case, adding profile_pic permission to /me?fields=id,first_name,last_name,email caused this error.

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

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();
}
?>