PHP Facebook API - Email return null - php

I have code like this:
$helper = new FacebookRedirectLoginHelper('http://MyAwesomeWebsite.com/' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
echo print_r($ex);
} catch( Exception $ex ) {
echo print_r($ex);
}
if ( isset( $session ) ) {
$request = new FacebookRequest( $session, 'GET', '/me?locale=en_US&fields=name,email' );
$response = $request->execute();
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID
}
But every time $femail is null. Why? What I'm doing wrong?

When you log in the user, you have to pass along the email permission in the scope parameter.
So when you call your helper, also initialise a $permissions array:
$helper = new FacebookRedirectLoginHelper('http://MyAwesomeWebsite.com/' );
$permissions = ['email', 'public_profile'];
There should be $helper->getLoginUrl call in somewhere in your code. In that call you should pass the $permissions variable as the second parameter:
$loginUrl = $helper->getLoginUrl($placeYourCallbackURLHere, $permissions);
That asks the user explicitly for a permission to get the user's email. Note that the email can also be empty, if the user has:
Registered to Facebook via phone number (does not have email address in Faceebook)
Selected that they do not want to provide the email address at the login prompt.

Related

Unable to login through facebook php sdk

While login wiht fb php sdk, I am getting such kind of error
This page isn’t working
www.facebook.com is currently unable to handle this request.
HTTP ERROR 500
I had configure my app and my secret key properly according to facebook app and key.
I am not getting why such kind of error is thrown. Please Help me
// init app with app id and secret
FacebookSession::setDefaultApplication(
myappkey,mysecretkey );
// login helper with redirect_uri
$helper = new
FacebookRedirectLoginHelper('http://demos.krizna.com/1353/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
/* ---- header location after session ----*/
header("Location: index.php");
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}

How do I navigate through a facebook $graphObject array and sort it

