one time authentication for weblink with facebook app - php

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.

Related

How get access token from other users

I need to read the posts on facebook. I had create the application and the program works if I log with my credential. But when I log with another credential ( like another profile that I have just created) the program doesn't work anymore. This is my login page:
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if(!empty($_SESSION)) {
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
$access_token=$facebook->getAccessToken();
$facebook->setAccessToken($access_token);
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}
} else {
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
header("Location: ".$login_url);
}
when I login I obtain the access token and I call graph api:
https://graph.facebook.com/******/posts?access_token=**
This is operation work if I m who is logged in the application. If another login in the app this is not work.
Maybe it's a authentication problem. Maybe I forget some operation that I must do to authentica with another account. Anyone can help me?
You need to submit your App to Facebook then Facebook will check and pass you app then you can access you app other account. If you want to check App Functionality you can use Facebook App test user Id. Below I have Explained how to get test user
Goto App Page.
Click on Roles.
Click on to Right Corner Test users.
It will show your test user details.
Use this details and access you App.
You have to make your app public for all users from here: https://developers.facebook.com
have a look on it:
Use /me/feed instead of /me in your API call
see example below
Permissions
Your app needs user_posts permission from the person who created the post or the person tagged in the post. Then your app can read:
Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.
please read this thread https://stackoverflow.com/questions/30719556/read-post-from-facebook-home/30732874#30732874
READING
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */

Login with Facebook without database

I'm trying to create a website that allows users to login with their Facebook account. I do not need to make any requests or store any info when they are not on the website and so I do not need a database.
I am only going to accept login with Facebook and no other login types are required. I will need the typical login with Facebook button on the login page and the ability to keep them logged in across multiple pages. I would also like to add an ability to log out.
I've downloaded the PHP SDK and I am using the JavaScript SDK together on my pages, but I am having so much trouble.
Is it just me or does the Facebook SDK completely suck?
My first problem is that the JavaScript SDK on the login page doesn't redirect the user to the main page after authentication. I am manually refreshing the page currently (the PHP SDK realizes that the user is logged in and sends the user to the main page).
Another issue is logout. I am using the PHP SDK's getLogoutURL() function, and it logs the user out of Facebook, but my access token is still fully valid and PHP refuses to send the user to the login page. Why? I have no idea. Personally, I'd like that the user be logged out of my website and not Facebook.
I'm trying to make a seamless login system with Facebook, but I'm having nothing but trouble! I can't seem to find any good documentation on Facebook Connect at all. I'm using their examples and problems like this are happening. Maybe they just can't make a good SDK. I'd like to use the PHP SDK and the JavaScript SDK to make a very nice user experience, but it just doesn't seem possible.
login.php's PHP code
require_once("../fb-sdk/src/facebook.php");
$Facebook = new Facebook(array(
'appId' => 'xx',
'secret' => 'xx',
));
$User = $Facebook->getUser();
if ($User)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$UserProfile = $Facebook->api("/me");
} catch (FacebookApiException $e) {
error_log($e);
$User = null;
}
}
if ($User)
{
header("Location: index.php");
}
?>
login.php's JavaScript code
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xx', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<div class="fb-login-button">Login with Facebook</div>
index.php's PHP code
require_once("../fb-sdk/src/facebook.php");
$Facebook = new Facebook(array(
"appId" => "xx",
"secret" => "xx",
));
$User = $Facebook->getUser();
if ($User)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$UserProfile = $Facebook->api("/me");
} catch (FacebookApiException $e) {
error_log($e);
$User = null;
}
}
if (!$User)
{
header("Location: login.php");
}
?>
You have to subscribe for login event to get callback and then you can refresh your page. Also for logout you should used your own SESSION of site for login logout beside facebook login, so lets say if you get userid from facebook by calling this function (means user is login with facebook)
$User = $Facebook->getUser();
Then set something like this in your session, and use this variable to check login status of user with your web.
$_SESSION['LOGIN'] = 1;
and when you logout you can simply unset this variable or destroy session.
Here are the links of tutorial which gives you more detail on facebook SDK in PHP / JS
http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/

