How do I check if a given user ID has authenticated my app? - facebook

I'm using the Facebook Graph API and want to check if a user has authenticated my Facebook app by user ID. How do I do this?

You use:
SELECT is_app_user FROM user WHERE uid=USER_ID
This should return:
[
{
"is_app_user": true
}
]
If the user has logged in to your application.

Expanding on ifaour's answer, in PHP this query would look something like this:
<?php
$facebook = new Facebook(
'appID' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
);
$result = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT is_app_user FROM user WHERE uid=$user_id"
));
$is_installed = $result[0]['is_app_user'];

Here you can batch multiple requests together and avoid using FQL.
Assuming you have already logged into facebook and set the access token to the application access token, you can do this:
$batch = array();
foreach($friendArray AS $friend) {
$batch[] = array(
'method' => 'GET',
'relative_url' => '/' . $friend . '?fields=installed'
);
}
FB()->useApplicationAccessToken();
$batchResponse = FB()->facebook()->api('?batch='.json_encode($batch), 'POST');
Then you can process the batch response with code like this:
$installedUsers = array();
$notInstalledUsers = array();
foreach ($batchResponse AS $response) {
$body = json_decode($response['body'], true);
if (!isset($body['id']))
continue;
$id = $body['id'];
if (isset($body['installed']))
$installedUsers[] = $id;
else
$notInstalledUsers[] = $id;
}

Related

Facebook notifications - need permission or not?

Here is what I'm seeing in the docs:
Apps can send notifications to any existing user that has authorized the app. No special or extended permission is required.
Okay, sounds good. I'm using the JS SDK and here is what I'm trying to do:
FB.api('/me/notifications?access_token=' + window.accessToken + '&href=test&template=test', function(response) {
console.log(response);
});
This is what I'm getting:
"(#200) The "manage_notifications" permission is required in order to query the user's notifications."
I have tried replacing the href parameter with my app's real domain. Using my facebook ID instead of "/me/" makes no difference either. HELP!
I HAVE tried adding the manage_notifications permission (and still doesn't work...), but my question is why does it say the opposite in the docs?
EDIT: Went to PHP:
<?php
include_once('sdk/facebook.php');
$user = $_POST['user'];
$message = $_POST['message'];
$config = array();
$config['appId'] = '609802022365238';
$config['secret'] = '71afdf0dcbb5f00739cfaf4aff4301e7';
$facebook = new Facebook($config);
$facebook->setAccessToken($config['appId'].'|'.$config['secret']);
$href = 'href';
$params = array(
'href' => $href,
'template' => $message,
);
$facebook->api('/' . $user . '/notifications/', 'POST', $params);
?>
EDIT 2: After a silly logic mistake it now works :)
To send a notification you must use application access token - appid|appsecret, so you should send it server side and execute via AJAX call. PHP example:
require_once("facebook.php");
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$facebook = new Facebook($config);
$facebook->setAccessToken($config['appId'].'|'.$config['secret']);
$user = 'userid';
$message = 'message';
$href = 'href';
$params = array(
'href' => $href,
'template' => $message,
);
$facebook->api('/' . $user . '/notifications/', 'post', $params);
https://developers.facebook.com/docs/concepts/notifications/

Facebook PHP SDK - An active access token must be used to query information about the current user

I have problem with Facebook PHP SDK. It always throws that exception. I tried many solutions listed here, but nothing works for me.
It seems that Facebook returns to me valid access token, because I tested it with Debug tool in dashboard of my application.
What's my scenario?
I want to post to publish simple content to user's wall by calling static function:
function social_publish($network, $title, $message, $link = '', $image = '') {
global $_config;
// Initialize Facebook SDK
$facebook = new Facebook(array(
'appId' => $_config['fb_app']['app_id'],
'secret' => $_config['fb_app']['app_security_key']
));
// Set data
$attachment = array(
'name' => $title,
'caption' => $title,
'message' => $message,
'link' => $link,
'picture' => $image,
'actions' => array('name' => 'Test', 'link' => 'Link')
);
try {
$access_token = $facebook->getAccessToken(); // returns valid access token
$uid = $facebook->getUser(); // always return 0
$result = $facebook->api( '/' . $_config['fb_profile'] . '/feed/', 'post', $attachment); // $_config['fb_profile'] procudes 'me' in this case
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
Just to note: I am not working on local environment.
problem solve it as asked in scope request to Facebook for authentication, as I decided to use the JavaScript SDK-and then, here's the solution:
FB.getLoginStatus(function(response) {
if ( ! response.authResponse ) {
FB.login(function(response) {
// handle the response if needed
}, {scope: 'publish_actions, publish_stream'});
}
});
Thank you! :-)

facebook application : get birthday

I would like to know how to get the date of birthday of the user of facebook.
Here is the code which deal with facebook api :
<?php require 'src/facebook.php';
define("FB_APP_ID","***");
define("FB_SECRET","***");
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_SECRET,
'cookie' => true,
));
$currentUser = $facebook->getUser();
if($currentUser) {
try
{
$facebook_profile = $facebook->api('/me');
$friends_fields = $facebook->api('/me/friends');
}
catch (FacebookApiException $e)
{
print_r($e);
$user = null;
}
}
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_birthday, birthday, date_birthday, email, offline_access, publish_stream'
)
);
$logoutUrl = $facebook->getLogoutUrl();
?>
I tried $facebook_profile['user_birthday'] and $facebook_profile['birthday']
But it does not work.
I don't know how to do ? Can you help me please ?
The correct permission for birthday is user_birthday
Verify you have the permission
$permissions = $facebook->api('/me/permissions');
$permissions["data"][0]["user_birthday"];
Seeing that you have facebook_profile, you should just dump the contents of that response to see what you do have.
Also ensure the user did set his/her birthday...
There's probably more than one way to do it, but you should be able to get the user's birthday from an FQL call via the SDK api() method:
$result = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT birthday_date FROM user WHERE uid = me()',
));
$birthday = $result[0]['birthday_date'];
You'll need to have user_birthday or friends_birthday permissions to read the birthday and birthday_date fields.

