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.
Related
I am creating fb login with the php ,
the problem is that the email of user is not returning from facebook,
FBID and USER NAME is returning.
The same code i have done for another project is working but for the new one is not working
the code is like this
require 'src/facebook.php'; // Include facebook SDK file
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXX', // Facebook App ID
'secret' => 'XXXXXXXXXXXXXXXXX', // Facebook App Secret
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$fbid = $user_profile['id']; // To Get Facebook ID
$fbuname = $user_profile['username']; // To Get Facebook Username
$fbfullname = $user_profile['name']; // To Get Facebook full name
$femail = $user_profile['email']; // To Get Facebook email ID
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['USERNAME'] = $fbuname;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
header("location:fblogin.php");
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
));
header("location: " . $loginUrl);
}
$user_profile = $facebook->api('/me?fields=name,email');
It´s called "Declarative Fields", see changelog. Btw, you can´t get the username anymore.
I'm trying to run the sample code for Facebook connect that I downloaded from http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
I get this error message :
[error] => Array
(
[message] => An active access token must be used to query information about the current user.
[type] => OAuthException
[code] => 2500
)
You can try on my website : http://facebook.oliverjordan.net/thinkdiff
Here is the fbmain.php code :
<?php
//facebook application
$fbconfig['appid' ] = "463007877113xxx";
$fbconfig['secret'] = "-sensor-";
$fbconfig['baseurl'] = "http://facebook.oliverjordan.net/thinkdiff/index.php"; //"http://thinkdiff.net/demo/newfbconnect1/php/sdk3/index.php";
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$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.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user){
//get user basic description
$userInfo = $facebook->api("/$user");
//Retriving movies those are user like using graph api
try{
$movies = $facebook->api("/$user/movies");
}
catch(Exception $o){
d($o);
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$user/feed", 'post', array(
'message' => "I love thinkdiff.net for facebook app development tutorials. :)",
'link' => 'http://ithinkdiff.net',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
d($e);
}
$redirectUrl = $fbconfig['baseurl'] . '/index.php?success=1';
header("Location: $redirectUrl");
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_POST['tt'])){
try {
$statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['tt']));
} catch (FacebookApiException $e) {
d($e);
}
}
//fql query example using legacy method call and passing parameter
try{
$fql = "select name, hometown_location, sex, pic_square from user where uid=" . $user;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}?>
Can anyone help me?
You must ensure that your access token is active. Or maybe you're in logout condition. Or try to clean the cookies and cache from your browser (ctrl+shift+del)
Please check if you are getting any Facebook exceptions like
An active access token must be used to query information about the
current user.
which causes 0 as user id in return from $facebook->getUser().
So please check with getAccessTokenFromCode() from base_facebook.php and verify access_token_response format as it may be in JSON format.
So try to use appropriate decoding method to get $response_params['access_token'] from $access_token_response.
with my app's administrator acount on facebook my app work normally, but with other account I get error: Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
I had this problem before with other app (publish text on the user's wall), but fixed after i added
$user = $facebook->getUser(); What's wrong here? I have added offline_access permission... Help me, please if you can, Thank you very much.
<?php
require_once('images/Facebook.php');
$facebook = new Facebook(array(
'appId' => '456080124457246',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user_profile = $facebook->api('/me','GET');
$accessToken = $facebook->getAccessToken();
# Get User ID
$user = $facebook->getUser();
$facebook->setAccessToken($accessToken);
$facebook->api(456080124457246);
if ($user) {
try {
# Photo Caption
$photoCaption = $user_profile['name'] . ' patarimų plaukams sužinojo čia http://goo.gl/otwhf';
# Absolute Path to your image.
$imageUrl = 'http://padekime.wu.lt/plaukai/images/PlaukaiNeuzvedus.jpg'; // Example URL
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'url' => $imageUrl
);
$apiResponse = $facebook->api('/me/photos', 'POST', $post_data);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
In this case it's not even getting to your $facebook->getUser() call -- it's throwing an exception as soon as it reaches this line:
$user_profile = $facebook->api('/me','GET');
$facebook->api() is a bit of a tricky thing to work with because it throws an exception immediately if it doesn't know who "/me" is...even if you try to fix it later.
The trick, I think, is to wrap the entire thing in a try...catch block. Like so:
<?php
require_once('images/facebook.php');
$facebook = new Facebook(array(
'appId' => '456080124457246',
'secret' => 'xxxxx',
));
try {
$user_profile = $facebook->api('/me','GET');
# Get User ID
$user = $facebook->getUser();
if ($user) {
try {
# Photo Caption
$photoCaption = $user_profile['name'] . ' patarimų plaukams sužinojo čia http://goo.gl/otwhf';
# Absolute Path to your image.
$imageUrl = 'http://padekime.wu.lt/plaukai/images/PlaukaiNeuzvedus.jpg'; // Example URL
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'url' => $imageUrl
);
$apiResponse = $facebook->api('/me/photos', 'POST', $post_data);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
} catch (Exception $e) {
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload'
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
That'll redirect the user to the login url pretty much immediately, then come back with everything in tow. You don't have to set the accessToken with this setup.
This may actually unnecessarily repeat some functionality, but hopefully it's something to start with.
By the way, for what it's worth the offline_access permission is being phased out.
I stopped using "me" keyword to get the logged in user's profile.
instead of $facebook->api('/me','GET'), I changed to $facebook->api('/the facebook ID of the user','GET');
this reduce the need to do second try catch
If you do
if (!empty($user)) {}
That should help...
I use facebook sdk api with symfony, in the below $user_profile array he can retrieve every information but email and birthday.
require 'facebook.php';
$app_id = sfConfig::get('app_facebook_app_id');
$app_secret = sfConfig::get('app_facebook_secret_key');
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$location= $user_profile['location']['name'];
$gender = $user_profile['gender'];
$user_info = array(
'uid' => $user_profile['id'],
'first_name' => $user_profile['first_name'],
'last_name' => $user_profile['last_name'],
'email' => $user_profile['email'],
'birthday' => $user_profile['birthday'],
'gender' => $user_profile['gender'],
);
when I use print_r($user_profile) it return:
Array (
[uid] => 100004246655890
[first_name] => Ala
[last_name] => Hamad
[email] =>
[birthday] =>
[gender] => male
)
the email and birthday empty.
Nowhere in your code does it appear that you're requesting the Permission needed to access the user's email address or birthday
Check the permissions doc and make sure you're requesting the email and user_birthday permissions in your Authentication code.
If you don't receive these information, one of the cause is because the user configuration prohibits sharing them and Facebook don't send the warns.
Because some users, in the configuration, prohibits sharing the email or other information.
I searched for how to write that in code, then I found that I have to request email permission within the scope in the login url:
$params = array(
'redirect_uri' => url_for('sfGuardAuth/loginWithFB', true),'scope' => 'email,user_birthday,user_location'
);
$loginUrl = $facebook->getLoginUrl($params);
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'
));