Facebook PHP SDK: how to display login dialog automatically?

My code cannot display the permission dialog when a user connect to my Facebook application. Instead of the login page, I got a 404 error.
My code:
require 'src/facebook.php';
require './config.php';
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_secret,
'cookie' => true,
));
$userData = null;
$user = $facebook->getUser();
if ($user) {
try {
$userData = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_stream',
));
}
<div id="loginWrapper">
<?php if ($user): ?>
Logout
<?php else: ?>
Login with Facebook
<?php endif ?>
</div>
I have also tried to put directly an personalized URL (like bellow) and I got the same 404 error.
$loginUrl = "http://www.facebook.com/dialog/oauth?client_id=".$fb_app_id."&redirect_uri=".$fb_app_url."&scope=publish_stream";
UPDATE 1:
Otherwise when I try to Login directly through the server (from http://mydomain/application/index.php), I got a redirection to Facebook website to the URL below and got this error message:
https://www.facebook.com/dialog/oauth?client_id=xxxxxxxxxxxxxx&redirect_uri=http://apps.facebook.com/myapplication&state=f8cd945d8a9aefcd0b439fecd8515a68&canvas=1&fbconnect=0&scope=publish_stream
UPDATE 2:
Here my application configuration:
And the message I got when I try to access directly from the app link: apps.facebook.com/myapplication/ without be logged
I would appreciate any help.
The status_update permission you are using in the scope for the loginUrl is not a valid permission. Take a look at the docs.
That could be your problem.
Also remember, that if a user has already authorized your app, they will not see the permission dialog again on subsequent logins. They will only be taken through the facebook login procedure.
EDIT:
Take a look at the image I've attached, facebook will on redirect to the url you specify in the site url field in app settings:
Regarding the update of your post: Go to the Developer App and select the App you're getting this error for. Click edit settings and enter the domain your App is hosted on/you're redirecting to into the "App Domain" field. Now just save and it should work.
Edit (solution from comment above): If it just doesn't work when you're not logged in, may it be that your App runs in Sandbox Mode? You can check if it's enabled in the "Advanced Settings" of your App.

Which facebook API's?

Is it possible for me to post a message on a given users facebook wall, if they perform a certain action on my website?
Basically, I am looking for a step by step guide to achieve this, as I have not been able to figure out how to do this via the facebook documentation.
Step 1:
Set up a new application at facebook. Enter details like your website address and domain name. Note down the api key, application id, and application secret. You can set up a new facebook application here. Note: To be able to access facebook developers dashboard you need to be a verified developer, i.e. you should either have your mobile number or credit card verified with it.
Step 2:
Set up an authentication method to check if user is logged into facebook and if facebook session exists ask for basic permissions from user. You can do this easily using PHP SDK:
$fb_sdk_path = FACEBOOK_SDK_PATH;
require_once($fb_sdk_path);
//initialize FB object
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true,
'domain' => 'example.com'
));
//try to get session. if this fails then it means user is not logged into facebook
$session = $facebook->getSession();
if (!$session) {
//get facebook login url
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0
)
);
//put login url script to redirect to facebook login page (if you want to do this)
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
exit;
} else {
//try to get user details from session this will trigger the permissions dialog.
try {
$uid = $facebook->getUser();
} catch (FacebookApiException $e) {
}
}
Step 3:
Use Facebook Javascript FB.ui method to generate a post form.
<div id="fb-root"></div> <!-- don't forget to include this -->
<script src="http://connect.facebook.net/en_US/all.js"></script><!-- include fb js -->
<script type="text/javascript">
//initialize facebook
FB.init({
appId:'YOUR_APP_ID',
cookie:true,
status:true,
xfbml:true
});
//call this function on click or some other event
function post_to_profile() {
FB.ui({
method: 'feed',
name: 'title of the feed',
link: 'link on the title',
caption: 'caption to show below link, probably your domain name',
description: 'description',
picture:'picture to show',
message: 'default message. this can be edited by the user before posting'
});
}
</script>
This should be enough to get it working.
I would recommend using the Javascript API. While you can certainly do it PHP, I find all the redirects required a poor user experience. Here is how you can get started loading the javascript API. It also has an example on how to post to a wall.
http://developers.facebook.com/docs/reference/javascript/
Posting to someones wall (yours or a friends) via javascript uses the FB.ui call.
http://developers.facebook.com/docs/reference/javascript/FB.ui/
Taken directly from http://developers.facebook.com/docs/guides/web/
<html>
<head>
<title>My Great Website</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'YOUR_APP_ID', cookie:true,
status:true, xfbml:true
});
FB.ui({ method: 'feed',
message: 'Facebook for Websites is super-cool'});
</script>
</body>
</html>
This will open a prompt to post onto the currently logged in user's wall.
The getting started guide to the Graph API should help you. Specifically, you'll be dealing with the post object (that page contains a note about publishing, scroll down to the "Publishing" section). You'll also need the publish_stream permission, which you can learn more about here. And since you're doing this in PHP, the official Facebook PHP SDK will be of interest to you as well.
Here's the general flow
Register an app at developers.facebook.com
Create page w/ this link to this page: https://www.facebook.com/dialog/oauth?
client_id=164837516907837&
type=user_agent&
scope=email,read_stream,user_videos,friends_videos,user_about_me,offline_access&
redirect_uri=http://www.facebook.com/connect/login_success.html
Save the user x's oath token that is returned from step2
Via API call post to user x's wall
To reference: http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development/
Various steps involved
1)Register App at facebook
developers
2)Get PHP SDK of Facebook
3)Get Offline access from user
so that you can post in users wall
without his permission(Use
accordingly)
4)Save the access token given by
facebook for the user
5)Using the access token by php
SDK post into the wall
Check this question it may be of some help
Publishing To User's Wall Without Being Online/Logged-in - Facebook Sharing Using Graph API

