Facebook redirect with extended permissions - facebook

I am trying to work out facebook connect based on this tutorial:
http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
They have given you a few scripts to use to figure it out, this is the extended permissions one:
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => '...',
'secret' => '...',
'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();
# req_perms is a comma separated list of the permissions needed
$url = $facebook->getLoginUrl(array(
'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'
));
header("Location: {$url} ");
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
When I execute this it lets me allow the extended permissions but then I get a redirect loop error. When I check in facebook it has granted extended permissions.
Now I tried to just implement it into the login script they gave, which is this
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => '...',
'secret' => '...',
'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)){
# We have an active session, let's check if we have already registered the user
$query = mysql_query("SELECT * FROM users WHERE oauth_prov = 1 AND oauth_id = ". $user['id']);
$result = mysql_fetch_array($query);
# If not, let's add it to the database
echo $user['id'] . $user['name'];
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_prov, oauth_id, username) VALUES ('1', {$user['id']}, '{$user['name']}')");
$query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
}
// this sets variables in the session
$_SESSION['id'] = $result['id'];
$_SESSION['oauth_uid'] = $result['oauth_id'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['username'] = $result['username'];
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
However, I don't know where it should go, as I would like to request permissions at the same time as the login to get the users details. If I put this:
try{
$uid = $facebook->getUser();
# req_perms is a comma separated list of the permissions needed
$url = $facebook->getLoginUrl(array(
'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'
));
header("Location: {$url} ");
} catch (Exception $e){}
After I set the session values then I don't even get to allow anything, it just hangs and I get a redirect error.
If I put it just after getting the facebook user_id then it gives me the allow dialog (although one after the other as its obviously asking twice, something I would like to stop) but then again gives me a redirect error, having granted the extended permissions
I really don't have a clue where to put it, the documentation for facebook is absolutely abysmal

Instead of this:
# req_perms is a comma separated list of the permissions needed
$url = $facebook->getLoginUrl(array('req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'));
try:
$url = $facebook->getLoginUrl(array('scope' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'));
for an complete example see the php-sdk:
https://github.com/facebook/php-sdk/blob/master/examples/example.php

Related

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

Facebook. Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user

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...

Facebook request access token and get email

I have a facebook login script for my site that currently works fine. I want to add the ability to request the email from user, along with the current basic info. I know i need to request an access token, but icant quite figure out how. Here's my current code:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$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/');
You have to provide an extended permission for email at the time of login..
$access_token = $this->facebook->getAccessToken();
//check permissions list
$permissions_list = $this->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 = $facebook->getLoginUrl(array('scope' => 'email,user_birthday',
'redirect_uri' => your site redirectUri,
'display' => 'popup'
));
header("location:$login");
}
}
$user = $facebook->getUser();
if ($user) {
try {
$userInfo = $facebook->api("/$user");
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
print_r($userInfo);
Have a look at the server-side authentication process - this is where you pass through the permissions you want (known as "scope"). The user will be presented with a login panel if they are not already logged in, and then afterwards a separate permissions panel for any permissions above basic you are requesting and that they haven't already granted. You will then receive an auth token or a code that can be exchanged for a token, and you use this to then further query the user and get their email details in the response.
Good luck!

How do i spot the case when the user authorized the application but the secret was wrong in PHP?

In my application i need to handle all various cases. I have no problems with the standard cases, i'm having some problem with edge cases, for example
the app secret has been inputted wrong
The user deauthorized my app
This is my code
//I have already checked that the app id is valid
require AI1EC_LIB_PATH . '/facebook-php-sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $plugin_settings['facebook-app-id'],
'secret' => $plugin_settings['facebook-app-secret'],
));
// 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' );
} catch ( FacebookApiException $e ) {
error_log( json_encode( $e->getResult() ) );
$user = NULL;
}
}
// Login or logout url will be needed depending on current user state.
if ( $user ) {
$logout_url = $facebook->getLogoutUrl();
echo "OK!";
} else {
$params = array(
'scope' => 'user_events, friends_events',
);
$login_url = $facebook->getLoginUrl( $params );
$args = array(
'login_url' => $login_url,
);
$ai1ec_view_helper->display_admin( 'plugins/facebook/user_login.php', $args );
}
Where should i put the handling of particular errors?I would love to show a nice message to the user like "Something went wrong, check if your entered your app secret correctly" or "You have deauthorized your app". Maybe it's in the catch() block that y should do that but i don't know what codes to check.
Anyone can help?

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'
));