I am using the following 2 API's to create a facebook connect but having issues with the sessions being picked up the the PHP SDK. I have downloaded the latest facebook-connect-js & facebook-php-sdk
Here is my initial FB.init connect using the JS no problem ie.
<script>
// initialize the library with the API key
FB.init({
apiKey: '9999999999999999999999999999',
session : <?php echo json_encode($session); ?>,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
I can test if its working by reloading the page an using the following script I can see the response session.
FB.getLoginStatus(function(response) {
if (response.session) {
console.log(response.session)
} else {
// no user session available, someone you dont know
}
});
But the PHP SDK is not picking up the session.
ie
$facebook = new Facebook(array(
'appId' => '9999999999999999',
'secret' => '9999999999999999999999999999999',
'cookie' => true,
));
$session = $facebook->getSession();
The javascript is creating a cookie but its not being found by the session.
Any suggestions to what I am doing wrong.
Hope you can help.
For whatever reason the problem has resolved itself.
May have been a server issue
Related
I'm trying without success for 2 days now to retrieve page feed with Facebook PHP SDK. Details :
I got a user, who is page admin
I created an app (not public, is that a problem?)
I use an AJAX called PHP script to try to retrieve feed, because I don't want to pollute main page loading.
All stuff given on PHP SDK doc is related to manual login and access token retrieval.
I Managed to retrieve a user token using the 2-scripts code (login, and callback), with manage_pages speical grant require :
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://domain.com/fb_callback.php', $permissions);
How can achieve the same thing without manual redirection, is one script, in AJAX context? SHould I use Curl to emulate manual redirection?
THing which puzzle me out is that the same stuff tok 2 lines using JS framework :
window.fbAsyncInit = function() {
// Framework init with Vinexpo app ID
FB.init({
appId : '012345789',
xfbml : true,
version : 'v2.4'
});
// Check status
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// If connected, get last 2 posts on Facebook page
FB.api(
"/page_ID/posts?limit=2",
{
access_token : response.authResponse.accessToken
},
function (responsePost) {
if (responsePost && !responsePost.error) {
// Fill tiles on social network panel
}
}
);
}
});
Thanks in advance for answers or leads.
If you just want to read the newsfeed of one of you pages via AJAX, you don't necessarily need the PHP SDK if you generate yourself an eternal page access token and use this for your plain HTTP requests.
Have a look at my answer here on how to get such a token:
Post to a facebook page without "manage_pages" permission using php
FacebookI am using facebook javascript sdk to loigin a user, and then I wish to get some of his info via the php sdk, but I keep getting "An active access token must be used to query information about the current user."
this is the relevant html/js code:
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '8', // App ID from the app dashboard
channelUrl : '//url/frontend/channel.php', // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true,
oauth:true,
xfbml : true // Look for social plugins on the page
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
submitform();
} });
};
function submitform() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me?fields=email,name', function(response) {
//submits a form from this page...
});
}
</script>
Facebook
and the php that fails is :
$facebook = new Facebook(array(
'appId' => Configuration::$facebook_app_id,
'secret' => Configuration::$facebook_app_secret));
// Get User ID
$user_profile = $facebook->api('/me?fields=name,id','GET');
It seemed to work for a while, and then it breaks with
" [message] => An active access token must be used to query information about the current user.
[type] => OAuthException
[code] => 2500",
Anyone has an idea how to stabilize this?
Thanks
Maybe that happens because your acces token was expired?
There are several access token types. And if your access token is a "short-term token" - you must refresh it.
you can read abot acces tokens here https://developers.facebook.com/docs/facebook-login/access-tokens/
In python server lib for facebook i used method fetchToken(appId, secret) to refresh my expired token.
Probably a dumb thing to ask, but this will really help me get my head around FB integration.
I am using standard FB.init to use javascript SDK, and using PHP SDK to do some basic API calls:
FB.init({
appId : '265236093556723', // App ID
status : true, // check login status
// cookie : true, // enable cookies to allow the server to access the session. WHY IS THERE AN INFINITE LOOP WHEN THIS IS REMOVED?!?!?!?!?!
xfbml : true, // parse XFBML
oauth : true,
channelUrl : 'http://www.loveweber.co.uk/dev/fbchannel.php' // Channel File
});
I was testing stuff and commented out the cookie: true line. This caused the site to loop through realoding the page and im not sure why. I read everywhere that PHP uses this cookie set by Javascript... so is it something to do with the PHP call to the API?
Or maybe something to do with:
FB.Event.subscribe('auth.login', function(response) {
window.location.reload(); // When user logs in, the page refreshes...
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
the realoding of the page when a user logs in or out?
Thanks would help such a lot.
FB.Event.subscribe('auth.login', function(response) {
window.location.reload(); // When user logs in, the page refreshes...
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
I notice that your not checking the response variable in either event subscription. You should ensure that the response is what you think it is before you blindly do the reload(); The reason Facebook sends you the response object is because it is not always what you think.
The response object will be like:
{
status: "xxx", /* Current status of the session */
authResponse: { /* Information about the current session */
userID: "" /* String representing the current user's ID */
signedRequest: "", /* String with the current signedRequest */
expiresIn: "", /* UNIX time when the session expires */
accessToken: "", /* Access token of the user */
}
}
So be sure the response.status is 'connected' when you subscribe to auth.login. and then not 'connected' when you subscribe to the auth.logout.
I have a facebook canvas application and I am using the latest version of the PHP SDK.
I have a workflow that looks like this. User logs into facebook and clicks on the application from their list of apps.
User lands on a form page -> clicks submit -> user doesn't see that it goes through the form process page and try's to post to wall -> header redirect to invitation page.
The flow works because I have built in transparent error handling. However, there is no wall post during this first walk through of the flow. Repeat by clicking on facebook icon to go to user home page, click on the application link in the list of user apps.
User lands on a form page -> clicks submit -> user doesn't see that it goes through the form process page and try's to post to wall -> header redirect to invitation page.
This time and every time there after it works.
The error I receive during the first try is that the session access_token is invalid. Every single time afterwards, as long as the user does not logout it will work and I will never get a bad token.
ON THE FORM PROCESS PAGE WHERE THE WALL POST CODE IS:
$user = null;
require "/usr/home/app/www/fb/facebook.php";
//facebook application
$fbconfig['appid' ] = "xxx";
$fbconfig['secret'] = "xxx";
$fbconfig['baseUrl'] = "http://www.app.com/fb";
$fbconfig['appBaseUrl'] = "http://apps.facebook.com/app";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
));
//session_write_close();
$user = $facebook->getUser();
try {
$publishStream = $facebook->api("/me/feed", 'post', array(
'message' => "mess",
'link' => 'http://apps.facebook.com/app',
'picture' => 'http://images.app.com/img.jpg',
'name' => 'name',
'description'=> 'des'
)
);
} catch (FacebookApiException $e) {
d($e);
}
header("Location: https://www.app.com/fb/invite.php");
This is the exact error truncated to leave out information that is erroneous:
FacebookApiException Object
(
[result:protected] => Array
(
[error] => Array
(
[message] => An active access token must be used to query information about the current user.
[type] => OAuthException
)
)
....
Maybe you can try the offline_access permission to get a non-terminating access token?
So, after pounding my head against the wall for a week... I figured it out!
I had added a script at the end of the first page to make the scroll reset.
<script>
FB.init({
appId : 'appid',
status : true,
cookie : true,
xfbml : true,
});
</script>
On the next page was the processing, that was not working correct until I reached the next page where the invitation screen was to appear. On that page was the FB.init,
function callAppReq() {
FB.init({
appId : 'appid',
cookie: true,
channelUrl : 'https://apps.facebook.com/app',
oauth : true
});
After this page was loaded, every time thereafter the app worked correctly. I was scratching my head and couldn't figure it out. Until I noticed, "oauth : true" was the ONLY thing going on that was NOT being called on the first page. So, in that dumb script that I needed to make the scroll bar go away I added ":oauth : true"...
<script>
FB.init({
appId : 'appid',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
</script>
Lo' and behold, it works now. I am very upset that it was this code breaking things but VERY happy that I now have it fixed and understand what the issue was!!!
i want to authenticate my facebook profile with my website so i can pull infor from the page.
i was suggested to one time authenticate with the facebook api through a temp page. somewhat like:
<fb:login-button params="some permission" />
i am new to coding facebook apps. but this seems like fbml. how can i use it to authenticate my website with my own profile. i dont need users to log into my website. i just need to pull info from my page.
the facebook documentation is sparse and fragmented. all i got for the Login was this code fragment. I dont understand how i can authenticate a weblink through this method.
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
can anyone throw some light??
Let's start from the beggining:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en">
It's required for fbml to work. Next:
<fb:login-button autologoutlink="true"></fb:login-button>
<div id="fb-root"></div>
These two lines create the "facebook login button", you should place them in your html where you want the button to appear.
Right before your closing body tag add:
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID HERE', status: true, cookie: true, xfbml: true});
FB.Event.subscribe("auth.login", function(response) {
if(response.session) {
// this is where you handle facebook's response
}
});
};
</script>
What you are doing here is first initializing the connection to facebook, with your app id (you need to create an application), and register an "auth.login" event. The auth.login event is triggered every time you click the facebook login button and successfully login to facebook, or facebook auto logins you based on their cookie.
You can find an explanation of the auth.login and other events here, look at the sidebar at the left, all events are listed.
The response is JSON formatted and it contains your basic session information:
{
status: 'connected',
session: {
access_token: '...',
expires:'...',
secret:'...',
session_key:'...',
sig:'...',
uid:'...'
}
}
You can read more about it here. If your status is indeed "connected" the next most important bit of information is the uid, this is your unique facebook identifier, a public id with which you can send further requests to facebook. What you do with the response is up to you. An obvious choice would be to send it via ajax to a script that logs you in your application.
To get more info from facebook you need to download the php sdk. To use the sdk:
<?php
include_once "facebook-sdk-3.0.0/src/facebook.php";
$appID = "YOUR APP ID";
$appSecret = "YOUR APP SECRET";
$cookie = "fbs_{$appID}";
$cookie = isset($_COOKIE[$cookie]) ? trim($_COOKIE[$cookie], '"') : "";
if(empty($cookie)) {
echo "no facebook cookie";
die();
}
parse_str($cookie, $data);
$facebook = new Facebook(array(
"appId" => $appID,
"secret" => $appSecret,
"cookie" => true
));
$facebook->setAccessToken($data["access_token"]);
$user = $facebook->getUser();
$profile = $facebook->api("/me");
?>
So at first you parse facebook's cookie which is named "fbs_YOUR_APP_ID" and contains your session information (url encoded). What you actually need is the access_token (a unique identifier of the authenticated session), which was also returned to you in the JSON response object before. Then via the Facebook object you can do and api requests you want.
Now to have a full authentication mechanism you should create a similar connect script that instead of getting the session information from the cookie it should take them from the response object that is returned when auth.login occurs (possibly via ajax).
You should read the Authentication workflow document to better understand how facebook connect works.
A good and easy way to deal with Facebook authentication is to implement the server side flow with the Facebook PHP SDK (see on github). So you will have something like :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
If the user is logged in, then $user is his Facebook ID. You then have to check if you have a valid access token by making an API call :
If it does not raise any exception, then you have a valid access token
If it does, then you have to re-authenticate the user.
Here :
if ($user) {
try {
$facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
You need then to display the login or logout link :
<?php if ($user): ?>
Logout of Facebook
<?php else: ?>
Login with Facebook
<?php endif ?>
When the user is logged in and you have a valid access token, you can make API calls to get data from Facebook :
$user_profile = $facebook->api('/me');
You may want to check the example page of the Facebook PHP SDK which is well documented.
Hope that helps.