I have am using FB's Javascript SDK on the client and PHP SDK on the server.
I can see when I use getSignedRequest() I get the signed request containing the code property and the correct userId. However for the life in me I can't figure out how to go on to use this signedRequest to obtain a valid access token which I can use to create further calls for things like user information. I have tried querying for the access code by attempting to instantiate a signed request or calling the ->getAccessToken() method on the $facebook object as well as the jsHelper object but nothing is returned to me. Here's my code:
require_once 'src/autoload.php';
$facebook = new Facebook\Facebook([
'app_id' => $AppId,
'app_secret' => $AppSecret,
'default_graph_version' => 'v2.8',
]);
$jsHelper = $facebook->getJavaScriptHelper();
$signedRequest = $jsHelper->getSignedRequest();
if ($signedRequest) {
try {
$codeField = $signedRequest->get('code');
$g = $facebook->getAccessToken();
//I would hope this would be the access token, but sadly it's an empty
value.
error_log($g);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
error_log("fbResp Ex: ". $e->getMessage());
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
error_log("SDK Ex: ". $e->getMessage());
exit;
}
I never used JavaScriptHelper but AccessToken comes from helper not Facebook object itself. Try
$g = $jsHelper->getAccessToken();
Related
I would like to get images from my Instagram account to my web page. So I try to use FB php sdk and get accessToken first according this documentation. But it returns null. I don't know what is wrong with the code.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID,
'app_secret' => self::APP_SECRET,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$helper = $fb->getRedirectLoginHelper(); // Whichever helper I use access-token is null
dd($helper->getAccessToken());
}
I need help with it. It could be so simple.
EDIT:
After few hours I have this, but the last command throws an Facebook\Exceptions\FacebookResponseException Invalid OAuth access token signature. As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID_FB,
'app_secret' => self::APP_SECRET_FB,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$token = $fb->getApp()->getAccessToken();
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type', $token->getValue());
}
If I've understood the docs correctly, if you want to get an access token dynamically, according to https://developers.facebook.com/docs/facebook-login/web, you need enable fb-login for your app
https://developers.facebook.com/apps/
select your app
add fb-login & follow the tips.
Otherwise you should just be able to get an access token for your app from the web interface and use that over and over.
See also : https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
There's also:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Did%2Cname&version=v9.0
Which enables you to generate an access token, and test out a call to the graph api, AND allows you to export code you can copy/paste:
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/me',
'{access-token}'
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
EDIT:
I see in your original question you state:
As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
According to the docs, if you want to supply an access token as {app_id}|{client-token} (not sure what secret you're using here) you should append this to the URL, which is not in the URL you're using.
See example here: https://developers.facebook.com/docs/facebook-login/access-tokens#clienttokens
The URL they use is:
curl -i -X GET "https://graph.facebook.com/{your-user-id}/accounts?access_token={user-access-token}
So for you this be:
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type&access_token=733163597544229|{client_token}');
EDIT 2:
I managed to get your sample working so perhaps these screen shots will help:
PHP Code:
<?php
$accessToken="EAAJIZAj**************************************************************************************************************************************************************************ZD";
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '642**********502',
'app_secret' => '0185*****************f743',
'default_graph_version' => 'v2.10',
'default_access_token' => "{$accessToken}"
]);
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me');
} 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;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
?>
I took the source code from https://github.com/facebookarchive/php-graph-sdk and copied the src/Facebook dir into my project. I amended the path location in my code
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php'; //<< comment out everything else and check the path is correct with this.
Working code: (same as above) with successful output shown at the bottom of the screen shot.
If you need to get the app secret go to the apps settings to uncover it:
Seems you were right - the access token does have an expiry and I had to refresh mine since using it yesterday.
As far as I know this will probably not work to get the access token .
To get access token you need to implement the login with facebook in your app to get the access token . If your app is only used by limited user then you can get access token on this link https://developers.facebook.com/tools/explorer/ but if your app is used by wide range of user and each user has their own data then you need to implement oauth2 in your app
I am struggling going round in circles getting an Facebook App to post to a Page's Wall, as that Page.
** Note: I put out a 300 point bounty to update an outdated answer of a related, well-viewed, existing question. Happy to award anyone who also answers there with the updated, working, solution
In brief:
I have the App Secret and ID
I have Page ID
I am relying on an in-code approach to generating the token I need.
It is based on a solution I saw posted on the SDK GitHub page but it does not work
I am using API v 2.9
I am using the latest PHP SDK
It's just been hard.
The solution I used is purely based on the one below:
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/Facebook');
require_once __DIR__ . '/Facebook/autoload.php';
use Facebook\FacebookRequest;
$app_id = {{your app-id}};
$app_secret = {{your app-secret}};
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => '{{your app-version}}',
]);
$token = $fb->get(
'/oauth/access_token?client_id=' . $app_id . '&'.
'client_secret=' . $app_secret . '&'.
'grant_type=client_credentials');
$get_token = $token -> getdecodedBody();
$access_token = $get_token['access_token'];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/{{your facebook name}}', $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;
}
$body = $response->getBody();
print_r($body);
?>
I am certainly not lazy. I have been stuck on this issue for weeks.
I have tried the following different solutions and have gotten stuck in either a permissions related issue that was also related to depracated functionality and API calls or getting the right token to do it.
Posting to a facebook page from a website using curl (using a pure CURL approach - "The user hasn't authorized the application to perform this action")
Facebook SDK returned an error: You must provide an access token. Php Facebook Api - (suggests that I support login and redirection callback - yet I do not want any user intervention everytime when posting onto the page)
Graph returned an error: Invalid appsecret_proof provided in the API argument - Previous attempt was based on this example but the appsecret-proof issue
Simple example to post to a Facebook fan page via PHP? - Another CURL-based approach that failed me
https://stackoverflow.com/a/14212125/919426 - Best explained step by
step process for permissions and tokens, but still failed
Update:
Tried the following and got the error "Invalid appsecret_proof provided in the API argument"
$fb = new Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.9',
]);
$postData = [
'message' => "Test Message",
'picture' => 'https://www.website.com/image.jpg'
];
try
{
// 'LONG_LIVED_PAGE_ACCESS_TOKEN' obtained by going to https://developers.facebook.com/tools/debug/accesstoken and clicking
// "Extend Access Token"
$response = $fb->post('/' . 'PAGE_ID' . '/feed', $postData,"LONG_LIVED_PAGE_ACCESS_TOKEN");
}
catch (FacebookResponseException $e)
{
var_dump("Facebook Response Exception occured: \n" . $e);
exit;
}
catch(FacebookSDKException $e)
{
var_dump("Generic Facebook SDK Exception occured: \n" . $e);
exit;
}
catch(Exception $e)
{
var_dump("Uknown Exception occured while attempting to call the Facebook SDK API: \n" . $e);
exit;
}
There are countless more that I have tried and failed.
I'm using v5.0 of Facebook's PHP SDK and have already set up an app.
I would like to get a list of friends via the Graph API using the SDK. To illustrate my implementation, this is the code in which I am trying to get lists of friends on Facebook:
public static function getFriends($access_token)
{
$facebook_app_id = env('FACEBOOK_APP_ID');
$facebook_app_secret = env('FACEBOOK_APP_SECRET');
$facebook = new Facebook([
'app_id' => $facebook_app_id,
'app_secret' => $facebook_app_secret,
'default_access_token' => $access_token,
'default_graph_version' => env('FACEBOOK_API_VERSION') // v2.7
]);
try {
$facebook_request = $facebook->get('me/taggable_friends');
$friends = $facebook_request->getGraphEdge();
$all_friends = $friends->asArray();
if ($facebook->next($friends)) {
while ($friends = $facebook->next($friends)) {
$all_friends = array_merge($friends->asArray(), $all_friends);
}
}
return $all_friends;
} catch (\Exception $e) {
throw $e;
}
}
When the above method is called, it shows a Invalid appsecret_proof provided in the API argument exception message. Digging around, I read that passing a separate parameter of appsecret_proof will get rid of this, however, I've already tried using the App Token of my app taken from the Access Token Tool page to get the value for the appsecret_proof and I still get the error.
And to add, the Require App Secret in my app settings is set to No and yet I still get the same error. Am I missing anything or am I passing the wrong values in getting appsecret_proof?
I've been trying to implement the Facebook OAuth SDK for the past couple of days but keep running into a weird broken link error.
I have followed their instructions on the facebook SDK and used this code for login.php (???? to censor app ID and secret)
$fb = new Facebook\Facebook ([
'app_id' => '????????????????',
'app_secret' => '????????????????',
'default_graph_version' => 'v.2.4'
]);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('http://url.ca/login-callback.php');
This redirects to the login-callback.php file which is what Facebook recommends. Using their provided template code for login-callback.php, mine looks like this:
<?php
session_start();
require_once 'src/Facebook/autoload.php';
//Create the Facebook service
$fb = new Facebook\Facebook ([
'app_id' => '????????????????',
'app_secret' => '????????????????',
'default_graph_version' => 'v.2.4'
]);
$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)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
}
?>
But after being redirected from login.php (clicking on the a href element), I arrive at this:
Sorry, this page isn't available
The link you followed may be broken, or the page may have been removed.
On the Facebook page, no prompt to login, no nothing. I've made my app public already and added this Url to the app as well as ensuring OAuth is enabled, but nothing seems to be working. Does anyone with experience using Facebook OAuth have any idea what's going on?
Is that 'v.2.4' a typo in your question?
The string used in the API should be v2.4 - if you have an extra '.' it's linking you to a URL similar to the real URL of the login dialog, but with an invalid version number in the path
I'm trying to access public information for a user based on their username/pagename.
I'm doing this:
$uname = 'csga5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $session->get('/search?q='+$uname+'&type=user');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
But the exception is thrown, here is the output:
Graph returned an error: (#803) Some of the aliases you requested do not exist: v2.20
Alternatively(Got this from looking at the source code)
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user']);
Returns "Graph returned an error: An access token is required to request this resource." I stole a reference from somewhere using app id and secret as the token in this format:
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user'], self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET);
This throws: "Graph returned an error: A user access token is required to request this resource."
I don't understand why a USER access token is required :/
Anyone know how to search for a user based on username in php? I've seen other examples that were slightly outdated, but I was pretty much the same as what they claim worked.
Edit:
The information we want to acquire is primarily follower count.
First of all, you can´t search for users by username anymore. Earlier this was possible by just using a simple API call: graph.facebook.com/username
This does not work anymore, and the Search API only allows to search for the name (first/last). You are not supposed to use the username anymore.
That being said, you need to authorize yourself and use a User Token, as the error message tells you. That´s just how it is, and you can read it in the docs too:
Searches across Page and Place objects requires an app access token.
All other endpoints require a user access token.
Source: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#search
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
It seems to be the case that it's not possible(at the time) to access more than a user's name publicly. OAuth is required to access the public profile (which is a default permission).
Using the graph api explorer you can verify this using the endpoint /{user-id} and trying to get additional information for a user with whatever id.
The return is like this:
{
"name": "John Doe",
"id": "100003216243221"
}
You can get first and last name as well, by appending:
?fields=name,first_name,last_name
But access to other information fails, even when public. (I only tested location, which clearly has an additional permission).
EDIT!
HOWEVER:
If you wish to access a facebook page, some information is accessible.
This is some of the information returned if no fields are specified: about, id, can_post, category, check_ins, has_added_app, is_community_page, is_published, likes, link, location, name, phone, talking_about_count, username, website, were_here_count.
Using the endpoint:
{page-username-or-id}?fields=engagement,is_permanently_closed,emails,picture
Can retrieve other information fields (assuming they're public).
So code for this:
Facebook sdk v4:
$session = FacebookSession::newAppSession();
$session->validate();
$ret = new FacebookRequest(
$session, 'GET', '/'.$uname.'?fields=name,engagement,phone,link,is_community_page,is_permanently_closed,influences,hometown,general_info,emails,bio,birthday,description,location,username,likes,picture'
);
$ret = $ret->execute()->getGraphObject()->asArray();
If you want to catch exceptions, you can look the thrown exceptions up: https://developers.facebook.com/docs/php/
This works for the same request for facebook sdk v5 (though, I don't know that the way I called send request is advised):
$uname = 'tbdsolutions5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
$response = $session->sendRequest('GET','/'.$uname,[
//Optionally:
//'fields' => 'comma, separated, fields'
],
self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$response = $response->getGraphObject()->asArray();