Can I store Facebook access token and use it later?

I am building a web app (PHP) that uses FB connect. I successfully register / sign in user with the help of the PHP lib provided by facebook. Also I can post to wall, using this code
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
$facebook = new Facebook(array(
'appId' => $fb_key,
'secret' => $fb_secret,
'cookie' => true, // enable optional cookie support
));
$session = $facebook->getSession();
if ($session)
{
$facebook->api('/me/feed', 'POST', array('message'=>$message, 'link'=>$link['href'], 'name'=>$link['text']));
}
However, if I manually go to my browser's cookie manager and delete the cookie that stores FB session, the code doesn't work. The only thing I have is user's FB ID which I store in DB. Is there any way to post to user's wall even if FB sessions is lost? Does it make sense to store user's FB access token in DB to post to wall later or is the access token relatively short-lived?
Here's an example situation that might happen in my app:
user clicks fb button, authorizes my app, gets redirected back to my site where I automatically create an account based on data provided by FB, also I store user's FB ID so that I could sign in this user later. Now he browses site, enters some info and this info gets posted to his wall. Everything is fine so far because user's browser holds the cookie created by FB. Now user leaves the site and contacts site admin. Admin opens his own browser, goes to admin interface and posts something on behalf of this user. Now, having that user's FB ID and assuming that user hasn't revoked permissions, can I still post this to his wall?
With the Facebook PHP SDK v3 (see on github), it is pretty simple to ask and use a user offline access token. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
Then, when the user is logged in, you can retrieve the offline access token and store it. To get it, call :
if ($user) {
$token = $facebook->getAccessToken();
// store token
}
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
Hope that helps !
UPDATE: This answer is no longer valid as offline_access is deprecated.
You need to request the offline_access permission. Check the permissions doc.
EDIT Per the update and comments - some info on the removal of the offline_access can be found here.

Categories