I wanted to include the facebook login inside my application. This is the sample code which I was provided with:
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'my api goes here',
'secret' => 'my api secret goes here',
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$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();
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!--
We use the JS SDK to provide a richer user experience. For more info,
look here: http://github.com/facebook/connect-js
-->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// 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>
<h1>php-sdk</h1>
<?php if ($me): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<div>
Without using JavaScript & XFBML:
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
</div>
<?php endif ?>
<h3>Session</h3>
<?php if ($me): ?>
<pre><?php print_r($session); ?></pre>
<h3>You</h3>
<img src="https://graph.facebook.com/<?php echo $uid; ?>/picture">
<?php echo $me['name']; ?>
<?php echo $me['education'][0]['school']['name']; ?>
<h3>Your User Object</h3>
<pre><?php print_r($me); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
<h3>Naitik</h3>
<img src="https://graph.facebook.com/naitik/picture">
<?php echo $naitik['name']; ?>
</body>
</html>
Now - this works well but when I'm trying to include that in my code igniter view file it's not allowing me to login due to an error. In the code where it says 'my api goes here' and 'my api secret goes here' I'm obviously inserting my app data. Does any of you encountered similar issue? When I click login I'm getting this error: An error occurred with MY APP. Please try again later.
Can anyone help me with this one?
Have you tried any of these two CodeIgniter libraries for Facebook?
http://www.haughin.com/code/facebook/
http://brandonbeasley.com/blog/facebook-api-codeigniter/
UPDATE: Sadly these links are no longer valid.
My partner just made a library and indepth tut to help with this:
http://hitsend.ca/2010/10/facebook-connect-user-authentication-using-the-new-graph-api-in-codeigniter/
Let us know what you think. We needed it for our uses, and figured it was a common problem.
It uses the new graph api, not the old one. That solves A LOT of problems.
Let us know what you think.
Related
I have created an api to import photos from facebook and google+. But I am facing a problem in displaying the list of photos. Can you please resolve this?
My Code Below:
File Name: index.php (Google)
<?php
include_once "google-plus-access.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Google+ API To Fetch Photos</title>
<link rel='stylesheet' href='style.css' />
</head>
<body>
<div id="bar">
<div class="top-area" >
<div class="login" >
<?php if(isset($me) && isset($activities)) { ?>
<a href="?logout" ><h5>Logout</h5></a>
<?php } else { ?>
<a href="<?php echo($authUrl); ?>" ><h5>Login</h5></a>
<?php } ?>
</div>
</div>
</div>
<?php if(isset($me) && isset($activities)) {?>
<div class="big-container" >
<div class="profile" >
<div class="profile-pic" ><a href="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>" ><img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" /></a>
</div>
<div class="profile-info" >
<div class="name" ><a href="<?php echo($me['url']) ; ?>" ><?php if(isset($me['displayName'])) echo(strtoupper($me['displayName'])); else echo "Not set or private"; ?></a></div>
<div class="details" >
<ul>
<li><b>GENDER : </b><?php if(isset($me['gender'])) echo($me['gender']); else echo "Not set or private"; ?></li>
<li><b>ORGANISATION : </b><?php if(isset($me['organizations']['0']['name'])) echo($me['organizations']['0']['name']); else echo "Not set or private"; ?></li>
<li><b>PLACE : </b><?php if(isset($me['placesLived']['0']['value'])) echo($me['placesLived']['0']['value']); else echo "Not set or private"; ?></li>
</ul>
</div>
</div>
</div>
</div>
<?php foreach($activities['items'] as $activity): ?>
<div class="activity" >
<div class="title" ><a href="<?php echo($activity['object']['url']) ; ?>" ><?php echo($activity['object']['content']); ?></a></div>
<p>Published at <?php echo($activity['published']); ?></p>
<p>
<?php echo($activity['object']['replies']['totalItems']); ?> Replies .
<?php echo($activity['object']['plusoners']['totalItems']); ?> Plusoners .
<?php echo($activity['object']['resharers']['totalItems']); ?> Reshares
</p>
</div>
<?php endforeach ?>
<br><br>
<div class="photos">
<?php
if(isset($me['url']))
{
$photos = "https://plus.google.com/photos/";//.$me['id']."/albums";
echo $photos;
}
?>
</div>
<?php } else {?>
<div class="login-box">
<div id="connect-button"><a href="<?php echo($authUrl); ?>" ><img src="connect-button.png" alt="Connect to your Google+ Account"/></a>
<div>This API is purely read-only. It will <b>NOT</b> post anything to your profile.
</div>
</div>
</div>
<?php } ?>
</body>
</html>
File Name: google-plus-access.php
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("picpixa");
//*********** Replace with Your API Credentials **************
$client->setClientId('***********************');
$client->setClientSecret('************************');
$client->setRedirectUri('http://localhost/MyApi/Google-Plus/');
$client->setDeveloperKey('*********************************');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/photos'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
File Name: index.php (Facebook)
<?php
include_once "fbmain.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Fetch Image From Facebook</title>
<script type="text/javascript">
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui({method: 'feed',
message: userPrompt,
link: hrefLink,
caption: hrefTitle,
picture: 'http://thinkdiff.net/ithinkdiff.png'
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
function publishStream() {
streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
}
function newInvite() {
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Come on checkout Personalized Products. visit http://www.picpixa.com',
},
function(receiverUserIds) {
console.log("IDS : " + receiverUserIds.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
</script>
</head>
<body>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<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: '<?= $fbconfig['appid'] ?>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
</script>
<?php if (!$user) { ?>
You have to login using Facebook Login Button to see api calling result.
<img src="Images/login.png">
<?php } else { ?>
<img src="Images/logout.png">
<?php } ?>
<!-- all time check if user session is valid or not -->
<?php if ($user) { ?>
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>
<!-- Data retrived from user profile are shown here -->
<div class="box">
<b>User Photos using Graph API</b>
<?php d($user_photos); ?>
</div>
</td>
</tr>
</table>
<?php }?>
</body>
</html>
File Name: fbmain.php
<?php
$fbconfig['appid'] = "Your App Id";
$fbconfig['secret'] = "Your App Secret";
$fbconfig['baseurl'] = "localhost/MyApi/Facebook/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
try {
include_once "facebook.php";
} catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => false,
));
//Facebook Authentication part
$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.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_photos',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//Retriving photos of user using graph api
try {
$user_photos = $facebook->api("/$user/photos");
} catch (Exception $o) {
d($o);
}
}
function d($d) {
echo 'This function is called <br><br><pre>';
print_r($d);
echo '</pre>';
}
?>
I am not sure what you expected on the Google+ side. All you are doing for photos, apparently, is printing the URL based on the Google ID. (Assuming the portion that was commented out.)
There is no way using the Google+ API to get the user's photos. You need to look into using the Picasa Web Albums Data API, but this is using Google's older GData protocol. There are a couple of resources that may help, for example, there is a PHP library which uses an older version of the protocol and a more modern example code snippet which may guide you in doing this.
You should star https://code.google.com/p/google-plus-platform/issues/detail?id=670 to indicate you want a more modern API for photos in Google+.
I'm trying to get user birthday with facebook API. I do know we need now to ask permission for this. I don't really know how it works
Just found this to add:
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email,read_stream')
);
}
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
and this is my whole code ( quite basic ):
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '4539768XXXXX',
'secret' => 'fe86f3b0b34b3eXXXXXXXXXX',
'cookie' => true,
));
$signedRequest = $facebook->getSignedRequest();
$liked = $signedRequest["page"]["liked"];
// Get User ID
$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) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email,read_stream')
);
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<?php
if ($liked) {
header("Location:youlike.php");
} else {
echo "you don't like yet";
}
?>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login:
Login with Facebook
</div>
<?php endif ?>
<?php if ($user): ?>
<h3>Vous</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Personne connectée</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>Vous n'etes pas loggé!</em></strong>
<?php endif ?>
</body>
<script>
</script>
</html>
i would appreciate your help
thanks in advance!
You have a couple of problems in your code.
First, you aren't asking for the user_birthday permission when you create your $loginUrl. You should be requesting the same permissions for req_perms on line 33 as you do in the <fb:login-button> on line 68 of your code: email,user_birthday,status_update,publish_stream.
Once you copy over the permissions, you can remove line 68 of your code. The <fb:login-button> tag won't work without the JavaScript SDK.
Calling header() on line 61 after you've output text to the browser on lines 37-58 won't work. If you are going to redirect the browser, you can only do this before you've output text. Move this block of code before you output anything and it will work.
The white space between your ?> on line 36 and <!doctype> on line 39 will be output at the top of your HTML file. It cause the Facebook parser to choke. Some browsers don't like white space at the beginning of an HTML document either and will render your page incorrectly. Your code should really be ?><!doctype
I needed to request permission to a facebook user to get specific informations (email,birthday).
When a user launches the application for the first time, if he accepts the permission, he is forced to refresh the page to display data (just informations concerning the user,see my code).
The problem is it works fine sometime,that's why i don't know if it is a facebook problem or a problem in my own code.
If you can have a look at my code, some help would be much appreciated!
thanks in advance
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '453976824647366',
'secret' => 'fe86f3b0b34b3ed6XXXXXX',
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<fb:login-button autologoutlink="true" perms="email,user_birthday" size="large" onlogin="window.location = 'youlike.php';">Connect to this application using Facebook</fb:login-button>
<?php if ($user): ?>
<h3>Vous</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<pre><?php print_r($user_profile); ?></pre>
Date de Naissance : <?php echo $user_profile["birthday"];
echo '<ul>';
foreach ($friends["data"] as $value) {
echo '<li>';
echo '<div class="pic">';
echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
echo '</div>';
echo '<div class="picName">'.$value["name"].'</div>';
echo '</li>';
}
echo '</ul>';?>
<?php endif ?>
</body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
</div>
<script>
FB.init({appId: '453976824647366', status: true,
cookie: true, xfbml: true});
</script>
</div>
</html>
You can always force a refresh on login/logout, just to be sure:
after your FB.init
FB.Event.subscribe('auth.login', function(){
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(){
window.location.reload();
});
I have been trying to get this to work for a few days on and off and seem to get no where with it. what ever I try I get
You are not Connected. Public profile of Naitik
I am using a shared ssl does this have any to do with this?
I am guessing its an OAuth 2.0 that is giving me problems?
if I go to https://www.facebook.com/dialog/oauth?client_id=IDNUMBER&redirect_uri=https://apps.facebook.com/... I can see all my info
but if I just click the app from facebook's homepage it will say I am not logged in?
any ideas?
Thank you!
<?php
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '...',
'secret' => '...',
));
// Get User ID
$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) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>php-sdk</h1>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if ($user): ?>
<h3>You</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
<h3>Public profile of Naitik</h3>
<img src="https://graph.facebook.com/naitik/picture">
<?php echo $naitik['name']; ?>
</body>
</html>
Try adding a few more permissions like read_friendlist so that the API throws an exception on the statement $fb->api('/me') when the user is logged out as you want it to. For eg. set
$params = array('scope' => 'read_friendlists, friends_photos');
//$facebook->getLoginUrl($params);
//$facebook->getLogoutUrl($params);
// now use these login logout urls
You can also try adding $params = array('next'=> 'your-landing-page') to your facebook login request as $fb->loginUrl($params).
I'd like new users to be able to 'connect' with the use of the fb connect button on my site and once connected it will display their first+last name and profile picture.
If the user is already connected, the connect button turns into a logout.
Going by the docs, i've implemented the following code;
<html>
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:'xxxxxxxxxx', cookie:true,
status:true, xfbml:true
});
FB.api('/me', function(user) {
if(user != null) {
var image = document.getElementById('image');
image.src = 'http://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
}
});
</script>
<div align="center">
<img id="image"/>
<div id="name"></div>
</div>
</body>
</html>
The only problem is that it does not display the facebook connect button and when I try and insert it, the code breaks.
Any help would be much appreciated!
recap: website checks if the user has connected and has a valid session, if not, display fb connect/login button, if yes, display the logout button, either way it should show the user their name and profile photo.
Thank you!
The Facebook PHP-SDK will do exactly what you want:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
// Session based API call.
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
// login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>test full name and photo</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>', // 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
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// 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>
<?php if ($user): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<?php endif ?>
<?php if ($user): ?>
<div align="center">
<img id="image" src="https://graph.facebook.com/<?php echo $uid; ?>/picture" />
<div id="name"><?php echo $me['name']; ?></div>
</div>
<?php endif ?>
</body>
</html>