app authorization with PHP sdk - php

I'm using the latest Facebook PHP SDK and want to simply access user data:
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'yyy',
'cookie' => true
));
$user = $facebook->getUser();
if ($user) { // Checks if there is already a logged in user
try {
// Proceed knowing you have a logged in user who's already authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
else {
//Ask for bare minimum login
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
My problem is that the $user is FB logged in, but $facebook->api('/me') not only fails, but I don't get the App authorization dialog either.
What am I doing wrong?

Eventually found my error so for the record:
$facebook = new Facebook(array(
'appId' => 'xxxx',
'secret' => 'yyyyy',
'cookie' => true
));
$user = $facebook->getUser();
if ($user) { // Checks if there is already a logged in user
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
// Will throw the very first time as the token is not valid
error_log($e);
$user = null;
}
}
// $user is null : $user is either not logged in or the token is not valid
if(!$user) { //Ask for bare minimum login
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}

Try the FB demo script at : https://github.com/facebook/facebook-php-sdk/blob/master/examples/example.php
See if that works

Related

Facebook app doesn't pop up for permissions

Everything works fine with test users but when I publish my app and user clicks on app the permission popup dialog box does not appear. I guess there is some oauth problem but not sure. Please help me out
require 'facebook-files/facebook.php';
$app_id='xxxxxxxxxx';
$secret='xxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie'=> true,
'grant_type' => 'client_credentials'
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
//$access_token = $facebook->getAccessToken();
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends?fields=id,name,birthday,picture');
$event = $facebook->api('/me/?fields=events.fields(id,name)');
} catch (FacebookApiException $e) {
echo "Exception".error_log($e);
$user = null;
exit;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'read_stream,publish_actions,publish_stream,user_birthday,friends_birthday', 'display'=>'popup')
);
}
Make sure to add your site to the "valid oauth redirect uris" input field in your app's settings.

An active access token must be used to query information about the current user

I keep getting the error in the title, while using a simple code:
require_once('sdk/src/facebook.php');
require_once("AppInfo.php");
function idx(array $array, $key, $default = null) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
function he($str) {
return htmlentities($str, ENT_QUOTES, "UTF-8");
}
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'sharedSession' => true,
'trustForwarded' => true,
));
$arrayForJSON=array();
$user = $facebook->getUser();
$friends = idx($facebook->api('/me/friends'), 'data', array());
if ($friends) {
$arrayForJSON['friends']=$friends;
}
print_r($friends);
I really don't know how to solve it, I've been searching and trying many answers on stackoverflow
You need to set the access token to be able to get data or act on behalf of the user. Are you going through a login flow to allow authorization to your Facebook application?
Try the example at https://developers.facebook.com/docs/reference/php/facebook-api/
It provides the very basic login flow that will grant access to the data you're seeking.
you need to check if already login if not redirect the user to login link
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '191149314281714',
'secret' => '73b67bf1c825fa47efae70a46c18906b',
));
// 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');
$friends = idx($facebook->api('/me/friends'), 'data', array());
} 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'=>'offline_access'));
}

Facebook authentication fails

