I want to get following local insights of Facebook page using graph API
People Nearby:Hourly
Weekly
Overall
Check-ins
Please see the screen shot.
Image
You can get page insights by using this code and ask for page permissions ('manage_pages','pages_manage_cta') , and get page id first from your likes or managed pages and replace you page id in code with YOUR_PAGE_ID.
use FB php sdk version: facebook-php-sdk-v4-5.0-dev.
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.4', // or use v2.5 latest version
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages','pages_manage_cta'];
$redirectUrl = 'http://localhost/fbapp.php';
$loginUrl = $helper->getLoginUrl($redirectUrl, $permissions);
echo 'Log in with Facebook!';
After generating login url implement the code for response handling and getting required data.
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
setcookie('accessToken',$accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$fb->setDefaultAccessToken($accessToken);
// Get user groups detail
$requestPageInsights = $fb->request('GET', '/YOUR_PAGE_ID/insights');
//Make a batch request
$batch = ['page-insights' => $requestPageInsights];
try {
$responses = $fb->sendBatchRequest($batch);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
for a better view can use this:
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '<p>Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
echo "Response: " . $response->getBody() . "</p>\n\n";
echo "<hr />\n\n";
}
}
And for getting other details visit on and use your related params/scope https://developers.facebook.com/docs/graph-api/reference/v2.5/insights
Related
I have created a basic log in for my app, login.php. It looks like this:
<?php
session_start();
require_once __DIR__ . '/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXX',
'app_secret' => 'YYYYYYYYYYYY',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['user_hometown']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://localhost:8080/myapp/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
I'm now trying to add a logout link to fb-callback.php, to allow the user to log out from the app, but it's not working correctly - it redirects me to Facebook page instead of login.php on my localhost.
What am I doing wrong?
See the last lines of fb-callback.php for logout :
<?php
session_start();
require_once __DIR__ . '/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXX',
'app_secret' => 'YYYYYYYYYYYY',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=hometown', $accessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
echo 'Hometown: ' . $user->getHometown()->getField('name'). "<br>";
$logoutUrl = $helper->getLogoutUrl('{access-token}', 'http://localhost:8080/myapp/login.php');
echo 'Logout of Facebook!';
Also, is there a way to not display the user's access token in the URL after redirecting from login to fb-callback?
i am trying to get get user details from facebook using facebook sdk 5.
login page is loading and asking for login with facebook now when i am clicking on link its redirecting me to facebook and asking to allow share details i am clicking allow and then its redirecting to call back page but problem is callback page is keep loading after some time browser is showing
The connection has timed out
The server at website.com is taking too long to respond.
Below is the screen shot and code i am using
<?php
session_start();
require_once 'Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxxxxxxxxx', // Replace {app-id} with your app id
'app_secret' => 'xxxxxxxxxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$redirect = 'https://website.com/fb2/login.php';
# Create the login helper object
$helper = $fb->getRedirectLoginHelper();
# Get the access token and catch the exceptions if any
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
# If the
if (isset($accessToken)) {
// Logged in!
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
// But we shall we the same page
// Sets the default fallback access token so
// we don't have to pass it to each request
$fb->setDefaultAccessToken($accessToken);
try {
$response = $fb->get('/me?fields=email,name');
$userNode = $response->getGraphUser();
}catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// Print the user Details
echo "Welcome !<br><br>";
echo 'Name: ' . $userNode->getName().'<br>';
echo 'User ID: ' . $userNode->getId().'<br>';
echo 'Email: ' . $userNode->getProperty('email').'<br><br>';
$image = 'https://graph.facebook.com/'.$userNode->getId().'/picture?width=200';
echo "Picture<br>";
echo "<img src='$image' /><br><br>";
}else{
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl($redirect,$permissions);
echo 'Log in with Facebook!';
}
I figured it out it was hosting issue , hosting servers where blocking internal requests which was causing this error.
I've made a little Christmas themed Facebook app which I want to add on a page as a tab but I am running into some issues which makes the app unusable.
The site URL is the following: https://mariusvaduva.com/bradbattle/
If I do the first login there I run into no issues but unfortunately when I test it directly on the Facebook Page Tab, as a new user, after the login I receive a blank page instead of the iframe and the following error:
Refused to display in a frame because it set 'X-Frame-Options' to 'DENY'.
This is how I get the login URL:
session_start();
require_once 'php/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXX',
'app_secret' => 'XXXXXX',
'default_graph_version' => 'v2.8'
]);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://mariusvaduva.com/bradbattle/callback.php');
And this is how I display the link:
<div id="login_container">
<?php echo '<img id="login_btn" src="img/login.png">'; ?>
</div>
I've tried few suggestions including adding an .htaccess file with X-Frame-Options: ALLOW-FROM https://www.facebook.com/ but with no success.
What am I doing wrong? Is there another way of handling this? I really wanted to have this ready by this weekend. Any help or guidance is more than welcomed.
P.S. This is my callback file in case it helps:
session_start();
require_once 'php/Facebook/autoload.php';
require_once 'php/classes/class.database.php';
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXX',
'app_secret' => 'XXXXXX',
'default_graph_version' => 'v2.8'
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (!isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
$tokenMetadata->validateAppId('1849207942031149');
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string)$accessToken;
try {
$response = $fb->get('/me?fields=id,name', $_SESSION['fb_access_token']);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
$db = new Database();
$sql = 'SELECT id FROM users WHERE id = "%s" LIMIT 1';
$db->prepare($sql,array($user['id']));
$data = $db->execute();
if (empty($data)) {
$sql = 'INSERT INTO users (id, name) VALUES ("%s","%s")';
$db->prepare($sql,array($user['id'],$user['name']));
$data = $db->execute();
}
$_SESSION['user_id'] = (string)$user['id'];
$_SESSION['user_name'] = (string)$user['name'];
header('Location: https://mariusvaduva.com/bradbattle/bradbattle.php');
exit;
I have trying to retrieve user profile in my website.
But after I get the access token, I can't use it. The result it show is
Graph returned an error: Invalid OAuth access token
I can get the access token by below code
Login.php
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'I have insert correct app id',
'app_secret' => 'and app secret',
'default_graph_version' => 'v2.0',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl('http://myweb.com/login-callback.php', $permissions);
echo 'Log in with Facebook!';
?>
And below is login-callback.php
<?php
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'I have insert correct app id',
'app_secret' => 'and app secret',
'default_graph_version' => 'v2.0',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/me?fields=id,name', "'".$_SESSION['fb_access_token']."'");
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
?>
Am I doing something wrong? Please help. Thanks.
I only have:
$response = $fb->get('/me?fields=id,name', $token);
$user = $response->getGraphUser();
It works perfectly
I think You should change your code :
"'".$_SESSION['fb_access_token']."'" to $accessToken
and try again
I am new to the whole Facebook API.
I am creating a login page for users, and the idea is that they login with Facebook.
At the top of login page I have the following code:
$fb = new Facebook\Facebook([
'app_id' => "$fb_appid",
'app_secret' => "$fb_appsecret",
'default_graph_version' => 'v2.2',
]);
Then a little lower I have the login button:
if(isset($fb)){
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
$fb_login_url = $helper->getLoginUrl("$server_url/public/facebook/login-callback", $permissions);
} else $fb_login_url = "";
if(strlen($fb_login_url) >= 1) echo "<a href='$fb_login_url'><i class='fa fa-2x fa-facebook-square'></i></a>";
else echo "<a href='#' disabled='disabled'><i class='fa fa-2x fa-facebook-square'></i></a>";
The code works up until there, if I click the button, I go through to the Facebook portal, click the allow for the permissions and whatever, then it redirects me to login-callback.
The code on login-callback is:
if(isset($fb)){
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
}
if (strlen($err_message) <= 0 && isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string) $accessToken;
$fb->setDefaultAccessToken("$accessToken");
try {
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
// $username = $userNode->getName();
// $firstname = $userNode->getFirstName();
// $lastname = $userNode->getLastName();
print_r($userNode);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
}
}
}
The $userNode looks like this:
Facebook\GraphNodes\GraphUser Object
(
[items:protected] => Array
(
[name] => Jacques Koekemoer
[id] => xxxxxxxxxxxxxxxxxx
)
)
I have set the permissions to allow for the email, and if I am not mistaken the public profile is sent automatically.
I have also checked that the button on the login page does have "&scope=email". Below is the code that I have right on the page right now in the login button:
https://www.facebook.com/v2.2/dialog/oauth?client_id=xxxxxxxx&state=xxxxxxxx&response_type=code&sdk=php-sdk-5.0.0&redirect_uri=http%3A%2F%2Fxxxxxxx.xxxxxxxxxxxx.co.za%2Fpublic%2Ffacebook%2Flogin-callback&scope=email
I replaced the client_id, state and domain name because I don't want that information available publicly as I don't know what people can do with it.
Let me know if it is needed to solve the problem.
I used the Facebook guide here to setup and download the SDK.
I solved the problem.
You need to request specific fields from Facebook in the get function.
$response = $fb->get('/me?fields=id,name,email');
This can be found here.
A full list of fields that you can query can be found here.
Example
if (isset($fb)) {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
} catch (Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
}
if (strlen($err_message) <= 0 && isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string)$accessToken;
$fb->setDefaultAccessToken("$accessToken");
try {
// this here is where you specify the fields
$response = $fb->get('/me?fields=id,name,email');
$userNode = $response->getGraphUser();
/* handle the result */
} catch (Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
} catch (Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
}
}
}
One of the my friend was trying to the issue from last 5 days. huummm very irritating. which got love in 2 min...
Assumption: using PHP for O2Authentication
Solution:
$loginURL = $fb->getLoginUrl({your redirect URL},['email']);
And job is done.
Thanks & Regards
Jaiswar Vipin Kumar R.
Check you app version if it is version 2.2 or lower, it will work fine , it is not than it will not return. for that you have to request api with scope for email access.