trying to determine if user is a page admin using FB GraphAPI - facebook

I have a page tab app. When the user clicks on the "Go to App" and is sent to my page tab edit url i am trying to determine if they are a page admin or not.
I have tried two different methods. I have tried from the only admin/owner of the page
method 1 used from https://developers.facebook.com/blog/post/2011/09/05/platform-updates--labor-day-edition/
$page_info = $facebook->api("/".$pageID."?fields=access_token");
$pageAccessToken = $page_info['access_token']
$is_admin_url = "https://graph.facebook.com/" . $pageID
. "/admins/" . $FBuser . "?access_token="
. $pageAccessToken;
$response = file_get_contents($is_admin_url);
response is {"data":[]}
I have also tried::
path = '/'.$pageID.'/admins/'.$FBuser;
$params = array(
'app_id' => FB_APP_ID,
'access_token' => $pageAccessToken
);
$is_admin = $facebook->api($path, 'POST', $params);

Although PAGE_ID/admins is a valid request, you need an admin's access_token to see the list. I.e. only admins can see who else is an admin.
What you can do is approach this from the other end by yielding a list of pages that the user is an admin of (using the https://graph.facebook.com/USER_ID/accounts/ data and the manage_pages permission) and search through that list for your application.
However, I would understand if some users would be reluctant to give the manage_pages permission, as it also provides an access token to authenticate as that page, which would be something of a security hole on their part. Unfortunately, there does not seem to be another way to access a list of pages for which that user is an admin.

Simplest way will be signed Request.
A signed_request parameter is POSTed to an application when the app is loaded inside a Page Tab.
You can get a lot of information from signed_request
require '../fb_sdk/facebook.php';
$config = array();
$config['appId'] = '45916xxxxxx';
$config['secret'] = '59caxxxxxx';
$facebook = new Facebook($config);
$facebook->setFileUploadSupport(true);
$signed_request = $facebook->getSignedRequest();
print_($signed_request); will have output like
Array
(
[algorithm] => HMAC-SHA256
[expires] => 1347210000
[issued_at] => 1347203265
[oauth_token] => AAAGhmv67ki8BAAfBwtxxxx
[page] => Array
(
[id] => 192430xxxxxx
[liked] => 1
[admin] => 1
)
[user] => Array
(
[country] => in
[locale] => en_US
[age] => Array
(
[min] => 21
)
)
[user_id] => 10000020xxxxx
)
You can use $signed_request[page][admin] value to determine whether a user is admin of current page, in which your app in loaded in Page Tab. If it's set to 1 then user is admin of the page else not an admin i.e. set to 0.
More About Signed Request

i had some luck using admin_only = true
https://developers.facebook.com/docs/graph-api/reference/user/groups/

Related

Post to facebook page from facebook page tab app

I want to post activities from page tab app to my own facebook page. I referred many documents to post message to app.
My php code :
$GLOBALS["facebook"] = new \Facebook_Facebook(array('appId' => $facebook_app_id, 'secret' => $facebook_secret,));
$page_info = $GLOBALS["facebook"]->api("/pageid?fields=access_token");
print_r($page_info);die;
if (!empty($page_info['access_token'])) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => 'TEST'
);
$postId = $facebook->api("/pageid/feed", "post", $args);
But pageinfo variable has only id. I'm not getting access_token. Any idea what else need to be done?
We need manage_pages permission which we can get it using https://www.facebook.com/dialog/oauth?client_id=client_app_id&client_secret=9ea3e2eff7c65b1fcf1a633da&redirect_uri=YOUR_REDIRECT_URL&scope=read_stream,publish_stream,offline_access,manage_pages.
After that using above code we will get access token which can be used to publish to our page

Facebook canvas GET param (app_data)

I am trying to get app_data from the facebook canvas.
It's working in page tab.
https://www.facebook.com/something/app_55218516481307?app_data=4B9E753
$signed_request = $facebook->getSignedRequest();
$app_data = $signed_request["app_data"];
app_data contains the value - '4B9E753' So, it's nice.
But there, app_data is not even set.
https://apps.facebook.com/namespace/?app_data=something
signed_request contains only
Array (
[algorithm] => HMAC-SHA256
[issued_at] => 65456446
[user] => Array (
[country] => cz
[locale] => cs_CZ
[age] => Array (
[min] => 21
)
)
)
Why?
It only works in a page tab and not on the canvas page.
https://developers.facebook.com/docs/reference/login/signed-request/
to send data to the app on its canvas app page use
'https://apps.facebook.com/yourappname?sk=app_yourapp_id/whatever_you_wish_to_send/'
and get it in php with $thisrequest = $_REQUEST['sk']; you can echo it to see what you get back.

