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?
Related
im getting "OAuthException: An active access token must be used to query information about the current user" once every two page loads (with any authenticated user), the correct load gets the user info with out any problems.
This is my current script:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'cookie' => true,
));
//obtiene las Variables Iniciales
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => ('http://xxxxx.com/Salir') ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email,user_birthday,user_hometown,user_location'));
}
This is the button:
<fb:login-button perms='email,user_birthday,user_hometown,user_location' length='long' autologoutlink='false' onlogin='fbLogin();'></fb:login-button>
<div id='fb-root'></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '$FBid',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
return false;
});
FB.Event.subscribe('auth.logout', function(response) {
return false;
});
};
(function() {var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/es_ES/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Does anyone have any idea about why this is happening?
Thanks for the help :D
I apologize for my bad English.
Where do I go from here? This is almost just copy paste from the example provided in the sdk. I don't understand how people can build anything with this API?? How do I open the prompt screen for login etc? Where the heck does Facebook say something about that?
<?php
require 'fb_sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APIID',
'secret' => 'SECRET',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
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;
}
}
// Permissions requested from the user.
$par = array();
$par['scope'] = 'user_about_me, read_friendlists';
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>
You can find information on using the Graph for user authentication here on Facebook Developers.
With $loginUrl = $facebook->getLoginUrl($par); the variable $loginUrl will contain a url to the authentication dialog. Most developers either present this to the user as a link or perform a redirect with javascript - eg:
die('<script>top.location.href = "' . $loginUrl . '"</script>');
The other alternative is to use the JavaScript SDK with XFBML to authenticate (if you have cookies enable with both SDKs they will share session data) - example from here:
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// See if there is a user from a cookie
$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) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user_profile) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
You can also login purely with JavaScript using FB.Login:
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 + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'user_about_me, read_friendlists'});
It is mentioned in the comment :
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
SDK will take care of that, you need not worry about it.
The user details are there in $user_profile
do a echo"<pre>"; print_r($user_profile); echo"</pre>"; and you will get it.
I am using codeigniter on my site and I use facebook login to login but I have a problem.
->getUser does not return any data when I try my normal codeigniter project. But, in the new folder which is not related my project I try to login from example.php which comes from facebook sdk it works well.
I have checked everything (autoloads, config, etc.)
I think my problem is about sessions.
Thanks for your help.
I suggest that you use the new version of PHP SDK for the Facebook API. I had the same problem with version 3.0.1, that is why I use the previews version 2.1.2 which works just fine.
Unfortunately I don't have time to play with the new version (3.0.1) but there is a very simple example with version 2.1.2:
Config
/* application/config/autoload.php */
$autoload['libraries'] = array('template', 'session', 'facebook');
Library
/* application/libraries/Facebook.php */
require_once("Facebook/2.1.2/facebook.php");
class CI_Facebook extends Facebook {}
Template
/* application/views/template.php */
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
cookie : true,
xfbml : true
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
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.
I am successfully using the Facebook SDK (PHP) to connect users to my site, but I'm having issues when they authenticate their account. Their account is successfully authenticated, but for some reason my site's sessions are cleared.
Flow:
User logs into my site (local username and password)
User connects to Facebook in a popup
Facebook authenticates user and returns back to my site
My sites session is now invalid (both in the popup and main window) causing the user to be logged out
I am using the Facebook SDK (PHP) and my site uses the CakePHP framework
Any help will be greatly appreciated.
I can't tell you what is deleting your session, but you might want to try this (works for me)
use the Javascript SDK to display the login buttons that will open the popup to connect to FB
add the js SDK to your page like this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo FB_API_ID; ?>', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function() {
new Request({
'method': 'get',
'url': '<?php echo $this->Html->url(array('controller'=>'users','action'=>'login_fb'));?>',
'onSuccess': function(result){
window.location.reload();
}
}).send();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
On the auth.login event i'm using an ajax call to /users/login_fb that will use the Facebook SDK to check the facebook session:
App::import('Lib', 'facebook_sdk/facebook');
// "MyAuth" is a custom Auth Component that extends the normal Auth component
$this->MyAuth->facebook = new Facebook(array(
'appId' => FB_API_ID,
'secret' => FB_SECRET,
'cookie' => true,
));
$me = null;
$session = $this->MyAuth->facebook->getSession();
if ($session) {
try {
$uid = $this->MyAuth->facebook->getUser();
$me = $this->MyAuth->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if ($me) {
$this->Session->write('FbLogin.session',$session);
$this->Session->write('FbLogin.user',$me);
$UserModel = ClassRegistry::init('User');
$user = $UserModel->findByUid($me['id']);
if(!$user){
$UserModel->create();
$user_data = array( 'username'=>$me['username'],
'name'=>$me['first_name'],
'lastname'=>$me['last_name'],
'email'=>$me['email'],
'group_id'=>GROUP_VISITOR,
'uid'=>$me['id']
);
$UserModel->save($user_data);
$user['User']['id'] = $UserModel->id;
}
$this->Session->write($this->MyAuth->sessionKey, $user['User']);
$this->MyAuth->_loggedIn = true;
}
}
the main idea is that.. in js i call an ajax to check the fb session and then save it in the cake session , and the js will refresh the page
Could be worth checking the Cake security level, it might be doing referrer checks (I think it does this in the "high" setting, maybe the "medium" as well), which would be invalidating the session.
I couldn't find out why the session was being reset so decided not to use the SDK for the authentication. This is what I used instead.
$code = (isset ($_REQUEST['code']) ? $_REQUEST['code'] : null);
if (empty ($code)) {
$dialogUrl = 'http://www.facebook.com/dialog/oauth?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&scope=' . implode(',', $this->scope);
header('Location: ' . $dialogUrl);
die;
}
else {
$tokenUrl = 'https://graph.facebook.com/oauth/access_token?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&client_secret=' . $this->secret . '&code=' . $code;
$accessToken = file_get_contents($tokenUrl);
$this->Session->write('facebookAccessToken', $accessToken);
$graphUrl = 'https://graph.facebook.com/me?' . $accessToken;
$fbUser = json_decode(file_get_contents($graphUrl));
if ($fbUser) {
...
}
}