Now I can get my own information such as my id,username.But when I use this access Token in order to get my friend lists,then the error is :
An active access token must be used to query information about the current user.
What is this mean?why the access Token doesn't work?
the first php:
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://my_ip/facebook/login-callback.php', $permissions);
the second php:
(I can get my information):
try {
$response = $fb->get('/me');
var_dump($response);
echo "<br>";
$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;
}
//echo "<br>";
echo 'logged in as the id '.$userNode->getId()."<br>";
echo 'Logged in as ' . $userNode->getName()."<br>";
echo 'the user picture is '.$userNode->getPicture()."<br>";
$picture = $userNode->getPicture();
and:
$permissions = ['user_friends'];
$friendsUrl = $helper->getLoginUrl('http://my_ip/facebook/friends-callback.php',$permissions);
finally,in the third php,I use the same way to get the information,but it is failed.
I think you missunderstood the concept of Facebook API.
First you have to get user permission to accept your request:
$permissions = ['email', 'user_friends']; // Permissions
$loginUrl = $helper->getLoginUrl('http://my_ip/facebook/login-callback.php', $permissions);
Then, in your login-callback.php file you can access the API according to requested permissions. For friends list:
$response = $fb->get('/me/friends');
var_dump($response);
You don't have to login every time after yout first request. The access token will be saved in session.
Related
I use Facebook SDK 5 with an index.php and a profile.php(only for presentation the data). I use them for log in in my website with facebook account, but after the first time that someone logs in from my computer to his fb account I don't have the option to log in again. I automatically log in with his account. How can I delete the "past user data"? I've tried deleting the session but nothing happened.
session_start();
unset($_SESSION['facebook_access_token']);
unset($accesstoken);
if (isset($accesstoken)){
echo hi;
try
{
$fbuid = $fb->getUser();
$me = $fb->api('/me');
}
catch(FacebookApiException $e){}
}
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
echo hi3;
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://newpage.photoclub-tey.com.cy/please/', $permissions);
echo 'Log in with Facebook!';
}
unset($_SESSION);
unset($_SESSION['facebook_access_token']);
$accessToken->revokeToken();
session_destroy();
?>
https://www.facebook.com/profile.php?id=100010558444183
I want to get this profile id when user login with Facebook.
I tried with this but it gives something else.
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me',$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();
$id = $user['id']; ```
You cannot get the "real" id anymore, only an App Scoped ID that is unique and can still be used for identifying returning users. If you want to get a link to the user profile, use the link field: https://developers.facebook.com/docs/graph-api/reference/v3.2/user
For example:
$response = $fb->get('/me?fields=name,link', $access_token);
More details: https://github.com/facebook/php-graph-sdk/blob/5.x/docs/examples/retrieve_user_profile.md
I have a problem with the Facebook API, I try to test fairly regularly ids facebook pages liked by the user who uses my API. But soon enough I got this message: (# 4) Application request limit reached. (in php)
Here's how I connect to the API and get pages:
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXX',
'default_graph_version' => 'v3.1',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = []; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// printing $profile array on the screen which holds the basic info about user
print_r($profile);
$res = $fb->get('/me/likes?limit=1000', $_SESSION['token']);
$res = $res->getGraphEdge()->asArray();
foreach($res as $page) {
$pages[] = $page['id'];
}
} else {
// replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
$loginUrl = $helper->getLoginUrl('http://localhost/index.php', $permissions);
echo 'Log in with Facebook!';
}
I'm looking for a way to keep the page consultation but every time after a while, 4/5 times I have the error message.
If not before it works. Do you have an idea to keep the $ fb object without necessarily making the call? In $ _SESSION it's the same thing.
Thanks
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'm using the code below on my website to try and post a message on a Facebook page that I manage. I'm using the Facebook PHP SDK v5. Whenever I run the code I get directed to Facebook with an error window that says,
"URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs."
However, if I go to the Graph API Explorer and request a User Access Token, then hard code the access token into the script it works just fine. I added Facebook Login to the products tab on my app setting, since that's the only place you can add in the "Valid OAuth redirect URIs". I'm pretty sure the problem is coming from the "Valid OAuth redirect URIs" field in the setting area. I'm not sure what to put in that field or if that is even the problem at all. Currently, I've tried putting the following in the "Valid OAuth redirect URIs" field with no luck;
just my domain i.e. www.my-domain.com
the full path the the calling script i.e. www.my-domain.com/calling-script.php
the full path to a blank page on my server i.e. www.my-domain.com/blank.html
None are working. This is my first go at trying to use the Facebook PHP SDK so I'm sure I'm doing it all wrong... Wondering if anyone is able to give me some guidance on this?
UPDATE:
See answer posted below with fix. My original post was not very clear regarding my intentions. My goal was to successfully post a message to a Facebook Page as the Page, not as an individual user. Hope this helps someone down the road.
Here are my app settings:
Here is the PHP script I am using:
session_start();
$path = "path-to-Facebook-autoloader-on-my-server";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-from-app-settings',
'app_secret' => 'app-secret-number-from-app-settings',
'default_graph_version' => 'v2.7',
]);
/////////////////////////////////////////////////////////////////////////
// If I uncomment the below line the script works fine, but the token expires often
// and I do not want to have to keep updating it
// $_SESSION['facebook_access_token'] = "access-token-obtained-from-Graph-API-Explorer";
/////////////////////////////////////////////////////////////////////////
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$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(isset($_SESSION['facebook_access_token'])){
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}else{
$_SESSION['facebook_access_token'] = (string)$accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string)$longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try{
$request = $fb->get('/me');
}catch(Facebook\Exceptions\FacebookResponseException $e){
// When Graph returns an error
if($e->getCode() == 190){
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
}catch(Facebook\Exceptions\FacebookSDKException $e){
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
try{
// message must come from the user-end
$data = ['message' => 'test message...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphNode();
}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;
}
echo $response['id'];
}else{
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
i checked your script. all looks fine except one thing. can u try after changing
$helper = $fb->getCanvasHelper();
to
$helper = $fb->getRedirectLoginHelper();
and see what error it throws if any?
also u can refer to the shared gist. do let us know your error.
https://gist.github.com/gunnrryy/c2c828fc2a77124cc1bed57af5e216df
So I ended up figuring it out. I played around with the script I originally posted and finally got it to work...sort of. No matter how I ran the script messages were always being sent to the page I manage as a notification. They would not show up on the wall. The end goal I was looking for was to post on to a page that I manage as the page, not as myself. Just in case anyone else comes across this the code below works perfect. Also, it does not require you to submit privileges for approval with Facebook.
The answer to my original question in regards to the "Valid OAuth redirect URIs" field. I ended up putting the path to the calling script in that field and it worked fine.
session_start();
$path = "server-path-to-Facebook-autoloader.php";
$permissions = ['manage_pages', 'publish_pages'];
$callback = "full-path-to-the-calling-script(this-script).php";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-number-here',
'app_secret' => 'app-secret-here',
'default_graph_version' => 'v2.7',
]);
$helper = $fb->getRedirectLoginHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach ($pages as $key) {
if ($key['name'] == 'name-of-page-to-post-to') {
$post = $fb->post('/' . $key['id'] . '/feed', array('message' => 'this is an automated test message from Affordable HomeCare...'), $key['access_token']);
$post = $post->getGraphNode()->asArray();
if($post['id'] <> ''){
$res['myresponse'] = "Successfully Posted to Facebook";
}else{
$res['myresponse'] = "Error: Unable to verify post ID";
}
echo $res['myresponse'];
}
}
} else {
$loginUrl = $helper->getLoginUrl($callback, $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}