Facebook API post to friends wall

I'm building application to post statuses from authenticated users like that one.
The problem is the application posting from my profile on friends wall who authenticated the application from my profile.
I'm using Facebook API with CodeIgniter.
the code
$userId = $this->facebook->getUser();
$IDs = $this->facebook_data->get_IDs();
if(isset($_POST['link'])){
$args = array(
'from' => array('name'=>'Resala','id'=>'294357147348261'),
'application'=>array('name'=>'XXXX','id'=>'XXXXX'),
'name' =>'XXXX',
'message' => $_POST['status2'],
'link' => $_POST['link']
);
}else{
$args = array(
'from' => array('name'=>'Resala','id'=>'294357147348261'),
'application'=>array('name'=>'Resala','id'=>'XXXXX'),
'name' =>'XXXX',
'message' => $_POST['status1']
);
}
foreach($IDs->result() as $row){
$ID=$row->user_id;
$this->facebook->api("/$ID/feed", "post", $args);
}
The right docs for creating a post are:
http://developers.facebook.com/docs/reference/api/user/#posts
There you can see the params "from" and "application" don't exist and "name (can only be used if link is specified)".
It's not possible to post in the name of an app. You can only post in the name of an page (that may be assosiated with the app).
Therefor you have to use the page access token instead of the user access token.
See: http://developers.facebook.com/docs/reference/api/page/#page_access_tokens

facebook tab userid is 0 after page like

I'm trying to get a the facebook userid in a facebook tab, but somehow this always returns 0.
This is the code I use:
$config = array();
$config["appId"] = "427761887242287";
$config["secret"] = "xxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook($config);
$fbData = $facebook->getSignedRequest();
Facebook appId and secret are valid, I've already tried with resetting the secret.
I've tried to do a print_r on $fbdata but this only returns:
Array
(
[algorithm] => HMAC-SHA256
[issued_at] => 1337603346
[page] => Array
(
[id] => 158282080958121
[liked] => 1
[admin] =>
)
[user] => Array
(
[country] => nl
[locale] => en_US
[age] => Array
(
[min] => 21
)
)
)
As you can see, this retuns only some non usefull data as far as the user goes.
I've also tried $facebook->getUser() but this does return 0.
I do have a valid SSL certificate on my server, I use the right http and https URL's but I can't find out why I get a 0 for the userid while I'm logged in.
Any suggestions?
If this is a facebook page tab application, then the user id is not returned unless the user has explicitly authorized your application. And from the response you've posted it looks like this is the case. You would need to get the user to authorize your application, not just like a page for this to work
https://developers.facebook.com/docs/authentication/pagetab/

Facebook Graph Api - Posting to Fan Page as an Admin

