I need to get the User ID of a user hitting a Facebook iFrame application. While sifting through all of the bogus and outdated information, I think I've come across the correct info.
When the user hits the page, I need to have them authorize the app. In my PHP I do this:
$facebook = new Facebook($appData);
$user = $facebook->getUser();
if(!$user) {
echo '<script>top.location.href="'.$facebook->getLoginUrl().'";</script>';
die();
}
This gives me the authorization request, but then pushes me back to my server, not the iFrame App's URL (http://app.facebook.com/blah). I manually constructed the URL and tried to set the URL to the app.facebook.com URI but then it I get an error saying the URL is not valid for the app.
How do you get it to redirect back to the app after authorization? This app will live inside Facebook, not be generally accessible outside, so I'm not looking for Facebook Connect login.
Edit
This is the exact error I get when I fiddle with the request_uri:
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
Have you tried setting the redirect_uri parameter.
if(!$user) {
$params = array('redirect_uri' => 'http://app.facebook.com/blah/');
die('<script>top.location.href="'.$facebook->getLoginUrl($params).'";</script>');
}
Go to:
http://developers.facebook.com/apps
In the your developer application settings on you need to change the URL settings so that Facebook knows your app is a canvas app. In the settings, be sure to delete all the URLs that are in the Web tab and then make sure that all the URLs are appropriately set in the On Facebook tab.
You can following sample code to authorize facebook application in an iframe app using graph api
<?php
ob_start();
session_start();
/*
* App Config
*/
$config= array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
'canvas'=>"http://apps.facebook.com/sampleapp/");
$GRAPH_URL = "https://graph.facebook.com/";
$scope = "publish_stream,email";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id=".$config['appId']."&redirect_uri=".urlencode($config['canvas']). "&scope=" . $scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if(is_array($data)){
$authToken = $data['oauth_token'];
$userId = $data['user_id'];
$_SESSION['auth_token'] = $authToken;
//check for permission//
$permissions = json_decode(curl_get_file_contents($GRAPH_URL . "me/permissions?access_token=" . $authToken), TRUE);
if(array_key_exists('publish_stream', $permissions['data'][0]) ) {
$post = array('client_id'=>$config['appId'],'redirect_uri'=>$config['canvas'].'','client_secret'=>$config['secret'],'type'=>'client_cred');
$token_url="https://graph.facebook.com/oauth/access_token";
$response = curlpost($token_url,$post);
$params = explode('&',$response);
if(isset($params[0])){
$token = explode('=',$params[0]);
if($token[0]=='access_token'){
$access_token = $token[1];
$_SESSION['access_token']=$access_token;
$_SESSION['authorized']=1;
echo("<script> top.location.href='" . $config['canvas']."home.php'; </script>");
}
}else{
echo("<script> top.location.href='" . $config['canvas']."error.php'; </script>");
}
}else{
$url='https://graph.facebook.com/oauth/authorize?client_id='.$config['appId'].'&redirect_uri='.urlencode($config['canvas']).'&display=page&scope=publish_stream,email&type=user_agent';
echo("<script> top.location.href='" . $url. "'</script>");
}
}else{
echo("<script> top.location.href='" . $config['canvas']."error.php';</script>");
}
?>
Check this link for details
http://forum.bharathlisting.com/showthread.php?tid=13&pid=20#pid20
Related
I am creating an app in facebook and when user enters my app then the authentication will happen and after that i will get the access token and id of user now i want the details of the same user and i have to store that in database .... how to do this
CODE I HAVE TRIED IS
<?php
$app_id = "xxxxxxxxxxx";
$canvas_page = "xxxxxxxxxxxxx";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)."&scope=email,user_birthday";
$signed_request = $_REQUEST["signed_request"];
//print_r($signed_request);
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
//print_r($payload);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
//print_r($data);
if(!isset ($_GET['code'])) {
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
$accessToken = $data["oauth_token"];
echo ("<br/><br/>Welcome User: " . $data["user_id"]);
}
} else {
echo("<script> top.location.href='" . $pageUrl . "'</script>");
}
?>
Now i want the username and other details in string or array format ...
Please help me....
Using this Graph api :
https://graph.facebook.com/me?access_token=XXXXXXXXXXXXXXX
You can choose the fields you want returned using the fields query parameter:
https://graph.facebook.com/me?fields=id,name
You can use the Facebook PHP SDK which automatically deal with this situation and sets the access token, or you may manually specify the access token using
setAccessToken($access_token) method
and pass it your user's access token and make Graph API call using api() method to get data about user. If you want to do away with the SDK then you need to add access token as parameter to Graph API end points.
I have created a simple Facebook application some weeks ago. I was getting user information through the Facebook API by asking permission from the users. But it stopped working last week out of nothing and I have been looking for an answer since then.
Basically I used to use file_get_contents to get the user information from Facebook API. But I tried changing it to cURL after it started failing, but still not working. I tried using the Facebook PHP-SDK, even debugged the code to makeRequest method, but I get the same return in all methods.
When a cURL request is made to Facebook Open Graph URL, the request fails either with error number 7 or 28. They are both error codes for unable to connect to the site or getting time out.
My site is on a shared hosting, I have tried using cURL to get other sites, and It works fine. But when I try to get even http://www.facebook.com, cURL returns FALSE.
The hosting has SSL certificate, has cURL enabled etc. And it was working fine some time ago. I have read through various threads and posts about this, tried many different cURL options, and none of them seem to work.
Any ideas?
index.php
$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($GLOBALS['canvas_page']) . "&scope=publish_stream,email";
$signed_request = $_POST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
$_SESSION['oauth_token'] = $data['oauth_token'];
$_SESSION['user_id'] = $data["user_id"];
$user = new User($_SESSION['user_id'], $_SESSION['oauth_token']);
User class
function __construct($fid, $at) {
$this->facebook = new Facebook(array(
'appId' => "<APP_ID>",
'secret' => "<FACEBOOK_SECRET_ID>",
));
$this->fid = $fid;
$this->token = $at;
if ($data = $this->getGraph()) {
...
}
}
public function getGraph() {
$session = $this->facebook->getUser();
if ($session) {
try {
$access_token = $this->facebook->getAccessToken();
$attachment = array('access_token' => $access_token);
//$result = $this->facebook->api('/' . $this->fid, 'GET', $attachment);
$result = $this->facebook->api('/' . $this->fid, 'GET');
return $result;
} catch (FacebookApiException $e) {
return false;
}
}
}
Notes:
After checking the Facebook PHP SDK methods, I've realized that I do not need to send access token, as it will set it if access token is not in the $params.
It goes down to makeRequest() method in sdk, and returns false from the curl_exec.
Apparently this is related with the round-robin DNS structure of Facebook. I guess one of the addresses of the Facebook failed and the server was still trying to connect to that address because of the DNS cache.
The hosting provider had to clear their DNS caches to resolve the problem.
For more information about the round-robin DNS, you may visit http://en.wikipedia.org/wiki/Round-robin_DNS.
I have a facebook iframe app which correctly logs in and authorizes the app, but getUser() only works on the first page. As soon as a user clicks a link to a new page within the iframe, getUser() returns 0.
What's strange is that this same code works for another app... I do all the clicking I want and getUser() returns a valid ID.
The app that doesn't work: https://apps.facebook.com/celestial_glory/
The one that does (same codebase): https://apps.facebook.com/uprisingstlouis/
Here's the code I am using:
require_once ('fb/facebook.php');
// snip... set $app_id, $secret, and $canvas_page
// first, try normal facebook getUser(). If that works, awesome.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
$signed_request = $_REQUEST['signed_request'];
// Get User ID
$user = $facebook->getUser();
if ($user != '0') return 'fb=' . $user; // works once
// getUser() didn't work. Try oAuth. Maybe user needs to log in or
// authorize the game?
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($canvas_page);
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo '<a target="_top" href="' . $auth_url . '">Login to Facebook</a>';
exit;
// normally we would auto-redirect, but with a uid of 0, this just auto-redirects
// echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
return 'fb=' . $data['user_id'];
}
any ideas? I have triple-checked app ids and secrets and canvas pages. If those were wrong, I expect no page, not even the first, would work.
Change Facebook PHP-SDK initialization to:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true // this!
));
getUser works on the first page because it can get the user from signed_request (POST'ed by Facebook to your canvas page URL). Thus you need some way to track your user once he starts navigation deeper within your application. You could pass signed_request somehow all by yourself or simply enable built-in PHP-SDK cookie support as suggested above.
i have a problem with my facebook canvas app that is currently on development i'm working on http://localhost:8080
my canvas url is http://localhost:8080/fbcanvas/
on facebook the url is set to http://apps.facebook.com/app_name/
the problem is i'm getting a code as an $_GET['code'] variable after a user approves my app.
in facebook documentation it doesnt say anything about getting a $_GET['code'] it just says getting signed_request
this is the code i'm using from facebook examples.
require_once($_SERVER['DOCUMENT_ROOT'] . '/classes/Page.php');
require($_SERVER['DOCUMENT_ROOT'] . '/core/config.fb.php');
$canvas_page = 'http://apps.facebook.com/khawamusic/';
$auth_url = 'https://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
$signed_request = $_REQUEST['signed_request'];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if(empty($data['user_id'])) {
echo('<script> top.location.href="' . $auth_url .'";</script>');
} else {
$page = new Page;
$styles = array('reset.css', 'fbcanvas.css');
$scripts = array(
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js',
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'/sources/js/fbcanvas.js'
);
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
}
so what happens is a user approves my app then he gets redirected to http://apps.facebook.com/khawamusic/?code=blabla
i'm cnfused because in the documentation it doesn't say i'm suppose to get a $_GET['code']
If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with an authorization code:
http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
Refer: https://developers.facebook.com/docs/authentication/
EDIT:
Here's a sample of the authentication, this won't show ?code=Blabla..
First download the latest Facebook PHP SDK from here: https://github.com/facebook/php-sdk/tree/master/src
Make sure you save all 3 files, facebook.php, base_facebook.php and fb_ca_chain_bundle.crt
Now replace the text "YOUR_APP_ID" and ""YOUR_APP_API_SECRET" with your Application ID and App Secret from facebook, I've added sample wall posting using graph api, if you don't want, you can remove it, if you go through my codes and comments, you'll understand what it does and you don't want to do anything to get access token, just use $access_token variable and it'll give you the access_token of the current user and if you want the user's ID then use $user variable, if you want user's basic information, use $userInfo variable and it'll fetch user's data using graph api and returns all information in an array, you'll get the current user's info like id,name,first_name,last_name,link,hometown,location,bio,work,education,gender,timezone.etc.
Change $RedirectUrl with your landing page URL or your canvas page url
<?php
require 'facebook.php';
define('FACEBOOK_APP_ID', "YOUR_APP_ID"); // Your App ID
define('FACEBOOK_SECRET', "YOUR_APP_API_SECRET"); // Your App API Secret
$RedirectUrl = "http://apps.facebook.com/myapp/"; // Your Landing Page URL, User's will be redirect to this URL after they allow your app.
function d($d){
echo "<pre>";
print_r($d);
echo "</pre>";
}
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if(isset($_GET['code'])){
header("Location: $RedirectUrl");
}
if($user == 0) {
// If User is not connected to your app, then redirect User to Authentication Page.
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream", 'redirect_uri' => $RedirectUrl));
echo("<script> top.location.href='" . $login_url . "'</script>");
} else {
// If User is connected to your app, then do something.
$signed_request = $facebook->getSignedRequest(); // Get the data from a signed_request token.
$access_token = $facebook->getAccessToken(); // Determines the access token that should be used for API calls.
$userInfo = $facebook->api("/me"); // Get's User Info
try {
// Posts to user's wall after the user allows your app.
$wallpost = array(
'message' => "I like this",
'link' => 'http://google.com',
'picture' => 'http://i.imgur.com/8iz6L.png',
'name' => 'This is cool',
'description'=> 'Checkout this cool app'
);
$publishStream = $facebook->api("/$user/feed", "post", $wallpost); // WallPost to User's Wall using Graph API
echo "Your post was successfully posted to UID: $user";
}
catch (FacebookApiException $e) {
d($e);
}
}
?>
i'm not yet sure but i think i have the answer to the process of authorizing / authenticating a facebook app...
step 1 : the first time a user access your app facebook sends you a signed request and you need to parse it validate it and check if the $data['user_id'] is set.
the code:
$data = $canvas->parse_signed_request($signed_request);
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
if(empty($data['user_id'])) {
echo '<script>top.location.href="' . $auth_url . '"</script>';
}
so if the $data['user_id'] is empty go authenticate.
step 2: the user authorizes your app facebook sends you a signed request and a code
if(isset($_REQUEST['code'])) {
$access_token = $canvas->get_access_token($_REQUEST['code']);
$user = $canvas->getUser($access_token);
$user_info = array(
'user_id' => $user->id,
'user_username' => $user->username,
'user_name' => $user->name
);
// install the application for the new user.
$user_obj = new User($user_info);
// registered or allready exists.
if($user_obj) {
echo '<script>top.location.href="' . $canvas->canvas_page . '";</script>';
}
exit();
}
so from what i understood facebook sends you $_REQUEST['code'] just one time: when the user approves your canvas application.
that's it the user is installed so now every time a user re enters your application you will get a signed_request
but this time because the user already approves the application the signed request will include an user_id and oauth_token with it u can get stuff from the graph api.
IF THE SIGNED_REQUEST HAVE A USER_ID THIS IS WHAT U DO.
if(isset($data['user_id'])) {
$user = false;
if(!$user) {
$user = $canvas->getUser($data['oauth_token']);
}
if(!ob_start('ob_gzhandler')) ob_start();
$styles = array(
'reset.css', 'jplayer.fbcanvas.css', 'fbcanvas.css'
);
$scripts = array(
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js',
'/sources/js/jplayer/jquery.transform.js',
'/sources/js/jplayer/jquery.grab.js',
'/sources/js/jplayer/jquery.jplayer.js',
'/sources/js/jplayer/mod.csstransforms.min.js',
'/sources/js/jplayer/circle.player.js',
'/sources/js/fbcanvas.js'
);
$results = $canvas->getLatestSongs();
// the canvas.
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
ob_end_flush();
}
again i'm not sure but i think this is the process of authentication for FACEBOOK CANVAS APPS.
The question is: is it my brain? Or Facebook's infuriating API?
Intention:
Return my facebook album information and my user information
result: empty data set for album information, full result's for user information
{
"data": [
]
}
<?php
/****************************************************************************
Application settings
****************************************************************************/
$app_id = '123456';
$app_secret = "4543163864";
$my_url = "http://www.myurl.com/app";
$canvas_page = 'http://apps.facebook.com/my_canvas_page/';
# authorize the user using oauth protocol (including required permissions)
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)."&scope=user_photos,friends_photos";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$fb_user_session = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
# if authorization failed, kick back to auth_url
if (empty($fb_user_session["user_id"]))
{
echo("<script> top.location.href='" . $auth_url . "'</script>");
}
else
{
/****************************************************************************
User successfully logged in.
****************************************************************************/
$my_albums = "https://graph.facebook.com/me/albums?access_token=".$fb_user_session['oauth_token'];
$my_info = "https://graph.facebook.com/me?access_token=".$fb_user_session['oauth_token'];
echo "<a href='$my_albums'>my album information</a><br>";
echo "<a href='$my_info'>my user information</a>";
### ignore this, just testing iframe call ###
exit;
echo("<script> top.location.href='" . $my_albums . "'</script>");
}
?>
Additional information:
Testing an 'album' request from http://developers.facebook.com/docs/reference/api/user/ while logged in works! It successfully returns all my album info. But I noticed the authorization token in the test URL is different from my retrieved application token ($fb_user_session['oauth_token']). What is going on here?
Am I missing some kind of authorization step? Why would my application return empty data for my albums using the exact same call & token while Facebook's test call returns a full set? If anyone can help solve this problem once and for all, that would be awesome.
Any ideas?
Try adding "user_photo_video_tags" to the list of scopes requested. Also, try calling the permissions api call to make sure you have access to the user's photos by checking the "user_photos" permission.
The url is: https://graph.facebook.com/me/permissions?access_token=...