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);
Related
Hi I'm facing a problem which I couldn't find solution on net. I'm trying to log into my website using facebook login. This is my code. getAccessToken() method always returns null. Please Help me to resolve this error. Thank you. Below is my code.
this is my fbConfig.php file
<?php
if(!session_id()){
session_start();
}
//Include the autoloader provided in the SDK
require_once 'C:\xampp\htdocs\FBFunApp\php-graph-sdk-5.x\src\Facebook\autoload.php';
//Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
/*
* Configuration and setup Facebook SDK
*/
$appId = '560615054394144'; //Facebook App ID
$appSecret = 'AAAAAAAAAAAAAAAAAAAA'; //Facebook App Secret
$redirectURL = 'http://localhost:8080/FBFunApp/views/login.php'; //Callback URL
$fbPermissions = array('email'); //Optional permissions
$fb = new Facebook(array('app_id' => $appId,'app_secret' => $appSecret,'default_graph_version' => 'v2.10',));
// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();
// Try to get access token
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$accessToken = $helper->getAccessToken();
var_dump($accessToken); //returns null
}
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}catch(Exception $e){
echo 'Exception: '+$e->getMessage();
exit;
}
?>
This is login.php file. Config file is used inside this.
<?php
//Include FB config file & User class
require_once '../config/fbConfig.php';
require_once '../controllers/User.php';
if(isset($accessToken)){
if(isset($_SESSION['facebook_access_token'])){
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}else{
//Put short-lived access token in session
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler helps to manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// Set default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// Redirect the user back to the same page if url has "code" parameter in query string
if(isset($_GET['code'])){
header('Location: ./');
}
// Getting user facebook profile info
try {
$profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,cover,picture');
$fbUserProfile = $profileRequest->getGraphNode()->asArray();
print_r($fbUserProfile);
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// Redirect user back to app login page
header("Location: ./");
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// Initialize User class
$user = new User();
// Insert or update user data to the database
$fbUserData = array(
'oauth_provider'=> 'facebook',
'oauth_uid' => $fbUserProfile['id'],
'first_name' => $fbUserProfile['first_name'],
'last_name' => $fbUserProfile['last_name'],
'email' => $fbUserProfile['email'],
'gender' => $fbUserProfile['gender'],
'locale' => $fbUserProfile['locale'],
'cover' => $fbUserProfile['cover']['source'],
'picture' => $fbUserProfile['picture']['url'],
'link' => $fbUserProfile['link']
);
$userData = $user->checkUser($fbUserData);
// Put user data into session
$_SESSION['userData'] = $userData;
// Get logout url
$logoutURL = $helper->getLogoutUrl($accessToken, $redirectURL.'views/logout.php');
// Render facebook profile data
if(!empty($userData)){
$output = '<h2 style="color:#999999;">Facebook Profile Details</h2>';
$output .= '<div style="position: relative;">';
$output .= '<img src="'.$userData['cover'].'" />';
$output .= '<img style="position: absolute; top: 90%; left: 25%;" src="'.$userData['picture'].'"/>';
$output .= '</div>';
$output .= '<br/>Facebook ID : '.$userData['oauth_uid'];
$output .= '<br/>Name : '.$userData['first_name'].' '.$userData['last_name'];
$output .= '<br/>Email : '.$userData['email'];
$output .= '<br/>Gender : '.$userData['gender'];
$output .= '<br/>Locale : '.$userData['locale'];
$output .= '<br/>Logged in with : Facebook';
$output .= '<br/>Profile Link : Click to visit Facebook page';
$output .= '<br/>Logout from Facebook';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
}else{
// Get login url
$loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
// Render facebook login button
$output = '<img src="../images/app/fb-login.png">';
}
?>
<html>
<head>
<title>Login with Facebook</title>
</head>
<body>
<!-- Display login button / Facebook profile information -->
<div><?php echo $output; ?></div>
</body>
</html>
After the updation of facebook api :
Every request Url must be Https
So,
Change this :-
$redirectURL = 'http://localhost:8080/FBFunApp/views/login.php'; //Callback URL
To :
$redirectURL = 'https://localhost:8080/FBFunApp/views/login.php'; //Callback URL
You can do this using Changing your webserver setting Or using it's defaylt port :- 443 for ssl.
Happy Coding :)
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.
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'm trying to write an app that will post images the user makes to a user's wall in facebook, it was working until about an hour ago now i'm getting a catch error of "An active access token must be used to query information about the current user.". hopefully someone has a quick answer :)
here is my starting PHP that gets the user and checks for the album
<?php
include 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => ID,
'secret' => SECRET,
'cookie' => true
));
$me = null;
$thisPhoto = null;
$album_name = NAME;
$album_message = MESSAGE;
try {
$me = $facebook->api('/me');
$facebook->setFileUploadSupport(true);
// check if album with name exists...if not create it
$albums = $facebook->api('/me/albums');
foreach($albums['data'] as $album) {
if($album['name'] == $album_name) {
$album_uid = $album['id'];
}
}
if (!$album_uid) {
$album_details = array(
'message'=> $album_message,
'name'=> $album_name
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'] . "MADE";
}
//echo "<!-- $album_uid -->\n";
}
catch (FacebookApiException $e) {
echo "<!-- " . $e->getMessage() . " -->\n";
}
?>
This is my main HTML (the above is called before the doctype)
<!doctype>
<html>
<head>
<meta charset=utf-8>
<title>'TITLE</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css" media="screen">
html, body { width:100%; background-color: #FFF;}
body { margin:0 auto; padding:0; width:760px}
#flashContent { width:100%; height:100%; }
</style>
</head>
<body>
<?php
//print_r($me);
//echo $facebook->getUser();
//echo $facebook->getAccessToken();
// START
if($me) {
// true makes print_r give human readable instead of just a screen dump
//echo '<pre>' . print_r($VARIABLE, true) . '</pre>';
$appName = NAME.SWF;
$appWidth = "760";
$appHeight = "640";
$appID = "stache_yerself";
$appAlt = "Square Shooters app - 'Stache Yerself";
// ECHOS out HTML used for the APP
}
else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream,read_friendlists,user_photos'));
echo 'Login';
}
?>
</body>
</html>
The else above gives a link which is there; however, does nothing it just goes to an empty page. I reset the "secret" on the app's developer page but didn't help. I have no idea why it just stopped working (did facebook change their code again?). Even the login thing from the HTML section was working before and now...nothing. I'm stumped as to why this just stopped working.
Did you hit your API limit for your dev account?
You can do 600 queries in 600 seconds.
Also, this might be helpful
https://www.facebook.com/help/210701362295828/
I have a Facebook PHP SDK APP in development phase and i'm stuck on something...
The logic of the APP is this:
first the user have to like the page (app is on this) // works very well :)
after that comes the permissions request
if permission is granted: the app_data variable is pass through and the user recieves a picture.
app_data variable is necessary because, if the user clicks the app after permission granted again, it gets new picture automaticly. with the app_data don't.
my problem is this link:
$params = array(
scope => 'publish_stream,user_photos',
redirect_uri => 'http://www.facebook.com/XXXXX?sk=app_YYYYYY&app_data=1'
);
Accept
If i click on it, the app shows blank page, and nothing happening... :(
On direct call, that app runs without any error.
Can someone help me out?
// sorry for my english...
Thank you!
and the whole index.php is:
this is the whole index.php:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'yyyyy',
'baseUrl' => 'http://hosting.address/',
'appBaseUrl' => 'http://apps.facebook.com/app-name/',
'fileUpload' => 'true',
));
// Get User ID
$user = $facebook->getUser();
$params = array(
scope => 'publish_stream,user_photos',
redirect_uri => 'http://www.facebook.com/xxxxx?sk=app_yyyyy&app_data=1'
);
$signed_request = $facebook->getSignedRequest();
$app_data = $signed_request["app_data"];
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>the title</title>
<style>
a:link {color:#ffffff;}
a:visited {color:#ffffff;}
a:hover {color:#ececec;}
a:active {color:#1f1f1f;}
a:link {text-decoration: none}
</style>
</head>
<body>
<?php if ($user){
try {
$user_profile = $facebook->api('/me');
$likes = $facebook->api("/me/likes/123123123"); //page ID
if( !empty($likes['data']) ){
$scope = 'publish_stream,user_photos';
$scope_params = explode(',',$scope);
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('user_photos', $permissions['data'][0]) && isset($app_data)) {
$file = "1.jpg";
$message = 'bla bla';
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '#' . $file,
'message' => $message,
)
);
echo "<img width=\"520px\" src=\"1.jpg\" />";
} else {
?>
accept</td>
deny</td>
<?
}
}else{
echo "<img width=\"520px\" src=\"no-fan.jpg\" />";
}
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
if ($user) {
} else {
$loginUrl = $facebook->getLoginUrl($params);
echo '<script type="text/javascript">top.location.href = "'.$loginUrl .'";</script>';
}
?>
</body>
</html>
I've had this before when I was delving into the world of Facebook apps.
What I eventually done was for my redirect_uri I used a page on my domain, e.g. https://domain.com/facebook/redirect.php and in redirect.php I would have:
// user didn't give app permissions
if (isset($_GET['error_reason']))
{
header( 'Location: http://www.facebook.com/FANPAGE' ) ;
}
else
{
header( 'Location: http://www.facebook.com/XXXXX?sk=app_YYYYYY' ) ;
}