Reputation: 580
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; ?>
Upvotes: 0
Views: 1358
Reputation: 25918
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).
Upvotes: 1