I've setup a script which allows users to post messages to a fan page on Facebook. It all works but there's one small issue.
The Problem:
When the post is added to the page feed it displays the posting user's personal account.
I would prefer it to show the account of the page (like when you're admin of the page it says it came from that page). The account I'm posting with have admin rights to the page, but it still shows as a personal post.
HTTP POST
$url = "https://graph.facebook.com/PAGE_ID/feed";
$fields = array (
'message' => urlencode('Hello World'),
'access_token' => urlencode($access_token)
);
$fields_string = "";
foreach ($fields as $key => $value):
$fields_string .= $key . '=' . $value . '&';
endforeach;
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
To post as Page not as User, you need the following:
Permissions:
publish_stream
manage_pages
Requirements:
The page id and access_token (can be obtained since we got the required permissions above)
The current user to be an admin (to be able to retrieve the page's access_token)
An access_token with long-lived expiration time of one of the admins if you want to do this offline (from a background script)
PHP-SDK Example:
<?php
/**
* Edit the Page ID you are targeting
* And the message for your fans!
*/
$page_id = 'PAGE_ID';
$message = "I'm a Page!";
/**
* This code is just a snippet of the example.php script
* from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
*/
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} else {
$permissions = $facebook->api("/me/permissions");
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) {
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} 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(array('scope'=>'manage_pages,publish_stream'));
}
// ... rest of your code
?>
Here the connected $user is supposed to be the admin.
Result:
More in my tutorial
As far as I know, all you have to do is specify a uid (that is, the page's ID) in your call to stream.publish
EDIT
Have a look at impersonation
Because the is the only relevant posting in the google results for "facebook graph won't post to page as page" I want to make a note of the solution I found. You need an access token with manage_pages permissions. Then call
https://graph.facebook.com/<user_id>/accounts?access_token=<access_token>
This will list all the pages the user has access to and will provide the access tokens for each. You can then use those tokens to post as the page.
The Graph API expects the parameter page_id (The Object ID of the Fan Page) to be passed in as an argument to API calls to get the events posted in a Fanpage wall. Not mentioned anywhere in the official Graph API documentation, but it works. I have tested it successfully with the Official PHP SDK v3.0.1
The required application permissions would be create_event and manage_pages
An Example would look something like this:
//Facebook/Fan Page Id
$page_id = '18020xxxxxxxxxx';
//Event Start Time
$next_month = time() + (30 * 24 * 60 * 60);
//Event Paramaeters
$params = array(
'page_id' => $page_id, // **IMPORTANT**
'name' => 'Test Event Name',
'description' => 'This is the test event description. Check out the link for more info: http://yoursite.com',
'location' => 'Kottayam, Kerala, India',
'start_time' => $next_month
);
$create_event = $facebook->api("/$page_id/events", "post", $params);
The answer lies with acquiring a permission of "manage_pages" on the FB:login button, like so:
<fb:login-button perms="publish_stream,manage_pages" autologoutlink="true"></fb:login-button>`
When you get those permissions, you can then get a structured list back of all the pages the logged-in user is an Admin of. The URL to call for that is:
https://graph.facebook.com/me/accounts?access_token=YourAccessToken
I HATE the Facebook documentation, but here is a page with some of the information on it: https://developers.facebook.com/docs/reference/api/
See the 'Authorization' and 'Page Login' sections in particular on that page.
A great resource to put all of this together (for Coldfusion Developers) is Jeff Gladnick's CFC on RIA Forge: http://facebookgraph.riaforge.org/
I added the following UDF to Jeff's CFC if you care to use it:
<cffunction name="getPageLogins" access="public" output="true" returntype="any" hint="gets a user's associated pages they manage so they can log in as that page and post">
<cfset var profile = "" />
<cfhttp url="https://graph.facebook.com/me/accounts?access_token=#getAccessToken()#" result="accounts" />
<cfif IsJSON(accounts.filecontent)>
<cfreturn DeserializeJSON(accounts.filecontent) />
<cfelse>
<cfreturn 0/>
</cfif>
</cffunction>
What this returns is a structure of all the pages the logged-in user is an Admin of. It returns the page NAME, ID, ACCESS_TOKEN and CATEGORY (not needed in this context).
So, VERY IMPORTANT: The ID is what you pass to set what page you are posting TO, and the ACCESS_TOKEN is what you pass to set who you are POSTING AS.
Once you have the list of pages, you can parse the data to get a three-element array with:
ID - ACCESS_TOKEN - NAME
Be careful though, because the Facebook ACCESS_TOKEN does use some weird characters.
Let me know if you need any additional help.
You must retrieve access_tokens for Pages and Applications that the user administrates.
The access tokens can be queried by calling /{user_id}/accounts via the Graph API.
More details:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0 -> Reference -> Pages
This is how I do it with PHP SDK 4.0 and Graph API 2.3:
/**
* Posts a message, link or link+message on the page feed as a page entity
*
* #param FacebookSession $session (containing a page admin user access_token)
* #param string $pageId
* #param string $message - optional
* #param string $link - optional
*
* #return GraphObject
*/
function postPageAsPage( $session, $pageId, $message = '', $link = '' ){
// get the page token to make the post request
$pageToken = ( new FacebookRequest(
$session,
'GET',
"/$pageId" . "?fields=access_token"
))->execute()->getGraphObject();
return ( new FacebookRequest(
$session,
'POST',
"/$pageId/feed",
array(
'access_token' => $pageToken->getProperty( 'access_token' ),
'message' => $message,
'link' => $link,
)
))->execute()->getGraphObject();
}