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();
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 followed these instructions and some others to create an app and get tokens: facebook: permanent Page Access Token?
I used the following php code to post using the app:
<?php
require_once 'src/Facebook/autoload.php'; $fb = new \Facebook\Facebook([ 'app_id' => 'apkey', 'app_secret' => 'appsecret', 'default_graph_version' => 'v2.10', //'default_access_token' => '{access-token}', // optional ]);
$linkData = [
"message" => "Wonderful message.",
]; $pageAccessToken ='pageaccesstoken';
try { $response = $fb->post('/targetfeed/feed', $linkData, $pageAccessToken); } 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; } $graphNode = $response->getGraphNode();
?>
I replace the keys and specific data with description.
My issue is that when I run this script it posts to the feed, but it posts as the app owner. I created the app in my personal account, and went through the token process using that account. I was granted admin access to the account that I want to post to, but when I post to that account it is posting as my person page and I instead want it to post as if I am posting as the account that I am posting to.
I am sure it some access token setting or permissions things, but I cannot figure it out. Any suggestions?
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 try to get the total number of likes for different Facebook pages, like this one for example : https://www.facebook.com/LeoMessi/
I have implemented the following code :
<?php
// Pass session data over.
session_start();
// Include the required dependencies.
require_once( 'vendor/autoload.php' );
// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
'app_id' => '**********',
'app_secret' => '**********',
'default_graph_version' => 'v2.9',
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/176063032413299?fields=likes.limit(0).summary(true)', $_SESSION['access_token']);
var_dump($response);
} 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;
}
It works, but it does not return the total_count property. I don'to how to access this property for any Facebook Page. Could you help me ?
Ok everybody, I just founded the solution just after having posted my question. And the solution is just here : Request to get total count of Facebook page likes in v2.3 API
To get the number of fans, you now need to use fields=fan_count.
So I just replace
/176063032413299?fields=likes.limit(0).summary(true)
With
/176063032413299?fields=fan_count
And it returns
["fan_count"]=> int(88899488)
Hope this can help someone else.
Modify field as :
{page-id}?fields=fan_count
I have been stumped for a while now. I'm attempting to write myself a small app to automatically post to a number of groups that I am members of in FB. I'm a PHP novice, but this is about my strongest skill set for what FB allows in terms of access that I can tell. So far, I CAN post to my own wall no problem but once I try and post to my own FB testing group I'm stumped. Here is my code so far...
<?php
require_once __DIR__ . '/vendor/autoload.php';
require 'src/config.php';
require 'src/facebook.php';
$fb = new Facebook\Facebook([
'app_id' => $config['App_ID'],
'app_secret' => $config['App_Secret'],
'default_graph_version' => 'v2.8',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'Test post to my feed.',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/{group_id}/feed', $linkData, $config['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;
}
?>
Currently the error that this is generating is:
Graph returned an error: (#200) Insufficient permission to post to target on behalf of the viewer
I have made the app Public and generated the access token with manage_pages and publish_pages. Unfortunately I'm out of ideas as of this point. Any help would be greatly appreciated. Thanks in advance.
OK. I figured out my problem at this point. It was that I had to go into the App Settings in my FB user account and change my App from "Only Me" to Public. Once I did that I was able to post to my groups. Next will be to figure out how to post into the proper fields for a "Sell Something" type of post and then to test it in groups that I'm not an admin of.
I figure it has to be possible to post into non-admin groups since there are a number of services out there for FB auto-posting and they have to get around it somehow.