I am using the following script from facebook example:
The script grabs the e-mail fine but hometown and location trigger a 500 error on my server. I need to grab the data for statistics.
<?php
$app_id = "API_ID_GOES_HERE";
$app_secret = "SECRET_GOES_HERE";
$my_url = "REDIRECT_URL_GOES_HERE";
$permissions ="user_hometown,user_location,email";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&scope=".$permissions.
"&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&scope=".$permissions. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
echo ("Location ". $user->location);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
I found the answer. Using this $user->hometown->name Will get the Hometown array and the Name object.
EX. [hometown] => stdClass Object ( [id] => 111806898837603 [name] => San Antonio, Texas )
$user->hometown->name
OUTPUT:
San Antonio, Texas
I would take the URLs you are creating to get the user info off the graph api (i.e. $graph_url) and paste them into your browser to inspect the data facebook is returning, and go from there. If the URL's are returning proper information, then you know you are getting the right data back. Use the Graph API Explorer (https://developers.facebook.com/tools/explorer) to test the URL's you are creating for the graph API. You can see what results look like with different permissions granted and code accordingly for the response. Hope that helps!
Related
I've read the facbeook blog post about how to handle expired access tokens here: https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
But a few things are not clear to me and it's making it difficult for me to progress. I've listed both the sample code from the blog, and my own php code. I'd mostly like to know just what changes I need to make to my code so the code from the blog will work in my own. I also have some questions about specific code from the blog. For starters where is $_REQUEST["code"] is coming from?
If you look at my code you'll see that I'm trying to send a notification to a user, I get the app access token before hand, and make the api call that sends the the access token along with it; but in the sample code the graph call gets made with curl_file_get_contents() instead of $facebook->api, what do I do about that? Does $facebook->api return the same kind of response as curl_file_get_contents()? Because the sample code checks that response for errors and redirects if there is one.
//PHP SAMPLE CODE FROM THE BLOG
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
//IS THIS SUPPOSED TO BE MY CANVAS APP URL?
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
//WHERE IS THIS $CODE VARIABLE COMING FROM?
$code = $_REQUEST["code"];
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// ATTEMPT TO QUERY THE GRAPH
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//CHECK FOR ERRORS
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
//MY PHP
$token_url ="https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APP_ID .
"&client_secret=" . $APP_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
$app_token = str_replace("access_token=", "", $app_token);
$data = array(
'href'=> 'https://apps.facebook.com/thebringernetwork/',
'access_token'=> $app_token,
'template'=> 'test'
);
// HOW DO I USE THAT ERROR CHECKING CODE AT THIS POINT?
$facebook->api('/16xxxxx3/notifications', 'post', $data);
I have this PHP code that i need help with
here is what i have
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookies' => 'true'
));
$FBuser = $facebook->getUser();
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . FB_APP_ID .
"&client_secret=" . FB_APP_SECRET .
"&grant_type=client_credentials";
So far so good.. but then i try
$permissions = $facebook->api("/me/permissions");
And i get the error
"An active access token must be used to query information about the current user."
I know the user has already installed my app. I must be missing something simple??
Thanks
Randy
This:
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . FB_APP_ID .
"&client_secret=" . FB_APP_SECRET .
"&grant_type=client_credentials";
Simply gets an access token for the APP. There is no user attached to this. Read this documentation about getting a user's login url. Then, the facebook SDK you have at that redirect_uri will finish the job for you, and get you an access_token. From there you just need to call $permissions = $facebook->api("/me/permissions"); and it should work just fine.
To be sure, after you get that access_token in your current script, run it in the debugger to ensure a user_id is tied to it.
I use c++ and libcurl to interact with face book.
I'm make a native windows application,so I can't use any facebook sdk.
Can I handle expired/invalidate access token by using graph api?
Yes, unless the user has de-authorized your ap.
read this Facebook: How-To: Handle expired access tokens
Just call the graph api
this is what happens in php, but i think you can translate it fairly easy
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
I have an application on Facebook where I select a picture and I can upload to an album associated with the application.
I found some code about it, but until now, I could upload only to my personal account.
With this code I can get all the album details of the application:
$facebook->api('/app_id/albums?access_token='.$acces_token);
That's cool, I get a list, but after this, I do the following:
$upload_photo = $facebook->api('/'.$album_id.'/photos?access_token='.$acces_token, 'post', $photo_details);
And I always get the following exeption:
Fatal error: Uncaught OAuthException: (#100) Invalid ID for album owner thrown in
What is the problem?!
Maybe I don't have the right permissions? Or am I missing something?
I even tried this:
$create_album = $facebook->api('/app_id/albums?access_token='.$acces, 'post', $album_details);
$album_uid = $create_album['id'];
$upload_photo = $facebook->api('/'.$album_uid.'/photos?access_token='.$acces, 'post', $photo_details);
Try this!! it creates a new album and then it posts a photo in that specific album..
$post_login_url = "http://apps.facebook.com/yourapp/thefile";
$album_name = 'name of Album';
$album_description = 'something about album';
$code = $_REQUEST["code"];
$facebook->setFileUploadSupport(true);
//Obtain the access_token with publish_stream permission
if(empty($code))
{
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url .
"'</script>");
}
else {
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $facebook->getAccessToken();
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$postdata = http_build_query(
array(
'name' => $album_name,
'message' => $album_description
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false,
$context));
// Get the new album ID
$album_id = $result->id;
//Show photo upload form and post to the Graph URL
$graph_url = "https://graph.facebook.com/". $album_id
. "/photos?access_token=" . $access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url. ' "method="POST">';
echo 'Adding photo to album: ' . $album_name .'<br/><br/>';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message" type="text"
value=""><br/><br/>';
echo '<input type="submit" value="Upload" /><br/>';
echo '</form>';
echo '</body></html>';
}
?>
When a user comes into my app via an apprequest, Facebook appends a request_id to the URL.
I am trying to access this object before the user authorizes my application. When I try to make the api call:
FB.api('/'+requestId, function(response){ console.log(response); });
it returns the following:
error: Object
message: "An access token is required to request this resource."
But I should have access since it was my app that sent the request in the first place!
I did some digging, and I noticed that on the PHP side, it will use the user_access_token if available, and the app_access_token otherwise.
Is this a security limitation (i.e: cannot expose the app_access_token on the client side) or am I doing something wrong?
Any insight would be helpful. Thanks!
when you make a request to /{user_id}/apprequests you have to have authorized the user already...
Since the request was created by your application - only your application can manage -ie delete or read requests that were sent. Essentially, before the user authorizes you app he/she is anonymous to your application - therefore it would not be possible to read that users requests because you "dont know" who they are...
Hope this helps...
The following blog posts describes how to interact with requests and should hopefully answer your questions.
http://developers.facebook.com/blog/post/464
<?php
$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$access_token = file_get_contents($token_url);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$user_id = $data["user_id"];
//Get all app requests for user
$request_url ="https://graph.facebook.com/" .
$user_id . "/apprequests?" .
$access_token;
$requests = file_get_contents($request_url);
//Print all outstanding app requests
echo '<pre>';
print_r($requests);
echo '</pre>';
//Process and delete app requests
$data = json_decode($requests);
foreach($data->data as $item) {
$id = $item->id;
$delete_url = "https://graph.facebook.com/" .
$id . "?" . $access_token . "&method=delete";
$result = file_get_contents($delete_url);
echo("Requests deleted? " . $result);
}
?>
You have access to the app generated requests as the user follows the request via your app token but you need the user token to access the rest of the users requests.