I'm about to give up. for about a week i'm trying the simplest thing, authentication via facebook. every time I authenticatiom (via facebook login url) , getUser() and api('me'
) returns me null.
why?
the code:
$facebook = new Facebook(array(
'appId' => '306597542762982',
'secret' => '88XXXXXX7f1',
));
$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;
}
}
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'user_actions.news,publish_stream,user_about_me,email,publish_actions'));
print $loginUrl; exit;
}
var_dump($facebook->api('me'));
SOS.
EDIT: POST :
$params = array (
'article' => 'http://fb.raal.co.il/content/view/$id/$title',
'access_token' => $facebook->getAccessToken()
);
$out = $facebook->api( '/me/news.reads','post', $params);
var_dump($out); exit;
Continuing what NullPointer quoted earlier, from user ifaour:
Just check for the current Facebook user id $user and if it returned null then you need to reauthorize the user (or use the custom $_SESSION user id value - not recommended)
require 'facebook/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();
$photo_details = array('message' => 'my place');
$file='photos/my.jpg'; //Example image file
$photo_details['image'] = '#' . realpath($file);
if ($user) {
try {
// We have a valid FB session, so we can use 'me'
$upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
// redirect to Facebook login to get a fresh user access_token
$loginUrl = $facebook->getLoginUrl();
header('Location: ' . $loginUrl);
}
I've written a tutorial on how to upload a picture to the user's wall.
With the additional information, does this help? There is additional information I've found related to this, stating to attempt
$facebook->getAccessToken();
Apparently, that call can give either an app access token or a user access token. Depending on what you are trying to do with the access token, you will need the appropriate kind.
Alternatively, you may need to request certain permissions for what you are trying to do, which you can find here.
Related
Everything works fine with test users but when I publish my app and user clicks on app the permission popup dialog box does not appear. I guess there is some oauth problem but not sure. Please help me out
require 'facebook-files/facebook.php';
$app_id='xxxxxxxxxx';
$secret='xxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie'=> true,
'grant_type' => 'client_credentials'
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
//$access_token = $facebook->getAccessToken();
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends?fields=id,name,birthday,picture');
$event = $facebook->api('/me/?fields=events.fields(id,name)');
} catch (FacebookApiException $e) {
echo "Exception".error_log($e);
$user = null;
exit;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'read_stream,publish_actions,publish_stream,user_birthday,friends_birthday', 'display'=>'popup')
);
}
Make sure to add your site to the "valid oauth redirect uris" input field in your app's settings.
I keep getting the error in the title, while using a simple code:
require_once('sdk/src/facebook.php');
require_once("AppInfo.php");
function idx(array $array, $key, $default = null) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
function he($str) {
return htmlentities($str, ENT_QUOTES, "UTF-8");
}
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'sharedSession' => true,
'trustForwarded' => true,
));
$arrayForJSON=array();
$user = $facebook->getUser();
$friends = idx($facebook->api('/me/friends'), 'data', array());
if ($friends) {
$arrayForJSON['friends']=$friends;
}
print_r($friends);
I really don't know how to solve it, I've been searching and trying many answers on stackoverflow
You need to set the access token to be able to get data or act on behalf of the user. Are you going through a login flow to allow authorization to your Facebook application?
Try the example at https://developers.facebook.com/docs/reference/php/facebook-api/
It provides the very basic login flow that will grant access to the data you're seeking.
you need to check if already login if not redirect the user to login link
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '191149314281714',
'secret' => '73b67bf1c825fa47efae70a46c18906b',
));
// 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');
$friends = idx($facebook->api('/me/friends'), 'data', array());
} 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('scope'=>'offline_access'));
}
So this is working fine... But when I refresh the page twice(or click on two pages who include this script fast) it gives this error
OAuthException: An active access token must be used to query information about the current user.
Any ideas?
<?php
$app_id = '***************';
$app_secret = '**************';
$app_namespace = '****************';
$app_url = 'http://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'POST');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//<img src="https://graph.facebook.com/?php echo $user; ?/picture">
//?php print_r($user_profile); ?
?>
I personally find it easier to manage the access_token myself. Facebook's Graph API secures protected endpoints by requiring that an access_token be passed in. The PHP SDK abstracts this away, but I have never been comfortable with Facebook handling the information because sometimes it just doesn't work. This isn't to say that the library is bad, but only that I haven't been using it correctly. Keep this caveat in mind.
It looks like you're working with a Facebook Canvas App. When the user successfully authenticates for the first time, Facebook will send an access_token in $_GET. At this point, you should save this to your database, since that access token is good for 3 months or so.
At the point, from then on, you can pass in the access_token in the call parameters:
try {
$user_profile = $facebook->api('/me', 'POST', array(
"access_token" => '' // access token goes here
));
} catch (FacebookApiException $e) {
// error handling
}
Given that Facebook is returning the error that you need an access token in order to call the /me resource, it looks like $facebook->getUser(); is returning something. You may want to double-check what it is.
While I'm here, you're using this logic:
if (!conditional) {
// do something
}
if (conditional) {
// do something else
}
Confusing. Use else:
if (conditional) {
// do something
} else {
// do something else
}
I'm trying to get the access token of my app using graph api, by requesting the following string:
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=app_id&redirect_uri=canvas_page&scope=read_friendlists
This redirects to: canvas_page/#access_token=xxx&expires_in=4124&code=A...
But i am not sure how i can parse this with PHP, so that i eventually can make a json request to get the friendlist.
I hope you may be able to guide me :)
Thank you
Are you using the Facebook PHP sdk?
https://github.com/facebook/php-sdk
You can use it like this:
$facebook = new Facebook(array(
'appId' => 'your_app_id',
'secret' => 'your_app_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;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
You can use the $loginUrl to make a link where the user needs to click that will authorize your application if they haven't done so already
Then you can make calls to the graph api like this:
$friends = $facebook->api('/user_id/friends');
You can use the following code below. It worked for me.
First, you need to download Facebook SDK from here https://github.com/facebook/php-sdk
function facebook_oauth_init($facebook_app_id, $facebook_app_secret, $cookie = false)
{
$facebook = new Facebook(array("appId" => $facebook_app_id, "secret" => $facebook_app_secret,
"cookie" => $cookie));
return $facebook;
}
$fb_app_id = "YOUR_APP_ID";
$fb_app_secret = "YOUR_APP_SECRET";
$fb_user_id = "YOUR_USER_ID";
$fb_access_token = "YOUR_GIVEN_ACCESS_TOKEN";
$facebook = facebook_oauth_init($fb_app_id, $fb_app_secret);
$accounts = $facebook->api('/' . $fb_user_id . '/accounts', 'get', array('access_token'=>$fb_access_token));
$accounts = $accounts['data'];
$access_token_2
foreach($accounts as $acc)
{
if($fb_page_id == $acc['id'])
{
$access_token_2 = $acc['access_token'];
break;
}
}
"$access_token_2" should be what you are looking for.
Hope this helps.
Muhammad.
Using this "api" method (on php sdk), you don't need to especify the access token, it will be generated and setted into Facebook object.
Anyway, you can to use $facebook->getAccessToken()
http://developers.facebook.com/docs/reference/php/facebook-getAccessToken/
I am trying to write a script that will post to my facebook page and I assume all I have to do is modify my code for posting to a users stream.
$attachment = array
(
...
);
$result = $facebook->api($user.'/feed/','post',$attachment);
What do I put instead of the user's id? I am not sure if it is simply my page's id. Any ideas?
Assuming that my facebook page means my feed you simply do
$user = 'me';
1. POST ON PAGE'S WALL AS USER:
Publishing on a Page's wall as user is straight forward, you could use something like:
<?php
// path to sdk
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
try {
$post_id = $facebook->api('/TARGET_PAGE_ID/feed', 'POST', array('message'=>"I am a user!"));
var_dump($post_id);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream'));
}
// rest of code here
Note:
The owner of the post will be the current connected user.
the above depends on the page's Posting Ability settings.
you need the publish_stream permission
2. POST ON PAGE'S WALL AS PAGE:
Now to post as a Page you could use something like:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.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',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'TARGET_PAGE_ID';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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('scope'=>'manage_pages,publish_stream'));
}
// rest of code
?>
Notes:
You need the manage_pages and publish_stream permissions
Once you obtain the page's access_token you can start posting on its behalf
More about this is explained in depth in my tutorial.