Facebook photo tagging app not tagging people

I have a facebook photo tagging app that used to work a few months ago but no longer does. The user authenticates the app and it uploads a picture on their facebook account and tags their friends. The app uploads the picture but stopped tagging for some reason.
require_once('facebook.php');
$_SESSION['init'] = true; $current_date=date('m/d/Y'); $facebook =
new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
$facebook->setFileUploadSupport(true);
$session = $facebook->getSession(); $tokenorig =
$facebook->getAccessToken();
$friends =
file_get_contents("https://graph.facebook.com/me/friends?access_token="
. $tokenorig);
$friends = json_decode($friends, true);
$friends = $friends['data'];
foreach($friends as $friend) {
$uids[] = $friend['id'];
}
function makeTagArray($userId) {
$x=1; $y=1;
foreach($userId as $id) {
$tags[] = array('tag_uid'=>$id, 'x'=>$x,'y'=>$y);
$x+=1;
$y+=1;
}
$tags = json_encode($tags);
return $tags;
}
$arguments = array(
'message' => 'hi guys ',
'tags' => makeTagArray($uids),
'source' => '#' .realpath('pic2.jpg'),
);
$alb = "13378";
uploadPhoto(
$facebook,
$alb,
$arguments,
$tokenorig);
function uploadPhoto($facebook,$albId,$arguments,$tokenorig) {
//https://graph.facebook.com/me/photos
try {
$fbUpload =
$facebook->api('/'.$albId.'/photos?access_token='.$tokenorig,'post',
$arguments);
return $fbUpload;
} catch(FacebookApiException $e) {
echo "eror";
echo $e;
// var_dump($e);
return false;
}
}
//////////end
First off all,
You need user's to authorize your application to upload photos and tag on behalf of them and
you need publish_stream and user_photos permissions to tag user's friends

Retrieving user information from facebook

I am doing a registration on my website via facebook.
When the user logs in via facebook the $user array returned is not exactly what i want.
I have gone through the user parameters that are accessible via facebook, i have tried implementing them also but it is not working.
This is a sample of what i have
require_once "Database_Connect.php";
if (!isset($_POST['choosepassword']))
{
# We require the library
$user=array();
require("facebook.php");
# my error tracker
$error=0;
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
$user = $facebook->api('/me');
} catch (Exception $e){}
if(!empty($user)){
# User info ok? Let's print it (Here we will be adding the login and registering routines)
print_r($user);
***At this point what is retrieved is not exactly what i want*****
$ue=$user['email'];$ui=$user['id'];
$query = mysql_query("select * from members where email = '$ue' or (oauth_provider = 'facebook' AND oauth_uid = '$ui')", $link);
$result = mysql_fetch_array($query);
# If not, let's add it to the database
if(!empty($result)){
$error = 2; //record already in database
require_once "facebook_error.php";
die();
}
} else {
# For testing purposes, if there was an error, let's kill the script
$error = 1; //we were unable to retrieve info frm facebook
require_once "facebook_error.php";
die();
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
*** I tried specifying what i want returned here, but it doesnt seem to work*****
$url = $facebook->getLoginUrl(array(
'req_perms' => 'uid, first_name, last_name, name, email, current_location, user_website, user_likes, user_interests, user_birthday, pic_big',
'next' => 'http://www.zzzzzzz.com/facebook_register.php',
'cancel_url' => 'http://www.zzzzzzz.com'
));
header("Location: ".$login_url);
}
What am i not doing right?
Thank You
Update
I am using FQL to select user info from facebook now,
$fql = "select uid, first_name, last_name, name, sex, email, current_location, website, interests, birthday, pic_big from user where uid=me()";
$param = array('method' => 'fql.query', 'query' => $fql, 'callback' => '');
$user = $facebook->api($param);
It retrieves all the data except the birthday and the email
How can i select the email and birthday?
Thanks
Your application needs the user_birthday and email permissions for this, else it will not return that information. You only need to supply parameters that need a permission, not what fields you want in the req_perms parameter, so it should look like this:
$url = $facebook->getLoginUrl(array(
'req_perms' => 'email, user_birthday',
'next' => 'http://www.zzzzzzz.com/facebook_register.php',
'cancel_url' => 'http://www.zzzzzzz.com'
));