$config = array(
'appId' => 'yyyyyyyyyy',
'secret' => 'xxxxxxxxxx',
'cookie' => true,
'domain' => true
);
$facebook_client = new Facebook($config);
//Grab the user's session
$session = $facebook_client->getSession();
/*If session does not exist, the user is not loggedin or hasn't added the app
so redirect them to the authorize page.*/
if(!$session){
$text = "<script type=\"text/javascript\">\ntop.location.href = \"$oauth_url\";\n</script>";
echo $text;
exit;
}
$access_token = $access['access_token'];
$params = array('access_token' => $access_token);
try{
$me = $facebook_client->api('/me',$params);
$feed_params = array();
$feed_params['message'] = "Hello world";
$feed_params['link'] = "http://apps.facebook.com/jagdish/";
$feed_params['name'] = "jag";
$feed_params['caption'] = "Trying to post from application";
$feed_params['description'] = "From jag";
$feed_params['access_token'] = $access_token;
$id = me['id'];
$result = $facebook->api('/me/feed/','post',$feed_params);
}
catch(FacebookApiException $e)
{
error_log($e);
}
This is my code. When i executed it, got an exception saying
com.caucho.quercus.QuercusException: com.caucho.quercus.QuercusErrorException: /base/data/home/apps/fbookworkshop/version1.349114876107177725/index.php:49: Fatal Error: Method call 'api' is not allowed for a null value.
Where am i going wrong?
I guess you are mixing 3 (or more) tutorials together!!
Issues in your code:
The first issue:
$text = "<script type=\"text/javascript\">\ntop.location.href = \"$oauth_url\";\n</script>";
In this line:
Where did you set the $oauth_url?
Also no need for the \n
The second issue (mentioned by #fazo).
The third issue, NO NEED for the access_token all together if there's a valid session! so don't set it or use it in any of your requests as long as you are using /me.
The fourth issue:
$result = $facebook->api('/me/feed/','post',$feed_params);
Here you are using the code from another tutorial, since you are using $facebook var instead of $facebook_client
change
$access_token = $access['access_token'];
to
$access_token = $session['access_token'];
and tell us what happened
UPDATE:
looks like you can't use /me
https://github.com/facebook/php-sdk/issues/closed#issue/294
Related
I have been trying to post to an event that has already been created in a mySQL database and use facebook's graph api to post it to a group page. I am able to post an array created right in the code, but I would like to post an array that I am pulling in from a POST command. Here is what I have.
public function get_event()
{
require_once 'application/php-sdk/facebook.php';
$config = array(
'appId' => '1407968509465242',
'secret' => '***********************',
'cookie' => false,
'fileUpload' => true
);
$id = $_POST['eventsDrp'];
$this->load->model('mdl_facebook_event');
$output = $this->mdl_facebook_event->get_event($id);
print_r ($output);
$facebook = new Facebook($config);
// Set the current access token to be a long-lived token.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
$page_id = '594922100555123';
$page_access_token = '*******************';
// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2012-04-24T22:01:00+0000';
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.
// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'access_token' => $page_access_token,
'page_id' => $page_id //where $page_id is the ID of the page you are managing
);
// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $output);
if(isset($ret_obj['id'])) {
// Success
$event_id = $ret_obj['id'];
echo ('Event ID: ' . $event_id);
} else {
echo ("Couldn't create event.");
}
// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
echo "<pre>$msg</pre>";
}
I am trying to post the array from $output. I have tried to post from $params and everything works fine. When I try and post from $output I get Fatal error:
Uncaught OAuthException: Invalid token: "594922100555123". An ID has already been specified.
Is there some limitation with Fat Free Framework when we try to output the page into facebook tab?
I already try it with this below code, and unfortunately in the facebook tab iframe always empty blank page.
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->route('GET /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
First when user try to access GET /landing it will redirect to facebook tab and show the page GET /. But somehow it always return empty page, already inspect it with firebug on firefox and there is no error, on the response tab always shows Reload the page to get source for: https://localhost/f3-fb/. Already try it with my office framework and works perfectly.
If anybody ever get this problem please advise.
The problem is in XFRAME, on default F3 set the XFRAME value as SAME-ORIGIN, based on this doc, developer must overload the value with ALLOW-FROM uri.
Here is the full code for index.php:
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/');
$f3->route('POST /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
Add the config $f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/'); to allow this url inside on facebook iframe.
And always use POST for the route inside the facebook iframe (still don't know why must using that with F3, but it will occur the error and asking for POST route)
I have search over and over again and I can't seem to find an answer. What am I doing wrong?
My error is FacebookApiException [ 0 ]: An active access token must be used to query information about the current user.
EDIT Just to add. This worked once or twice, but never in succession.
require_once('media/fb/facebook.php');
$app_id = '123456';
$app_secret = '123456';
$my_url = 'mysiteurl';
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUload' => 'false');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl(array('redirect_uri' => $my_url));
header("Location:" . $login_url);
$user_profile = $facebook->api('/me','GET');
}
Your help is greatly appreciated.
Does your error come from this line: $user_profile = $facebook->api('/me','GET'); at the bottom?
The header function will re-direct the user to Facebook login page which will cause the browser to refresh. You won't get the user's access token immediately after that. You need to wait until the user is redirected back to your website to get the access token. You need to set $my_url to point to the same page of the codes you wrote here.
The FIRST time my index.php loads I get a value of 0 when calling:
$facebook->getUser();//returning 0 instead of id on first page load
The call works fine on any subsequent page load.
This is my code:
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$user_id = $facebook->getUser();//Returns 0 on first load.
Has anyone else experienced this? Maybe I should automatically reload the page if $facebook->getUser(); does not return a valid user?
May be it is not authenticating it for very first time, You can do some thing like this:
<?php
$facebook = new Facebook(array(
'appId' => xxx,
'secret' => xxx
));
$user_id = $facebook->getUser();
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$me = $facebook->api('/me','GET');
echo "Name: " . $me['name'];
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll redirect and
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
} else {
// No user, redirect for the user to login
$login_url = $facebook->getLoginUrl();
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
EDIT:
If error persists, try with this edit, just change your this line:
$me = $facebook->api('/me','GET');
to this:
$me= $facebook->api('/'.$user_id, 'GET');
Hope this will solve your problem.
I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.