APP authentication on facebook with PHP SDK - php

I have a problem with authenticating my Facebook APP with a Link generated through the Facebook PHP SKD:
when I click the link, an error appears on facebook (An error occurred. Please try again later.) and I won't get redirected to the "app login page".
https://www.facebook.com/dialog/oauth?redirect_uri=http%3A%2F%2Fxxx.test.net%2Fstart.php&state=8d0ea10xxxxxxx290be6c654f02xxxa&scope=user_likes
This is the code of the index.php:
<?php
require_once("./fbsdk/facebook.php");
//test.net
$config = array();
$config[‘appId’] = '37353621936xxxx';
$config[‘secret’] = 'fd39e0f0861f2bdae4fc79274749xxxx';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
?>
<!DOCTYPE html>
<html>
<head>
<title>
FB-DEV-TEST
</title>
</head>
<body>
<?php
$params = array(
'scope' => 'user_likes',
'redirect_uri' => 'http://xxx.test.net/start.php'
);
$loginUrl = $facebook->getLoginUrl($params);
echo "Login";
?>
</body>
</html>
I've already read this post, but I still can't figure out the problem... are there any changes I have to do at the Facebook APP center, before I can login? Thanx for your help & sry, for my bad english! :)

Check if your redirect_url domain matches the "Site URL:" in App settings on developers.facebook.com.

A few checklists that I can think of:
Make sure your Facebook app is not in sandbox mode (unless you are already signed in to your Facebook account before clicking on the login link)
At https://developers.facebook.com/apps/:
"Website with Facebook Login" must be checked, but for "Site URL", you can enter any landing URL.
Also at https://developers.facebook.com/apps/:
Make sure that your site domain is entered under App Domains.
Alternatively, you may want to check out Opauth, an authentication framework for PHP that handles these for you.

Related

Can i run my facebook apps from local host

Problem: Can i run my facebook apps from local host.
Description: I want to get facebook wall posts on my website page. For testing, i created a facebook app and put site url as "http:localhost:8088/fb/" nd app domain as "localhost". Now i want to get user id so that i can access facebook wall posts.But all am getting is user id equals to zero.I have checked it so many times. but everything seems to be correct. So i want to know that can we use local host as site url?? Can i get user id by running my code from local host. Below is my code.
<?php
include_once "facebook.php";
$facebook = new Facebook(array(
'appId' => '<app id>',
'secret' => '<app secret>',
'cookie' => true,
));
$uid = $facebook->getUser();
echo $uid;
$me = null;
if ($uid) {
try {
$me = $facebook->api('/me');
$feed = $facebook->api('/me/feed/');
} catch (FacebookApiException $e) {
error_log($e);
}
}
$params = array(
'scope' => 'read_stream',
'redirect_uri' => 'http://localhost:8088/fb/feeds.php'
);
if ($uid) {
$logoutUrl = $facebook->getLogoutUrl();
}
else {
$loginUrl = $facebook->getLoginUrl($params);
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
</head>
<body>
<?php if($uid)
{
?>
Logout
<?php
}
else
{
?>
Login
<?php
}
?>
<?php if ($me): ?>
<?php
echo "<pre>";
print_r($feed);
echo "</pre>";
?>
<?php endif ?>
</body>
</html>
Please tell me what is the problem here. Is there any settings tht i need to perform. I will be very thankful.
Yes you can run your app from localhost environment. You have done everything correct except that you don't need to add localhost in the app domain and your site url should be
http:// localhost:8088 /fb/
instead of "http:localhost:8088/fb/"
A better way to test out the Facebook api on localhost is to first create a virtual host for your web application like yourapp.local and then set the URLs in your Facebook app information accordingly. You can create separate Facebook apps for local and remote sites.
You can for the most part.
Facebook apps which are just iframes don't need to connect to your host - only you/your browsers does.
Two things to watch out for:
Make sure you have SSL (https://) on your localhost. If not, disable SSL in your test Facebook account settings.
One situation where Facebook will need to access your host include sharing URLs or images that are hosted in your app. Use external placeholders when testing your local app.
I'm sure you can't do that if you have facebook aggregations ( Objects+actions) in your app. Because they need to be accessed directly by facebook

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.

Facebook canvas app "redirect_uri" breaks out of iframe after authorization & authentication

I'm upgrading my existing FB apps, and going absolutely bonkers trying to get a simple PHP iframe canvas app to authorize and authenticate (as well as use SSL). Never looked through so many examples...
Here's where I'm stuck: After the user authorizes the app, and the app authenticates the user (I am able to make a graph request with the token OK), the redirect_uri happens, and the whole page refreshes, leaving Facebook and thenjust shows me the contents of my "Canvas URL" page (with my server's domain), rather than iframed on Facebook.
I currently have this as a crude two step process...
Here's what my code looks like on the first page (index.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
$code = $_REQUEST['code'];
if(!$code){
$display= 'page';
$scope= 'manage_pages, offline_access, read_insights, publish_stream, user_about_me, user_likes, email';
$redirect_url = 'https://myserver.com/apptest/step2.php';
$oauth_url = 'https://www.facebook.com/dialog/oauth?canvas=1&client_id='.$app_id.'&display='.$display.'&redirect_uri='.urlencode($redirect_url).'&scope='.$scope;
$config = array('appId' => $app_id,'secret' => $app_secret,'cookie' => true,'domain' => true);
$facebook_client = new Facebook($config);
echo "<script type=\"text/javascript\">top.location.href = \"".$oauth_url."\";</script>";
}
?>
and the second page (step2.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
if($_REQUEST['code']){
$code=$_REQUEST['code'];
$redirect_url = 'https://myserver.com/apptest/step2.php';
$link="https://graph.facebook.com/oauth/access_token?canvas=1&client_id=".$app_id."&redirect_uri=".urlencode($redirect_url)."&client_secret=".$app_secret."&code=".$code;
$string = file_get_contents($link);
$auth_token=substr($string, 13, 150);
$graph_url = "https://graph.facebook.com/me?access_token=".$auth_token;
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
Again, once the user has authorized the app, and the app has authenticated the user, the graph call works.
Any ideas?
When navigating to the OAuth dialog the web page (not the frame your app is in) is navigated to the OAuth URL. To get back into the Facebook iframe after authentication you need to set the OAuth redirect URL to the canvas_page URL. The code shown above is navigating to the URL of myserver when redirected so your app takes up the entire page (because you left the Facebook iframe when navigating to the OAuth dialog). Your code at canvas_url needs to determine if it is being entered from authorization (success or failure) or if it is being entered with a valid access token after authentication.
Also your canvas_page URL appears to be comprised of the facebook apps host and your application ID. It should be the facebook apps host and your application name (the redirect URL should be the same as the "Canvas Page" URL on your app's developer page).
Well I did get this working. On the app > settings > basic I hadn't set a namespace, so the URL it gave me for the app on facebook was like this: https://apps.facebook.com/123456789/ and now with the namespace they changed it to: https://apps.facebook.com/myappname. So that may have been it. I tried to carefully follow the simple PHP autorization demo on this page: https://developers.facebook.com/docs/appsonfacebook/tutorial/ and it seems to work ok now.
Thanks for the help!

one time authentication for weblink with facebook app

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.

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

Categories