How to get facebook user details using access token - php

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.

Related

Storing Access Token

I have been trying to solve this problem for three days now, it's really simple for those who know the open graph api well. I'm new to Facebook integration but have some PHP experience.
Basically all I'm trying to do is retrieve the following information from users and store it in a database.
Facebook User ID:
Name
Gender
Email
I have done the user ID, name and gender by using:
$contents = file_get_contents ('https://graph.facebook.com/'.$user);
$json=json_decode($contents,true);
$userid = $json['id'];
$username = $json['name'];
$usergender = $json['gender'];
$useremail = $json['email'];
This works and I understand I need to ask for permissions to access the email which I have done using this code:
$app_id = "211665122244023";
$canvas_page = "http://apps.facebook.com/midcitymafia/";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=email,publish_actions";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
But how do I get the access token and then use it to retrieve email from graph?
##UPDATE, THIS IS MY CURRENT CODE, STILL CAN'T SEEM TO GET IT TO WORK...
require 'src/facebook.php';
$app_id = "211665122244023";
$canvas_page = "http://apps.facebook.com/midcitymafia/";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=email,publish_actions";
$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 {
$graph = json_decode(file_get_contents("https://graph.facebook.com/".$user_id . "/?accesstoken=" .$data['access_token']));
}
$userid = $graph->id;
$username = $graph->name;
$usergender = $graph->gender;
$useremail = $graph->email;
?>
<br>
<?php echo 'ID: ' . $userid; ?>
<br>
<?php echo 'Name: ' . $username; ?>
<br>
<?php echo 'Gender: ' . $usergender; ?>
<br>
<?php echo 'Email: ' . $useremail; ?>
signed_request contains user access_token within itself.
In your case access_token is in $data['access_token']
Storing user access_token isn't a best idea since they provided for a short period of time and expired later. To get permanent access_token you need to request offline_access permission from user (I personally wouldn't recommend it since you may achieve most things without requiring offline_access, in many cases Application access_token may fit your needs).

Facebook App for adding tab to page OAuth in Codeigniter

I am creating a facebook app for adding a tab on my facebook page. I am using Codeigniter Framework for that. I need access to some user info - email, education, etc in a particular page of my app. So, I need to authenticate only in that page and get the access token. In my attempt of doing that I am able to authenticate the user but unable to get the code sent by facebook oauth, which I need to get the access token. I think this is due to the fact that Codeigniter modifies the get array. I tried some ways to get the get array working but I was still unable to get the code contents.
Can you please give me a straight forward way to get an oauth token for the user in my app. I have tried to search a lot, but nothing worked.
So far this is the code I wrote:
$canvas_page = $page_url;
$signed_request = $_REQUEST["signed_request"];
$code = $this->input->get('code');
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page)."&scope=email,user_work_history,user_education_history";
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"])."<br/>";
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page). "&client_secret=" . $app_secret . "&code=" . $code;
$a = file_get_contents($graph_url);
var_dump($a);
}
Please give me a simple way to get the OAuth done. I want to spend more time developing that app than trying to figure out OAuth.
You may disable sanitization of GET but you probably doesn't want this.
As a quick and dirty solution you can do something like this:
parse_str($_SERVER['QUERY_STRING'], $args); // $args now contain GET parameters

Facebook Authorization for an iFrame App in PHP

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

Facebook Graph API call successfully returns my user information, but not my albums?

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

Accessing a user details from a page application

I have seen examples of accessing users data in canvas application with oAuth and graph api. But what I want to do is access user data such as the name, email address and photo within a page tab application. I have looked around and seen no examples. I am wondering if this is possible and how I would access the user data and yes I would like to do it through oAuth(asking them for the data).
Best Regards
It's the same exact way you do it for Canvas Apps:
<?php
$app_id = YOUR_APP_ID;
$canvas_page = YOUR_CANVAS_PAGE_URL;
$auth_url = "http://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 {
echo ("Welcome User: " . $data["user_id"]);
}
?>
If you need to access the user email just add the scope parameter (with the email permission) to your authentication url.

Categories