On my facebook app, I'm logging a user in using the Javascript SDK.
If OK, I redirect him to this PHP page (designed to illustrate my problem):
test.php:
<?php
include('config.php');
require('phpsdk.php');
$access_token = $facebook->getAccessToken();
echo $access_token;
echo "<br /><br />";
$user = $facebook->getUser();
echo $user;
?>
(phpsdk.php handels the PHP SDK initiation)
Accessing test.php the FIRST time, returns a valid access token and the ID of the logged user.
However, when I refresh the page, the access token becomes of the type appID|appSecret.
The user is still logged in: getUser still returns the correct user ID.
Anyone knows what's causing this?
Clearing the Facebook Session with php sdk in redirect when user logs out.
Logout.php redirect user and use sdk to clear session data.
example redirect url. yourdomain.com/Logout.php?destroy=true
refer to: https://developers.facebook.com/docs/reference/php/facebook-destroySession/
<?php
session_start();
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'appID',
'secret' => 'appSecret',
'cookie' => true, // enable optional cookie support
));
if(isset($_GET['destroy'])){
$facebook->destroySession();
}
?>
It is not recommended to call getAccessToken(); over and over the way you described.
You should try first to see if the token is in the browser as a session and if not then try to use the SDK to find or request it.
Check browser for a user, if no user call sdk for user, if still null or 0 auth or reauth.
If user, check browser for access_token, if no token call sdk for token.
<?php
session_start();
include('config.php');
require('phpsdk.php');
// need to replace Your_App_ID and YourAppId with your applications id.
$facebook = new Facebook(array(
'appId' => 'Your_App_ID',
'secret' => 'Your_App_Secret',
'cookie' => true, // enable optional cookie support
));
if(isset($_SESSION['fb_YourAppId_user_id'])){
$user = $_SESSION['fb_YourAppId_user_id'];
}else{
$user = $facebook->getUser();
}
if($user){
if(isset($_SESSION['fb_YourAppId_access_token'])){
$access_token = $_SESSION['fb_YourAppId_access_token'];
}else{
$access_token = $facebook->getAccessToken();
}
}
echo $user;
echo "<br /><br />";
echo $access_token;
?>
Related
Is it possible to access profile updates of a facebook user who is not in your(application authorizer) friend list or like-list?
For example:
http://www.facebook.com/zuck
or
http://www.facebook.com/mashable
Is it possible using facebook api?
It depends on their privacy settings
<?php
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
$username = isset($_GET['username'])?$_GET['username']:"johnbevere.page";
$profile = $facebook->api('/'.$username.'/posts');
?>
<br/><br/><img src="https://graph.facebook.com/<?=$username?>/picture">
<?php
foreach( $profile['data'] as $data ){
if($data['message']){
echo $data['message']."<br><hr><br>";
}else{
echo $data['story']."<br><hr><br>";
}
}
?>
Success:
Page updates
User timeline Activity Log
Failed:
User timeline Feed
It is not possible to scrap the public feed of random profile using facebook API
Currently I have the facebook api working. I have included scope string to grab extra permissions.
I am lacking the ability to authorize access to restricted pages on my site. How can I set it up so when facebook logs the user in they are also logged in to my site?
<?php
include 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '****************',
'secret' => '****************',
'cookie' => true
));
// 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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
echo "<a href='$logoutUrl'>Logout</a>";
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_checkins, user_location, friends_checkins')
);
echo "<a href='$loginUrl'>Login</a>";
}
?>
<h3>Welcome to your profile</h3>
<?php
echo $user_profile['first_name'];
echo ' <span> </span> ';
echo $user_profile['last_name'];
?>
This is the basic php api from facebook.
There are endless ways to do this, but you should just be able to place the private content inside of an IF block checking for the logged in Facebook user:
<?php if ($user): // Show the private content ?>
<h3>Welcome to your profile</h3>
<?php
echo $user_profile['first_name'];
echo ' <span> </span> ';
echo $user_profile['last_name'];
?>
<?php endif; ?>
I am using php SDK example from github:
$user_id = $facebook->getUser();
As far as I understand this should open the facebook login dialog with the permissions I defined for the app, but I only see the basic permissions.
The option to check authenticated referrals is no longer available on the facebook app settings form.
Do I have to somehow request the permissions in the code itself?
You need code, to make permission window to pop out.
Something like this shold help:
Do you check on user?
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// Get the current user
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}
else{
$user_profile = $facebook->api('/me');
// STUFF
}
I have the following code, which are working partly
<?php
require_once 'facebook.php';
$app_id = 'MY_APP_ID';
$app_secret = 'MY_APP_SECRET';
$app_url = 'http://mysite.com/index.php/';
$scope = 'user_about_me';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Auth Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
$user_profile = $facebook->api('/me');
echo "id: " . $user_profile['id'];
?>
I get the correct id printed out on this page, but on several other pages i go into the if(!$user).
But there is an error in the oauth url:
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
I have found similar problems here on stackoverflow, but can't seem to fix it :/
Under my settings I have the same url and $app_url
Website with facebook -> site url -> https://www.facebook.com/pages/myappname/373671679372127/
EDIT: I edit my app_url, so it is now the same as my canvas url under app settings: http://mysite.com/index.php/
Now I don't get an error. I just get a blank window :(
EDIT: Importent to clear cookies once a while when testing. Else some very random errors somewhere
Check if you set the correct URL for "Website with Facebook Login" in the dev settings. This cannot be a page on facebook.com, it has to be a Link to YOUR domain.
Also, i would enclose the last 2 rows of your code in an "else" block. And the JavaScript code is wrong. This would be correct:
print('<script> top.location.href="' . $loginUrl . '";</script>');
(easier to understand with double quotes, you missed a semicolon. even if it´s not always needed, you better use it)
Try this code:
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Auth Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\';</script>');
}
else {
echo 'User ID: ' . $user;
}
Also, get rid of the Slash after "index.php". That´s not i folder (i hope/guess).
with the old (2.x) SDK I used this to log someone with offline_access:
$session = array
(
'uid' => $userdata['fb_uid'],
'sig' => $userdata['fb_sig'],
'access_token' => $userdata['fb_access_token']
);
$facebook->setSession($session);
In the new SDK this function doesnt exist anymore. I think I need to login using:
setPersistentData($key, $value)
but this function is protected and I dont know what 'code' is? Do I need this to log the user in or not? And what's going on with 'sig'? Don't I need this anymore?
Hope someone already figured this out because the documentation really doesn't help!
With the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access permission, you ask it when your generate the login URL. 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) {
// The access token we have is not valid
$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 you can retrieve the offline access token and store it. To get it, call :
$facebook->getAccessToken()
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 !
With PHP SDK 2.0 (I guess), I just use it like
$data = $facebook->api( '/me', 'GET', array( 'access_token' => $userdata['fb_access_token'] ) );
This should work with the newer one to as it seems to be more of a clean approach than rather setting up sessions by ourself. Can you try?
Quentin's answer is pretty nice but incomplete, I think. It works nice, but I for example getUser() isn't working in that time because userId (which is getUser() returning) is cached.
I have created a new method to clear all caches and save it persistently.
public function setPersistentAccessToken($access_token) {
$this->setAccessToken($access_token);
$this->user = $this->getUserFromAccessToken();
$this->setPersistentData('user_id', $this->user);
$this->setPersistentData('access_token', $access_token);
return $this;
}