I use Facebook PHP SDK 3.0.1 (latest currently).
What I need to be able to do is to post as a the identity of the Page on the Page.
I tried replacing the access_token with the access_token I get from the page (/me/accounts) however it now says token is invalid for some reason.
Facebook "impersonation" pages are offline now, and I don't see any info in the API regarding doing what I want.. maybe I'm lost or maybe not looking in the right direction..
Here's the example.php that I modified and use to archive this:
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
));
// Get User ID
$user = $facebook->getUser();
//Lists all the applications and pages
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$accounts_list = $facebook->api('/me/accounts');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$page_selected = 'xxxxxxxxxxxx';
$page_access_token = $accounts_list['data']['0']['access_token'];
echo 'page_access_token:' . $page_access_token;
<?php
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$page_selected/feed", 'post', array(
'access_token' => '$page_access_token',
'message' => 'Development Test message',
'link' => 'http://xxxxxxx.com',
'picture' => 'http://xxxxxx/xxxx_logo.gif',
'name' => 'xxxxxxxx Goes Here',
'description'=> 'And the exciting description here!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
echo($e);
echo $publishStream;
echo 'catch goes here';
}
}
?>
Since I can't answer my own question I edited the question.
Went through the whole API..
Solution:
Before posting as the page you need to set your access_token to the one page owns.
$facebook->setAccessToken($page_access_token);
does just that, and afterwards everything goes as it normally would be expected, no need to modify post function and add "access_token" option to post.
1.First you have to get the page access token.
public function getPageToken()
{
$page_id = "xxxxxxxxxx";
$page_access_token = "";
$result = $this->facebook->api("/me/accounts");
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
}
else
{
$url = "https://www.facebook.com/dialog/oauth?client_id=xxxxxxxxxx&redirect_uri=http://apps.facebook.com/xxxxxx&scope=manage_pages&response_type=token";
echo "<script type='text/javascript'> top.location.href='".$url."'; </script>";
}
return $page_access_token;
}
2.After getting the page access token just include that token in your post to wall code.
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
var token = '<?php echo $page_access_token ?>';
var wallPost = {
access_token: token,
message : 'xxxxxxxx',
link : 'http://apps.facebook.com/xxxxxxx/',
picture : 'xxxxxxxx',
name : 'xxxxx',
caption : 'xxxxxx',
description : 'xxxxxxx',
};
FB.api('/pageid/feed', 'post', wallPost, function(response) {
if (!response || response.error) {
} else {
}
});
</script>
3.Remember this code will only publish your post on Fan page's wall and users who liked the fan page will be able to see that post as the post is posted on their own feed.
Hope this will solve your problem.
Related
Fatal error: Uncaught OAuthException: An unexpected error has occurred. Please retry your request later.
I am trying give an option to Change their facebook cover from my website using facebook api.
Here is my code:
<script>
FB.login(function(response) {
if (response.authResponse) {
if (response)
{
fblogin();
// user is logged in and granted some permissions.
}
else
{
// user is logged in, but did not grant any permissions
alert('Kindly allow the My App to access the Facebook Account');
}
} else {
// user is not logged in
alert('You are not logged in Facebook Account');
}
}, {scope:'read_stream,publish_stream,publish_actions,offline_access,email'});
function fblogin()
{
var imageName = 'myimage.png';
jQuery.post("/facebook/index", {imageName:imageName}, function(data){
if(data)
{
parent.window.open("http://www.facebook.com/profile.php?preview_cover="+data,'_blank');
} else {
alert('Please Login.');
}
});
}
</script>
After login when i posted image name then :
require_once('/api/facebook/src/facebook.php');
$this->objfacebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_SECRET_KEY,
'fileUpload' => true,
'cookie' => true
));
$user_id = $this->objfacebook->getUser();
$access_token = $this->objfacebook->getAccessToken();
if ($user_id) {
$this->objfacebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Cover Photo',
'name'=> 'Created on My App'
);
$create_album = $this->objfacebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
//Uploading Photo
$photo_details = array(
'message'=> 'Cover Photo',
'name'=> 'Created on My App'
);
$file = BASE_PATH."/public/images/".$_POST['imageName']; //BASE_PATH - Actual path of image
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $this->objfacebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
echo $upload_photo['id'];
exit();
}
For my old user it is working fine, they have no issue when they changed their Facebook cover.
But when users come with their new facebook account to change their facebook they get a fetal error everytime.
I also have tried this with my new facebook account, it also gives me same Fetal Error.
I have no idea why is this happening for new users? Am i doing anything wrong here?
please give some idea.
it was happening because user didn't get any authorization popup to allow my app to publish data on their account..
it is fixed now. i have just updated my fb api. it works fine.
I'm currently developing my first facebook application. I have a problem with the setExtendedAccessToken() function in combination with FB.Event.subscribe('auth.login').
My js-code looks like this:
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'XXX', // App ID from the App Dashboard
channelUrl : 'http://domain.tld/app/channel.php', // Channel File for x-domain communication
frictionlessRequests: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('auth.login', function(response) {
$('#loginSpinner').show();
$('#loginFacebook').hide();
window.location = "http://domain.tld/app/?first_login";
});
};
The auth.login event should only trigger on the first login of the user.
This PHP Codes should also only trigger on the first login:
// triggers on first login
if (isset($_GET['first_login'])) {
if ($me) {
$facebook->setExtendedAccessToken();
$friends = $facebook->api('/me/friends');
$friends = $friends['data'];
if (!empty($friends)) {
//sql
}
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_actions', $permissions['data'][0]) ) {
$attachment = array(
'message' => 'XXX',
'name' => 'XXX - App',
'link' => 'http://domain.tld/app/',
'description' => 'XXX',
'picture'=> 'http://domain.tld/app/img.jpg',
'access_token' => $facebook->getAccessToken()
);
$facebook->api('/me/feed', 'POST', $attachment);
//sql
}
}
header('Location: http://domain.tld/app/');
exit;
}
The problem is an infinite loop which will always call the auth.login, because setExtendedAccessToken() will destroy the current session and facebook will login the user to my app automatically.
Is there a way to trigger auth.login only once? When I set setExtendedAccessToken() as a comment
// $facebook->setExtendedAccessToken();
my site only redirects the users once as it should be. But I need the extended login for my app.
My previous question: My WebApp (using facebook login) logs me out
I am having a little trouble authenticating with the below code.
I have a page that produces a loginUrl for the user to login/authenticate my app on Facebook:
<?php
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream, read_friendlists, user_birthday', 'redirect_uri' => 'complete.php'));
?>
<div id="connect_facebook">
<a class="button" href="<?php echo $loginUrl; ?>">Connect to Facebook</a>
</div>
And my complete.php has a script that does the following:
<script>
$(document).ready(function() {
pop_db();
});
function pop_db() {
$.post(
"pop_db.php",
function(data) {
alert(data);
}
);
}
</script>
And my pop_db.php file looks like:
<?php
require_once('constants.php');
$response = array();
$user = $facebook->getUser();
if($user) {
try {
// make API calls
$response['code'] = "success";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$response['code'] = "failure";
$response['userID'] = $facebook->getUser();
$response['access_token'] = $facebook->getAccessToken();
}
echo json_encode($response);
?>
And constants.php has my secret info for the Facebook object (and it also creates the $facebook object).
My issue is that when I do this using "complete.php" as the redirect and try to do the API calls async using this jQuery, I get back a response that userID = 0 (meaning the user isn't logged in) but it seems like I get a valid access token. When I use "pop_db.php" as my redirect instead of "complete.php" and therefore don't use any async calls, everything works fine.
Am I missing something? Why does it keep telling me the user isn't logged in?
Any suggestions are much appreciated.
Who are getting problem to login their own website thorough facebook / integrate facebook login to their website just follow the given link "http://developers.facebook.com/docs/howtos/login/server-side-login/#step2".It is a very nice link which can solve your problem definitely.
Thanks.
banalata.
"
using this reference I am trying to simply post ot a users feed.
can anyone tell me why this does not work?
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '<MY ID>',
'secret' => '<MY SECRET>'
));
// Get User ID
$user = $facebook->getUser();
$token = $facebook->getAccessToken();
if ($user) {
try {
$post_id = $facebook->api('/me/feed', 'POST', array('message'=>'Hello World!'));
if($post_id)
echo '1';// nothing echo's
else
echo '0';
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
fixed with JS scope
function fb_oAuth(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream'});//< - FIX
}
what's the response you are seeing? Facebook should return some thing? or you are not even hitting the facebook server?
I created a facebook application and send request to a user through below code.Now when a user allow my application then i need his id and email address into my canvas url.But on that below code user don't go to my canvas URL.So,Please help me to solve ,how a user go to my canvas url when he allow my application and i get the user id of that user?My code is below:
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '#######',
'secret' => '###################',
'cookie' => true, ));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0,'req_perms'=>$req_perms));
$me = null;
if (!$session)
{ echo "top.location.href= '$loginUrl';";exit;}
else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
}
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href= '$loginUrl';</script>"; exit;}
}
So,please help me to get the user id.
Thanks in advance
riad
The Facebook ID & email for the current user can be accessed through:
$me['id'];
$me['email'];
Is that what you're after?
First of all, your code is "badly" written. The catch block in your code "when executed" does not mean that the user is not logged in. It means that something went wrong in your try block (a.k.a bad Facebook Call).
Now for your question, you just need to place this in your try block:
$data = $facebook->api('/me?fields=id,email');
IMPORTANT NOTE:
You may not get the user real email, the user may choose to not share it with you and this way Facebook will create a "mirror" email to share with your App.
I am not familiar with php to comment on the code above. However in general it would be better to use javascript sdk for login alone (faced the same issue in asp.net). That way post user login, the control comes back to the same page where it was initiated. For example:
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: <app_id>, cookie: true, status: true, xfbml: true
});
function fblogin() {
FB.login(function (response) {
//Control comes back here
if (response.session) {
alert(response.session.access_token);
var url = '/me?fields=name,email';
FB.api(url, function (response) {
//You are now in the same page with the data you wanted. If necessary redirect.
alert(response.name);
alert(response.email);
});
}
else {
alert("User did not login successfully");
}
}, { perms: 'email' });
}
</script>
<img src="../Images/social_facebook.png" />
At last i solve my problem and now i can easily get the facebook user id and email address and other related information.Using this code i can hit to facebook for particular user's authentication and when user accept my application then i can get his/her facebook user id, email and other information into $user_info array.Hope it will help you.
Just see my code below:
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '########',
'secret' => '##########################',
'cookie' => true,
));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=> 1,'fbconnect' => 0,'req_perms' => $req_perms));
$user_info = null;
if (!$session)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";exit;}
else{
try { $user_info = $facebook->api('/me'); }
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; exit;}
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<?php
$user_name=$user_info['name'];
echo "Hi $user_name ! Your Facebook ID is: ".$user_info['id']."<br/>";
echo "Hi $user_name ! Your E-mail Address is: ".$user_info['email']."<br/>";
echo "Thanks for accepting our application.";
//print_r($user_info);
?>
</body>
</html>