I'm about to give up. for about a week i'm trying the simplest thing, authentication via facebook. every time I authenticatiom (via facebook login url) , getUser() and api('me'
) returns me null.
why?
the code:
$facebook = new Facebook(array(
'appId' => '306597542762982',
'secret' => '88XXXXXX7f1',
));
$user = $facebook->getUser();
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;
}
}
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'user_actions.news,publish_stream,user_about_me,email,publish_actions'));
print $loginUrl; exit;
}
var_dump($facebook->api('me'));
SOS.
EDIT: POST :
$params = array (
'article' => 'http://fb.raal.co.il/content/view/$id/$title',
'access_token' => $facebook->getAccessToken()
);
$out = $facebook->api( '/me/news.reads','post', $params);
var_dump($out); exit;
Continuing what NullPointer quoted earlier, from user ifaour:
Just check for the current Facebook user id $user and if it returned null then you need to reauthorize the user (or use the custom $_SESSION user id value - not recommended)
require 'facebook/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
$photo_details = array('message' => 'my place');
$file='photos/my.jpg'; //Example image file
$photo_details['image'] = '#' . realpath($file);
if ($user) {
try {
// We have a valid FB session, so we can use 'me'
$upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
// redirect to Facebook login to get a fresh user access_token
$loginUrl = $facebook->getLoginUrl();
header('Location: ' . $loginUrl);
}
I've written a tutorial on how to upload a picture to the user's wall.
With the additional information, does this help? There is additional information I've found related to this, stating to attempt
$facebook->getAccessToken();
Apparently, that call can give either an app access token or a user access token. Depending on what you are trying to do with the access token, you will need the appropriate kind.
Alternatively, you may need to request certain permissions for what you are trying to do, which you can find here.

Use facebook's php SDK to retrieve email

So far i have it set up to retrieve basic user info, nothing extended. Im trying to get the user email as well, with no success. Here's what i got:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$session = $facebook->getSession();
if (!empty($session)) {
try {
$params = array(
'scope' => 'email',
'redirect_uri' => 'https://www.dormduels/splash_test'
);
$loginUrl = $facebook->getLoginUrl($params);
$uid = $facebook->getUser();
$access_token = $facebook->getAccessToken();
echo $access_token;
$user = $facebook->api('me?fields=name,first_name,last_name,username,email&access_token='.$access_token);
echo "<pre>";
print_r($user);
exit();
The problem is. the getAccessToken that its displaying, when tested in facebooks graph explorer, doesnt show extended data like email, only basic. How do i request a more permission enabled acces token?
On my side, i do it this way:
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => FB_API_KEY,
'secret' => FB_API_SECRET,
));
// Get User ID
$fb_user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $fb_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 ($fb_user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$fb_user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($fb_user) {
$fb_loggedin = true;
} else {
$fb_loggedin = false;
$fb_loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_location',
'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].'/debut_'.($lang == 'fr' ? 'fr' : 'eng').'.php'
));
}
The SCOPE in the getLoginUrl is what you want to look at, you can see all the different permissions on the developer site at:
https://developers.facebook.com/docs/authentication/permissions/
Good luck
You need to ask for extended permissions, namely "email" for here in one of the following ways:
php sdk
Use the getLoginUrl() method of the sdk object, and specify the extended permissions you need in the 'scope', and redirect the user to its return value, Also you need to add the domain and the site url in your facebook app's admin page. Here's an example:
define('APP_ID', 'TODO FILL IT WITH YOURS');
define('APP_SECRET', 'TODO FILL IT WITH YOURS');
require_once 'facebook.php';
function redirect_to_login($fb){
$login_url = $fb->getLoginUrl(array(
'scope' => 'email',
));
header('Location: '.$login_url);
exit;
}
$fb = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$uid = $fb->getUser();
if (!$uid || !check_perms($fb, $uid, array('email'))) { // see check_perms below
// send users to login/auth page if they are not logged in,
// or not installed the app,
// or don't have all the perms we need
redirect_to_login($fb);
}
try {
$me = $fb->api('/me');
var_dump($me);
} catch (Exception $e) {
redirect_to_login($fb);
}
js sdk
Use the FB.login() function to ask for the extended permissions you need, in the second parameter.
For detailed information on the whole authentication process, see this page.
If you want to check if the current user has the all the permissions you want, you can use FQL like this:
function check_perms($facebook, $uid, $perms = array()) {
$perms_str = join(' = 1 and ', $perms).' = 1';
$query = "select uid from permissions where uid = '".$uid."' and ".$perms_str;
try {
$row = $facebook->api(array(
'method' => 'fql.query',
'query' => $query,
));
return $row && $row[0]['uid'] == $uid;
} catch (Exception $e) {
return false;
}
}
note:
Your php sdk version probably is outdated, the getSession() method have been deprecated in favor of getUser() / getAccessToken()
Try following:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
public function login() {
$loginUrl= $facebook->getLoginUrl(array('scope' => 'email',
'redirect_uri' => 'your redirectUri',
'display' => 'popup'
));
header("Location:$loginUrl");
}
public function fUserInfo() {
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api('/me/permissions', 'GET', array('access_token' => $access_token));
$permissions_needed = array('email');
foreach ($permissions_needed as $perm) {
if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
login();
}
}
$user = $facebook->getUser();
if ($user) {
try {
$userInfo = $facebook->api("/$user");
} catch (FacebookApiException $e) {
Config::getLogger()->debug($e->getMessage());
}
}
print_r($userInfo);
}

How to use facebook connect on mobile web application using the OAuth Dialog

Now I'm developing a mobile web application using facebook connect, but I am having problems with the OAuth Dialog. I use the following facebook documents for my reference:
http://developers.facebook.com/docs/guides/mobile/#web
I choose to use the OAuth Dialog instead of the Login Button because mobile browsers do not recognize the FBML (I use the Blackberry browser on testing). The OAuth Dialog also lets me add a list of permissions within the parameters of scope. But the problem is when I've logged in using the OAuth Dialog, the parameter $me wasn't recognized so that the login button still appears and doesn't not change to the logout button.
Here is an example of my code:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$accessToken = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
error_log($e);
}
}
if ($me) {
echo "<img src=\"images/logoutFB.gif\">";
} else {
echo "<img src=\"images/loginFB.gif\">";
}
Is the parameter $me can't be used if I use the OAuth Dialog to connects to facebook?
So how do I know that I am already logged into facebook or not if I use the OAuth Dialog?
Please help if you guys have the solution.
Looks like you need to use the updated PHP-SDK
getSession() has been replaced by getUser():
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}

Categories