I am using the following code to try and retrieve a Page's insights using FQL. Obviously I've stripped out the App ID, App Secret, URL, and Object ID (in the FQL query).
The page logs in the user correctly, and asks for the "read_insights" permission. I am logging in as a user that is an admin for the Page I am trying to access.
The response I'm getting is:
Array ( [0] => Array ( [metric] => page_like_adds [value] => 0 ) )
I'm brand new to FQL, so I'm sure I'm doing something dumb here.
<?php
require_once('facebook/src/facebook.php');
define('APP_ID', '');
define('APP_SECRET', '');
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
'cookie' => true,
));
$app_id = "";
$app_secret = "";
$my_url = "";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=read_insights";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$token = file_get_contents($token_url);
$params = null;
parse_str($token, $params);
} else {
echo("");
}
$fql = "SELECT metric, value FROM insights WHERE object_id=OBJECT_ID AND metric='page_like_adds' AND end_time=1272351600 AND period=86400";
$fqlresponse = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
print_r($fqlresponse);
?>
With your FQL:
$fql = "SELECT metric, value FROM insights WHERE object_id=OBJECT_ID AND metric='page_like_adds' AND end_time=1272351600 AND period=86400";
you're selecting the metric "page_like_adds", which is "Likes of your Page's content" till "1272351600", which is "Tuesday, April 27th 2010".
So I guess, your query is not, what you want.
Which insigh metrics do you want from your page?
I suggest to read: https://developers.facebook.com/docs/reference/fql/insights/ (the official Docs too FQL metrics)
You may also try the Graph API to access insights:
https://developers.facebook.com/tools/explorer/
Related
I am unable to figure out why every time I click on a link inside of my app (page 2 from page 1), it goes to page 2 but automatically redirects back to page one. This is getting frustrating. I feel like I have done everything correctly in the code below because it authenticates the user and everything as it should... but the only problem is, I can not navigate anywhere without it automatically going back to the index page.
$fb_app_id = "xxxxxxxx";
$fb_app_secret = "xxxxxxxxx";
$fb_scope = "email,user_birthday,user_location";
$fb_response_type = "token";
$canvas_page = "https://apps.facebook.com/app-name/";
require_once 'sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => '' . $fb_app_id . '',
'secret' => '' . $fb_app_secret . '',
'cookie' => true,
));
$app_id = '' . $fb_app_id . '';
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=" . $fb_scope . "&response_type=" . $fb_response_type . "");
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
$UserId = $data["user_id"];
$token = $facebook->getAccessToken();
$facebook->setAccessToken($token);
$user_profile = $facebook->api('/me/');
} ...
Can someone look at this and tell me what it is that I am doing wrong?
Thanks in advance!
Problem solved....
require_once 'sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => '0000000000000000000',
'secret' => 'if-i-tell-ya-ill-have-to-kill-ya',
'cookie' => true,
));
$canvas_page = "https://apps.facebook.com/whatever/";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $fb_app_id . "&redirect_uri=" . urlencode($canvas_page) . ("&scope=" . $fb_scope . "&response_type=" . $fb_response_type . "");
$signed_request = $_REQUEST["signed_request"];
$uid=$facebook->getuser();
if(empty($uid)){ echo("<script> top.location.href='" . $auth_url . "'</script>");}
else { // do something }
the code is according to fb manual, and i ve noticed that if the user refreshes the page, i can't retrieve the id of the user..the user will need to clear from the address bar the entire string after my url, in order to be able to obtain user info..
<?php
$app_id = "myid";
$app_secret = "mysecretkey";
$my_url = "http://myurl.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=publish_actions";
header("Location: " . $dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$_SESSION['access_token'] = $params['access_token'];
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo var_dump($user);
else {
echo("The state does not match. You may be a victim of CSRF.");
}
var_dump returns to me all necessary information after first redirect, but if i refresh the page it returns null..
perhaps i need to "destroy" any session cookies??
This happens cause the $code that you are using is no longer valid and has been consumed.
Also might I suggest you to use Facebook's PHP SDK. It would reduce time to develop your app and take care of these errors for you.
i altered the code a little bit, in order to by pass the problem..
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
if ($params['access_token'] == NULL) {
header("Location: " . $my_url);
}
$user = json_decode(file_get_contents($graph_url));
}
so, if the access_token is not valid, then the page is "forced" to be reloaded without any string query and retrieves a new one.. :)
there was a usefull reference over here as well https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
and many thanks to #Anvesh Saxena for his contribution
This question already exists:
Facebook getUser() always returns 0 [duplicate]
Closed 10 years ago.
This Facebook PHP SDK is driving me CRAZY!
getUser() always return 0
let me explain what I do:
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
));
$user = $facebook->getUser();
if ($user === 0)
{
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, publish_stream',
'redirect_uri' => FB_REDIRECT_URI
));
echo "<script type='text/javascript'>window.location = '$loginUrl';</script>";
exit();
}
simple code, equals to the example. Good...
I have this code in login.php and complete.php
I send the request from login.php and set the redirect_uri to complete.php (the same I wrote in Website with Facebook Login...obviously a complete URL like https://www.example.com/complete.php)
I really do not understand Why I still get 0!
It is not possible, Im logged in Facebook following the LoginURL.
I also passed the "permissions" with the URL.
I already registered at this app, so I really do not understand the reason why this SDK is continuing to return 0.
Could someone help me?
INFO:
I only have selected Website with Facebook Login, nothing else... "App on Facebook" is not selected.
EDIT:
https://www.facebook.com/login.php?api_key=216182291818102&skip_api_login=1&display=page&cancel_url=https%3A%2F%2Fwww.example.com%2Fusers%2Fcomplete%2F%3Ferror_reason%3Duser_denied%26error%3Daccess_denied%26error_description%3DThe%2Buser%2Bdenied%2Byour%2Brequest.%26state%3D720fab495a21639032816d3c688ae87b&fbconnect=1&next=https%3A%2F%2Fwww.facebook.com%2Fdialog%2Fpermissions.request%3F_path%3Dpermissions.request%26app_id%3D216182291818102%26redirect_uri%3Dhttps%253A%252F%252Fwww.example.com%252Fusers%252Fcomplete%252F%26display%3Dpage%26response_type%3Dcode%26state%3D720fab495a21639032816d3c688ae87b%26perms%3Duser_birthday%252Cemail%26fbconnect%3D1%26from_login%3D1%26client_id%3D216182291818102&rcount=1
i am used same example and it's work for me.
my connection is like this,try to add cookie = true and check, hope will work for you
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
Where did you get the example from? This is from the FB Developer page (https://developers.facebook.com/docs/authentication/server-side/):
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
Your code is looking good. You should provide one more parameter to facebook array that is cookie=>true. You should refer the following tutorial which worked for me.
http://www.9lessons.info/2011/02/login-with-facebook-and-twitter.html
Hope it will work for you.
Now I am posting the configuration of APP.
App ID/API Key
xxxxxxxxxxxxxxxxxx // your App ID
App Secret
xxxxxxxxxxxxxxxxxxxxxxx //Your secret key
Site URL
http://localhost/ //your site url
Contact Email
example#example.com //your email id
Support URL
http://localhost //your support url
I only provided this much information and its perfectly working for me.
Try this
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
and first you login in facebook account then execute this code.
$user=$facebook->getUser();
It looks like the authentication bit when Facebook is sending code, state parameters through $_GET is not covered in PHP-SDK.
if(!empty($_GET['code']) && !empty($_GET['state']))
{
$response = file_get_contents('https://graph.facebook.com/oauth/access_token?' . http_build_query(array('client_id' => AY_FACEBOOK_APP_ID, 'client_secret' => AY_FACEBOOK_APP_SECRET, 'redirect_uri' => AY_FACEBOOK_TAB_URL, 'code' => $_GET['code'])));
// now check state and parse access token
ay($response);
}
Did I overlook something? If not, then what is the reason for not including it?
Please note that I did not ask to provide an example as DMCS and Luc Franken did so far.
Yes, the state and code parameters are discussed on http://developers.facebook.com/docs/authentication/ in the part about CSRF protection.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
$response = file_get_contents(
'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => AY_FACEBOOK_APP_ID,
'client_secret' => AY_FACEBOOK_APP_SECRET,
'redirect_uri' => AY_FACEBOOK_TAB_URL,
'code' => $_GET['code']
)
)
);
// now check state and parse access token
ay($response);
That reads a bit better.
Now your question: It just works:
https://graph.facebook.com/oauth/access_token?client_id=1&client_secret=2&redirect_uri=3&code=1234
With this testing code:
echo 'https://graph.facebook.com/oauth/access_token?' . http_build_query(
array(
'client_id' => 1,
'client_secret' => 2,
'redirect_uri' => 3,
'code' => '1234'
)
);
Try to put the url in a variable, that will make life easier when debugging.
If you don't get anything in the code= part you might have values in the $_GET['code'] variable which won't be accepted by http_build_query since that function urlencodes the array data.
As title says I have a strange problem. When I click another link on my index page,it redirects to index again. I'm writing the same permission code on both pages.
Here is my code:
<?php
$code = $_REQUEST["code"];
if(empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&scope=email,publish_stream,offline_access";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret="
. $app_secret . "&code=" . $code . "&scope=email,publish_stream,offline_access";
$access_token = file_get_contents($token_url);
$graph_url = "https://graph.facebook.com/me?" . $access_token;
$user = json_decode(file_get_contents($graph_url));
?>
I'm writing this code all pages that I've linked on my index.
Is my code wrong, have a server problem or something else ?
Do the URLs in the links on the index page contain a code variable. If it's not explicitly declared in the query string portion of URL the Oauth dialog will be triggered and, if the app is already installed, the user will be redirected to $my_url.
On a side note, judging from your code you could benefit from using the existing Facebook PHP SDK. Here's a code snippet that uses the current (v3.0.0) SDK that contains the behaviour listed above:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
$fb_user_id = $facebook->getUser();
if ($fb_user_id) {
try {
$user = $facebook->api('/me');
} catch (FacebookApiException $e) {
$fb_user_id = null;
$params = array(
'redirect_uri' => $my_url,
'scope' => 'email,publish_stream,offline_access' );
$dialog_url = $facebook->getLoginUrl($params);
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
}