I would like fans of our Facebook page to be able to publish images to a specific Album. Although, the app was able to upload an image to a users timeline, the app isn't able to publish it to an album in the fanpage (facebook page of the company). What's wrong, or how can I change the code so I can track the bug.
In an earlier attempt, I was able with a similar script and never-expire token to publish the image onto the wall of the fanpage, but then the app posted it, and I want to see the users name.
<?php
require 'facebook.php';
$app_id = "xxx";
$app_secret = "xxx";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$canvas_page = "http://apps.facebook.com/xxx/";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)."&scope=publish_stream";
$signed_request = $_REQUEST["signed_request"];
if(isset($_FILES["source"]["name"]))
{
try {
$facebook->setFileUploadSupport(true);
$response = $facebook->api(
'/ALBUMID/photos/',
'post',
array(
'message' => $_POST['message'],
'source' => '#'.$_FILES["source"]["tmp_name"],
'access_token' => 'xxx'
)
);
}
catch (FacebookApiException $e) {
error_log('Could not post image to Facebook.');
}
}
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"]);
};
$signed_request = $facebook->getSignedRequest();
$user = $facebook->getUser();
$page_id = $signed_request["page"]["id"];
$page_admin = $signed_request["page"]["admin"];
$like_status = $signed_request["page"]["liked"];
$country = $signed_request["user"]["country"];
$locale = $signed_request["user"]["locale"];
echo "<br>user id = $user";
echo "<br>page id = $page_id";
echo "<br>page admin = $page_admin";
echo "<br>like status = $like_status";
echo "<br>country = $country";
echo "<br>locale = $locale";
if ($like_status) {
?>
<div id="like">
You like us.
<form enctype="multipart/form-data" action=" " method="POST">
Please choose a photo:
<input name="source" type="file"><br/><br/>
Say something about this photo:
<input name="message"
type="text" value=""><br/><br/>
<input type="submit" value="Upload" class="btn btn-primary"/><br/>
</form>
<?php
if(isset($response))
{
echo "Image Uploaded. <a href='http://facebook.com/{$response['id']}' target='_blank'>Click here to view</a>";
}
?>
</div>
<?php
}
else {
?>
<div id="niet_leuk">
You don't like us.
</div>
<?php
}
?>
This is a known bug with facebook opengraph. You can see the details of it here: https://developers.facebook.com/bugs/246002638848837/
It is marked as low priority, so I wouldn't expect a fix anytime soon.
So right now, you can only post images to a non-user page as the page admin or as the page itself.
Related
Years ago I've developed apps for Facebook, but now seems not working old method to get user's information (id, name, etc) and post data on user's wall.
I've used like this, but for now It returns me blank screen:
require_once('FacebookAPI/Facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
));
$user = $facebook->getUser();
if ($user)
{
try
{
#Code below to post data on user's wall
# Photo Caption
$photoCaption = 'Just used app';
$imageUrl = ('http://example.com'); // Example URL
$link = ('http://www.facebook.com/page/app_xxxx?ref=ts');
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'link' => $link,
'caption' => 'Caption text'
);
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
?>
#Code below to show app
<html>
<body bgcolor="#ffffff">
<center>
// link to my app
</center>
</body>
</html>
// Code below to get user's information (name, id)
<?php
$user_profile = $facebook->api('/me');
$coded = $_REQUEST['code'];
$name = $user_profile['name'];
$id = $user_profile['id'];
session_start();
$_SESSION['name'] = $name;
$_SESSION['id'] = $id;
}
catch (FacebookApiException $e)
{
$user = null;
error_log($e);
}
}
else
{ # Code below to get access from user
$redirectUri = 'http://www.facebook.com/mypage/app_xxxx?ref=ts';
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload',
'redirect_uri' => $redirectUri
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
Could someone help me out to get successfully user's name, id?
You can try this code. Hope you have downloaded latest php-sdk, you have appid,app des
include_once "php-sdk/src/facebook.php";
$app_id = 'your app id';
$facebook = new Facebook(array(
'appId' => 'your app id',
'secret' => 'your app secret'
));
$user = $facebook->getUser();
if ($user) {
$me = $facebook->api('/me');
$name= $me['name'];
$fid=$me['id'];
}
else
{
$loginUrl = "http://www.facebook.com/dialog/oauth?client_id=" .
$app_id . "&redirect_uri=" . urlencode($app_url) . "&scope=email";
echo("<script> top.location.href='" . $loginUrl . "'</script>");
}
I have the following code which works fine as long as in a previous part of the application, the user accepts the applications request to publish_stream.
# The facebook library
require_once("/var/www/facebook-php-sdk-master/src/facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId_here';
$config['secret'] = 'secret_here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
#check permissions
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $user_id,
'ext_perm' => 'publish_stream'
);
#set to true if true...
$can_offline = $facebook -> api( $api_call );
#is it true?
if( $can_offline ) {
$post = array(
'message' => 'post_a_message'
);
$facebook->api('/' . $_GET["id"] . '/feed', 'POST', $post);
} else {
// can't post message - don't have permission
}
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
} else {
error_log("user not logged in");
exit;
}
To try to resolve this, I attempted to insert the following code into the else statement which currently in the code above only contains the comment // can't post message - don't have permission
The code I tried to insert into that else was this:
$loginUrl = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
header("Location: ".$loginUrl);
That works as long as the user accepts to allow my app to publish_stream. However, if the user does not accept, my app will keep asking the user to accept publish_stream. How do I stop that loop from happening if the user decides not to accept?
As far as i remember, $facebook -> getLoginUrl can take parameter cancel_url, which contains the link, where user should be redirected if he doesn't give your app permissions.
So the code will be something like this
$login_url = $facebook -> getLoginUrl( array(
'scope' => 'publish_stream',
'cancel_url' => YOUR_LINK_HERE
));
Here is the working code : Please check it :
Page name : events.php
You can see $redirect_uri = https://localhost/facebook_page/events.php it is returning back to same page.
<?php
$facebook_appid = "your appid"; // Facebook appplication id
$facebook_secret = "your app secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "publish_stream"; // User permission for facebook
$profile_id = "profile_id";// Where do you want to post it(profile id - It is a number)
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = rand(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
?>
<!-- Here you can use
message, picture, link, name, caption, description, source, place, tags
as input fields-->
<form enctype="multipart/form-data" method="POST" action="https://graph.facebook.com/<?php echo $profile_id;?>/feed?access_token=<?php echo $access_token; ?>">
<input type="text" name="message" value="test" />
<input type="submit" name="submit" value="Submit" />
</form>
You can post it using jquery also.
I use the following code to check if the user has allowed publishing permisions or not:
$permissions = $facebook->api('me/permissions');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
//Continue with posting on users wall
} else {
//Continue without posting on users wall
}
I am trying to upload an image and post to my fan page wall as a page using this tutorial
however the connection doesnt seem to work.
any suggestions how to get the page parameters so that i can post images to the pages wall please
this code has been modified from the latest SDK 3.1.1
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '***************',
'secret' => '********************************',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = '***************';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => 'http://myDoamin.com/logout_page.php' ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body { font-family: 'Lucida Grande', Verdana, Arial, sans-serif; }
h1 a { text-decoration: none; color: #3b5998; }
h1 a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>php-sdk</h1>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if ($user): ?>
<h3>You</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($page_info); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
</body>
</html>
uploading handeled here:
<?php
$app_id = "***************";
$app_secret = "********************************";
$post_login_url = "http://mydomain.com/upload.php";
$code = $_REQUEST["code"];
//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 = $params['access_token'];
// Show photo upload form to user and post to the Graph URL
$graph_url= "https://graph.facebook.com/me/photos?"
. "access_token=" .$access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url .' "method="POST">';
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>';
}
?>
the example from the SDK is similar and when i run this it works as user. but not as page
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
refer to: https://developers.facebook.com/docs/authentication/pages/
Grant manage_pages permissions to your application.
Get page_access_token, make api post to page as page with page token.
EXAMPLE: php cURL upload: stand alone example, no sdk needed.
<?php
function GetCH(){
// id of the album to upload
$ablum_id = "182325958494028";
// photo caption
$photo_caption = "testing app ablum upload";
// the page access token if you are uploading as the page
$page_access_token = "Add Your page token here.";
// url to your photo
$photo_url = "http://sphotos.xx.fbcdn.net/hphotos-ash3/544288_10150906170859577_732484576_9506566_417314835_n.jpg";
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/".$ablum_id."/photos?url=".urlencode($photo_url)."&message=".urlencode($photo_caption)."&method=post&access_token=".$page_access_token."");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$sendCH = curl_exec($ch);
curl_close($ch);
return $sendCH;
};
// call our function and upload photo, large photos may be slow
echo GetCH();
// if successful a return is shown
// { "id": "387851721274783", "post_id": "171535666239724_387851741274781" }
?>
This is how I post as a Page. I'm using Facebook's PHP SDK.
I am first fetching a list of all the pages the user has access to, then I present a list of them to the user so they can choose one (code not shown here). I then store that data and use it later to post as that page.
How I get the list of pages:
try {
$result = $facebook->api("/me/accounts");
$userpages = $result['data'];
} catch (FacebookApiException $e) {
$userpages = array();
$fbuser = null;
$facebook->clearPersistentData();
}
Now I iterate through them ($settings is an array with my user's settings, including the page they chose to post as):
foreach ($userpages as $userpage) {
if ($userpage['category'] == "Application")
continue; # My app doesn't work with Application pages.
if ($settings['page']['id'] == $userpage['id']) {
# This is the page I want.
# $userpage['access_token'] has the access token.
}
}
The access_token gets added into my array of postdata for the request, and the id is used here.
return $facebook->api("/$id/feed/", "post", $postdata);
I just need simple and working facebook app. I bought ssl for this and i dont want too much expenses.
If user allowed app it will write his name and gender and his/her friends gender.
my app doesnt redirect after user allow the app. I cant fix it so just need basic app with out url redirecting.
ı used this code but it doesnt work. it need to be corrected:
require_once("facebook.php");
$facebook = new Facebook(array(
'appId' => '***',
'secret' => '***',
'scope' => 'manage_pages,offline_access,publish_stream,user_photos'
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
Here is the simple one page application full fills your needs
make the file with name index.php
download the facebook library download here
<?php
require_once 'library/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secret',
'cookie' => true,
));
$app_id = 'appid';
$canvas_page = "canvas_page_link";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=email,read_stream&response_type=token");
$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 {
//getting the userid and some other data for verification
//get the user id
$UserId = $data["user_id"];
echo 'UserId;' . $UserId;
//get the user access token
$token = $facebook->getAccessToken();
echo "</br>" . 'Access_Token:' . $token;
//set default access token and profile
$facebook->setAccessToken($token);
$user_profile = $facebook->api('/me');
//get the user name
$user_id = $facebook->getUser();
$user_profile = $facebook->api('/me','GET');
$user_name = $user_profile['name'];
echo "Name: " . $user_name;
$user_gender = $user_profile['gender'];
echo "Gender: " . $user_gender;
}
?>
I am developing a facebook app using PHP.
I am able to login using the below code
<?php
$app_id = "XXXXXXXXXXXXXXXXX";
$canvas_page = "http://apps.facebook.com/sandysfirst/";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" .urlencode($canvas_page)."&scope="."publish_stream,read_stream,offline_access";
$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 {
}?>
<?php
include_once "src/facebook.php";
$app_id = 'XXXXXXXXXXXXXXXXXXX';
$application_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$facebook = new Facebook(array(
'appId' => $app_id,
'fileUpload' =>true,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
if ($facebook->getSession()) {
$user = $facebook->getUser();
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
echo "<br/><br/><br/><br/> Welcome ".$fbme['name'];
}
echo "<html>
and the HTML follows below that with a form action.
I want to know how I can get the same user id or session on the second page once the form is submitted.
I am not using facebook.php of sdk 3.0.
I don't know the facebook api, but from some basic php there's a few methods you could use:
1 - Add the uid as a hidden field in the form.
<input type="hidden" name="uid" value="$uid">
2 - Add it to the action url
<form action="submit.php?uid=$uid">
However the better way is to use the facebook api, pretty much the same way you've got it listed there already (from the include_once "src/facebook.php";), to retrieve the uid each time, otherwise you leave it open to security hacks (easy to pass a fake uid in a form).