So I've been playing around with the Facebook API and have found that it's not easy! It's very hard to get a grip of it all. So I've managed to get the users id, name, email, friends, movies, and music.
/me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5)
But I found that it doesn't actually return the most useful data. It will return the data in any random order. Which is annoying. I was wondering if there is a way to sort the Movies and Music based on the likes (Most likes to least likes)?
At this stage all I've been able to do is print the users data using print_f($graphObject, 1). It would be really usefull if I could sort the Movies and Music based on the likes those pages have.
I'll add my code so everyone can see where im upto with the FB api - As you'll see, not very far. But I want to get to know it a lot more. It's very useful!
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( 'App_ID','SECRET_KEY' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://localhost/PHP_Advanced/Facebook/' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest(
$session,
//Add permissions to this - All gets returned as json object
'GET', '/me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5)'
);
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
//Store basic user info to then put into database
$userID = $graphObject['id'];
$userName = $graphObject['name'];
$userEmail = $graphObject['email'];
echo "Hello ".$userName;
echo "hello " . $data;
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
?>
</body>
</html>
Use {likes, name} to return likes count along with movie/music data.
Eg:
me?fields=id,name,email,movies.limit(5){likes,name},music.limit(5){likes,name}
After that you can sort json data based on likes.
Sample code:
<?php
$output = '{"id":"100004827362122","name":"FirstName LastName","email":"email#domain.com","movies":{"data":[{"likes":725577,"name":"Canal D2M","id":"253861394671560"},{"likes":4514156,"name":"UTV Motion Pictures","id":"82457488277"},{"likes":48573,"name":"Unfreedom","id":"204640696244906"},{"likes":13677504,"name":"Star Wars","id":"263361123833008"},{"likes":246922,"name":"Shudh Desi Endings","id":"162737470589326"}],"paging":{"cursors":{"before":"MjUzODYxMzk0NjcxNTYw","after":"MTYyNzM3NDcwNTg5MzI2"},"next":"https://graph.facebook.com/v2.2/100004827362122/movies?pretty=0&fields=likes,name&limit=5&after=MTYyNzM3NDcwNTg5MzI2"}},"music":{"data":[{"likes":2215,"name":"WDL","id":"1472840169599887"},{"likes":113860,"name":"Daniel Waples - Hang in Balance","id":"161974437185126"},{"likes":229799,"name":"KEXP","id":"9054273111"},{"likes":1276105,"name":"The Movement","id":"253878101400547"},{"likes":13294164,"name":"Virgin Radio Lebanon","id":"275155342593810"}],"paging":{"cursors":{"before":"MTQ3Mjg0MDE2OTU5OTg4Nw==","after":"Mjc1MTU1MzQyNTkzODEw"},"next":"https://graph.facebook.com/v2.2/100004827362122/music?pretty=0&fields=likes,name&limit=5&after=Mjc1MTU1MzQyNTkzODEw"}}}';
$output = json_decode($output, true);
$movies = $output['movies']['data'];
function sortData($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
usort($movies, 'sortData');
echo "<pre>";
print_r($movies);
?>

Graph API Get all photos

i have a website where people can upload pictures to be rated/liked etc. I am developing a function where if they don't want to upload pictures they can import them from there Facebook account.
I can login/logout the user from Facebook using the PHP Graph API but i am not sure on the request i need to get the logged in persons photos. I have setup the login url to the user_photos permissions.
I had a feature like this a few years ago where i would use the FQL to query the images but now i am using the new Facebook v4 Graph API.
Any help will be appreciated.
FacebookSession::setDefaultApplication( 'ID', 'SECRET' );
$helper = new FacebookRedirectLoginHelper('URL');
$permissions = array(
'user_photos'
);
try {
if ( isset( $_SESSION['access_token'] ) ) {
// Check if an access token has already been set.
$session = new FacebookSession( $_SESSION['access_token'] );
} else {
// Get access token from the code parameter in the URL.
$session = $helper->getSessionFromRedirect();
}
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error.
print_r( $ex );
} catch( \Exception $ex ) {
// When validation fails or other local issues.
print_r( $ex );
}
if ( isset( $session ) ) {
// Retrieve & store the access token in a session.
$_SESSION['access_token'] = $session->getToken();
// Logged in
echo 'Successfully logged in!';
} else {
// Generate the login URL for Facebook authentication.
$loginUrl = $helper->getLoginUrl($permissions);
echo 'Login';
}
After user has made the login you can get photos like so:
FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
$session = new FacebookSession($access_token);
$response = (new FacebookRequest($session, 'GET', '/me/photos?fields=source&limit=100'))->execute();
$object = $response->getGraphObject();
$arr = self::convertToAssoc($object);
put in the limit param your value.
here is how you convert the facebook-object:
public static function convertToAssoc($graphObject){
$arr = $graphObject->asArray();
if ( !array_key_exists('data', $arr) ){
$arr['data'] = '';
}
$arr_data = $arr['data'];
$data = [];
foreach($arr_data as $item){
$data[] = get_object_vars($item);
}
return $data;
}

how to implementation "graph.facebook" in php file

i want to use http://graph.facebook.com/XXX in my site
how i do a php file that have use this system and show my facebook details when i enter the link?
XXX = userrname
i want that the site show the details of the facebook user that enter the site
i tried everything but nothing, i dont want to make ap like this:
<?php
session_start();
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
// https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/
// initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
// now we create a second request to get the posted message in return
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
// use this for testing only
//unset($_SESSION['fb_token']);
thanks,
mtj

SDK 4.0 Facebook, no dialog to request permission publish_actions

I created an app on facebook and via PHP SDK 4.0 I created the login and I need to have write permissions on the feed, but even we have added the permissions, when I do not log apparre the more window box to approve and grant permissions .
this is the code used:
<?php session_start();
require 'Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('XXXXXXXXXX XXXXXXXX','XXXXXXXXXXXXXXXXXX');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'XXXXXXXXXXXXX' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo print_r( $graphObject, 1 );
if($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'www.example.com',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
} else {
$params = array(
scope => 'publish_actions'
//redirect_uri => $url
);
// show login url
echo 'Login';
}
?>
publish_actions should be approved by facebook for your application if you have already submitted for approval facebook might take upto a week till then you can't publish stories on facebook user's timeline.

Categories