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>';
}
?>
Related
I am following Justin Slope's API Tutorial which was made in 2020.
This is the code that I pasted with some changes on the redirect URLs and using a site that is ok with the developer website.
$creds = array(
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v3.2',
'persistent_data_handler' => 'session'
);
// create facebook object
$facebook = new Facebook\Facebook( $creds );
// helper
$helper = $facebook->getRedirectLoginHelper();
// oauth object
$oAuth2Client = $facebook->getOAuth2Client();
if ( isset( $_GET['code'] ) ) { // get access token
try {
$accessToken = $helper->getAccessToken();
} catch ( Facebook\Exceptions\FacebookResponseException $e ) { // graph error
echo 'Graph returned an error ' . $e->getMessage;
} catch ( Facebook\Exceptions\FacebookSDKException $e ) { // validation error
echo 'Facebook SDK returned an error ' . $e->getMessage;
}
if ( !$accessToken->isLongLived() ) { // exchange short for long
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken( $accessToken );
} catch ( Facebook\Exceptions\FacebookSDKException $e ) {
echo 'Error getting long lived access token ' . $e->getMessage();
}
}
echo '<pre>';
var_dump( $accessToken );
$accessToken = (string) $accessToken;
echo '<h1>Long Lived Access Token</h1>';
print_r( $accessToken );
} else { // display login url
$permissions = [
'public_profile',
'instagram_basic',
'pages_show_list',
'instagram_manage_insights',
'instagram_manage_comments',
'manage_pages',
'ads_management',
'business_management',
'instagram_content_publish',
'pages_read_engagement'
];
$loginUrl = $helper->getLoginUrl( FACEBOOK_REDIRECT_URI, $permissions );
echo '<a href="' . $loginUrl . '">
Login With Facebook
</a>';
}
Whenever I try to use the code this is always the output been trying for about an hour by the time this is posted
I tried changing the graph versions and double-checking redirects and I am still stumped on this.
Had to remove almost all of the stuff on the permissions 'pages_show_list' was the only thing left since the data isn't supported on the standard access on the Facebook developer website, have to get a privacy URL to get full access to all the other permissions.
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've got a php page that is pulling events from a facebook fan page. If I open an incognito window (or log out of facebook) and then click the link, a blank page opens. My guess is there's something to do with access tokens, permissions of the FB app and permissions to the page. Any insight would be greatly appreciated.
The ticket_uri tries to open a link like this: http://www.facebook.com/ajax/events/ticket.php?event_id=147884225370550&action_source=12. If logged in, it seems like this is auto-forwarded to the actual ticket link in the event.
Here is page I'm working on: http://danagould.com/live.php. It's pulling from the facebook page officialdanagould
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<?php
date_default_timezone_set('America/Los_Angeles');
//requiring FB PHP SDK
require 'fb-sdk/src/facebook.php';
//initializing keys
$facebook = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'MYAPPSECRET',
'cookie' => true, // enable optional cookie support
));
$fql = "SELECT name, pic, start_time, end_time, location, description, eid, has_profile_pic, venue, ticket_uri
FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 175890419184371 AND start_time > now() )
ORDER BY start_time asc";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
//looping through retrieved data
foreach( $fqlResult as $keys => $values ){
$convertedtime = strtotime($values['start_time']);
$start_date = date( 'F j', $convertedtime );
$content = $values['description'];
//printing the data
echo "<tr>";
echo "<td width='8%'>";
if ( $values['has_profile_pic'] == FALSE) {
echo "<img src=img/spacer.gif width='100%'/>";
} else {
echo "<img src={$values['pic']} width='100%'/>";
}
echo "</td>";
echo "<td width='2%'></td>";
echo "<td width='18%' class='tourdate'>{$start_date}</td>";
echo "<td width='49%'>";
echo "<table><tbody><tr><td class='tourlocation'>{$values['name']}</td></tr>";
echo "<tr><td class='poddesc'><p class='poddesc'>At {$values['location']}</p></td></tr></tbody></table>";
echo "<td width='23%' class='getickets'>";
echo "Get Tickets";
echo "</td></tr>";
echo "<tr height='5px'></tr>";
}
?>
</tbody>
</table>
Try setting the cookies to false or set $fql globally. In addition what are you stating in callback
I want to make further use of the API by obtaining the list of our user's friends and displaying their details in my application.
in old version, I use
$facebook->api_client->friends_get and
$facebook->api_client->users_getInfoBut in facebook 2012,i don't know how to use?
some body help me.
sample:
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('src/facebook.php');
$config = array(
'appId' => '*******',
'secret' => '************',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if(empty($user_id)){
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $GLOBALS['config']['appid'] . "&redirect_uri=" . urlencode($my_url)."&scope=friends_hometown";
echo ("<script> top.location.href='".$dialog_url ."' </script>");
}
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$fql = 'SELECT pic_square,hometown_location,name,sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())';
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
$count=count($ret_obj);
echo '<pre>';
for($i=0;$i<$count;$i++){
echo 'Name: ' . $ret_obj[$i]['name'];
echo '<br />';
echo 'Sex:' . $ret_obj[$i]['sex'];
echo '<br />';
echo 'Home :' . $ret_obj[$i]['hometown_location']['city'];
echo '<br />';
}
// FQL queries return the results in an array, so we have
// to get the user's name from the first element in the array.
echo'</pre>';
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
?>
</body>
</html>
you can use php Sdk
& to get Friends of users
use this code
$friends=$facebook->api('me/friends/,'GET');
& about information it depends on what information you want if you just want name & other very public infos the code above is enough
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!