In my database some users have Facebook IDs stored, as once they logged into my website via Facebook. For each of those users I would like to store a profile picture, which would be retrieved from their Facebook accounts.
Facebook PHP SDK specifies the following way to get a user picture:
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/picture'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
The problem is the $session param. Currently, I get the FacebookSession object after the user logs into my website via Facebook. However, for what I want to achieve, I don't have the session present.
Is it possible in PHP SDK to get Facebook user profile picture when having only the user ID, and without them being logged into Facebook?
I hope this helps,
http://graph.facebook.com/USERNAME OR USERID/picture?type=large
http://graph.facebook.com/USERNAME OR USERID/picture?type=small
http://graph.facebook.com/USERNAME OR USERID/picture?type=square
You do not need to log into facebook just use USERNAME OR USERID.
This is simple, basic thing and require only Googling...
If you're not looking for this, please elaborate the task you're doing...
Good Luck!!!
Simply use the following Graph path via GET request:
/{user_id}?fields=picture.type(large),id,name
Field type can be one of the following values:
small
normal
large
square
Or using width and/or height value like this:
/{user_id}?fields=picture.width(200).height(200),id,name
Also you can add redirect=0 param.
By default the picture edge will return a picture instead of a JSON response. If you want the picture edge to return JSON that describes the image set redirect=0 when you make the request.
So you will have the following JSON response:
{
"picture": {
"data": {
"height": 120,
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/hprofile-xaf1/v/t1.0-1/c53.10.120.120/165675_138088076251005_752993_n.jpg?oh=a9450bf53f2d2294531e11ae28be99c1&oe=56C740A5",
"width": 120
}
},
"id": "138087416251071",
"name": "Zenonis",
}
Related
I want read the friendlist of a facebook user with fb sdk 4, but the result is always empty. I created the application on facebook for the id and key and the friendlist permission should be granted by default.
The login and retrieving profiledata works, but not the friendlist request. Here the code:
FacebookSession::setDefaultApplication($id, $key);
try {
$session = $helper->getSessionFromRedirect();
} catch(Exception $ex) { /* handle error */ }
$request = new FacebookRequest($session, 'GET', '/me/friends');
$response = $request->execute();
$graphObject = $response->getGraphObject();
print_r($graphObject);
Instead of '/me/friends' I also tried '/{fbid}/friends', '/{fbid}/taggable_friends' and some other combinations I found with google, but all with the same result.
What did I wrong? And I also want to read the list if the user is offline once an hour. Is that possible and how?
It is completely unrelated to the PHP SDK, since v2.0 of the Graph API you can only get friends who authorized your App with user_friends too.
This has been discussed in countless threads already, hereĀ“s one with a very detailed answer: Get ALL User Friends Using Facebook Graph API - Android
If you want to read stuff while the user is offline, you need to store his User Access Token and use it for an API call. Make sure you extend it though, or it will only be valid for 2 hours.
More information about Access Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
I am using the following to make my requests to Facebook
$facebook->api('/feed',
array(
'access_token' => $_SESSION['fb_access_token'],
));
However, I want to get the news feed of the user.
Not to be confused: I do not want the feed of a certain user, much less of a given page.
I want the News Feed/Feed Stream the user views when accessing Facebook, one that contains the posts of your friends, etc.
How is this possible?
Make an API call to /me/home or /user_id/home where user_id is the current session user.
You are also using the old PHP SDK
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/home'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
Reference: https://developers.facebook.com/docs/graph-api/reference/v2.2/user/home
UPDATE:
The latest Graph API doc suggests the following:
As of October 6th, 2015, this endpoint is no longer available. Please consider using the /user-id/feed edge instead.
This effectively means we cannot access the user news feed provided by Facebook but will have to rely on /user-id/feed as an alternative.
The endpoint is me/home.
https://developers.facebook.com/docs/graph-api/reference/v2.2/user/home
The posts that a person sees in their Facebook News Feed.
Getting all recent notifications including read via Graph API, call:
graph.facebook.com/USER_ID/notifications?include_read=true
Imagine the situation when I'm logged in facebook web application as userA. I know userB's nickname but he is not in my friendlist and I do not know his id. And, of course, he does not use my app.
How can I get userB's id via a nickname?
After that how can I get his wall posts?
Are there any specific permissions? May be there are manual pages I've missed?
In v1.0, the following was possible:
http://graph.facebook.com/v1.0/{user-name}
However, with v2.0 and v2.1, accessing users via IDs or Usernames not connected to your application is not possible. E.g., trying http://graph.facebook.com/v2.1/{user-name} will throw an error:
{
"error": {
"message": "(#803) Cannot query users by their username (user-name)",
"type": "OAuthException",
"code": 803
}
}
Using the new PHP SDK (v4.0.x) you can do the following:
$response = (new FacebookRequest( $session, 'GET', '{user-name}', array(), 'v1.0' ))->execute()->getGraphObject()->asArray();
I have an android client, that initiate log-in to facebook, receives access token and other details about the profile.
The android client passes the access_token and details to the Server (PHP).
Both have facebook sdk installed.
When I initiate a FacebookRequest from the PHP, for example '/me/' It's working.
BUT when I initiate a (friends who have installed the APP) FacebookRequest from the PHP
'/me/friends'. I get "null".
When I use the graph explorer provided by facebook the result is :
{
"data": [
]
}
Additional information for the helpers:
The app contains only two users at the moment, which are friends on facebook.
Those users are both administrators of the app.
Currently the app is not live\published.
We haven't "Start a Submission" in Stats and Reviews as suggested somewhere.
We asked for the permission 'user_friends'.
Since everything in stack overflow requires reputation,
This is how the permissions look like:
http://i.stack.imgur.com/kURwB.png
Thanks
EDIT:
OK I added two test users, Made them friends of each other, and /me/friends through graph explorer is working for them.
BUT why doesn't it work for non-test-users?
Okay,
So apparently Facebook had a problem providing new Access Tokens.
Don't know why, but it provided the same access token, for new Log-Ins.
Now that they fixed that here is a Handy function that I wrote in PHP that will let users
Parse Facebook responses, this might come in hand since there is NOTHING explained over the Docs, Google, StackOverFlow.
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
function find_my_facebook_friends($access_token){
require_once 'facebook-php-sdk-v4-4.0-dev/autoload.php';
FacebookSession::setDefaultApplication('app_key','secret_key');
$session = new FacebookSession($access_token);
$request = new FacebookRequest(
$session,
'GET',
'/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
return $graphObject;
}
Usage:
include_once 'path/to/function.php';
//You wanna use it, just so the PHP file contains your app_key, secret_key Wont be exposed.
$access_token = isset($_POST['access_token']) ? $_POST['access_token'] : NULL;
$facebook_object = find_my_facebook_friends($access_token);
for($i = 0 ; $i < count($facebook_object['data']) ; $i++){
$id = get_object_vars($facebook_object['data'][$i]);
echo $id['id'];
echo $id['name'];
//You don't have to echo, you could handle those fields as you wanted.
}
This function refers to a Mobile Client passing his Log In User's access token to the server.
I hope this will save you lots of time!
I need help on how to bring in a users personal stream.
For example when I go to this webpage I want the user to be able to see his/her facebook live profile stream as if he/she was looking at the facebook website.
Also would you recommend I use the Javascript or PHP SDK ?
Any help or links to examples would be much appreciated.
To get the user's stream an app needs permission to get this data
When a user logs into an app, the app gets access to their public profile and friend list - to read more info about a person, an app must request additional permissions from them
Permissions enable you to access user information. The Graph API reference provides detailed information on the kind of information stored in a user profile and the specific permissions that must be granted by the user before your app can access it.
http://developers.facebook.com/docs/concepts/login/permissions-login-dialog/
In order to be granted permission you need an access token
An access token is a random string that provides temporary, secure access to Facebook APIs.
A token identifies a User, App or Page session and provides information about granted permissions. They also include information about when the token will expire and which app generated the token. Because of privacy checks, the majority of API calls on Facebook need to be signed with an access token
For a user profile, you need a user access token
User access tokens are the standard type for API calls; these are generated in the login flow when a user grants permissions to an app.
Once these basics are known, then you need to pull the data via an HTTP GET to
https://graph.facebook.com/me/feed?access_token=USER_ACCESS_TOKEN
Which will return an array of Post objects containing (up to) the last 25 posts.
http://developers.facebook.com/docs/reference/api/user/#feed
Now you have a JSON response that looks similar to this
{
"data": [
{
"id": "13608786_10101118139895617",
"from": {
"name": "Philippe Harewood",
"id": "13608786"
},
"picture": "https://fbexternal-a.akamaihd.net/safe_image.php?d=AQDuPlCx0L1BP7wp&w=130&h=130&url=http%3A%2F%2Fi4.ytimg.com%2Fvi%2F7_3hKVxOcRI%2Fmqdefault.jpg",
"link": "http://www.youtube.com/watch?v=7_3hKVxOcRI",
"source": "http://www.youtube.com/v/7_3hKVxOcRI?version=3&autohide=1&autoplay=1",
"name": "Suit & Tie (Acoustic Cover) - Tori Kelly",
"description": "hope you enjoy my cover of Suit & Tieeee. JT is the man. for all info and tickets to my upcoming shows go to torikellymusic.com !! love you guys! -----------...",
"icon": "https://fbstatic-a.akamaihd.net/rsrc.php/v2/yj/r/v2OnaTyTQZE.gif",
"privacy": {
"value": ""
},
"type": "video",
"application": {
"name": "YouTube",
"namespace": "yt-fb-app",
"id": "87741124305"
},
"created_time": "2013-03-23T23:21:50+0000",
"updated_time": "2013-03-23T23:21:50+0000",
"comments": {
"count": 0
}
}
],
"paging": {
"previous": "https://graph.facebook.com/13608786/feed?limit=25&since=1364080910",
"next": "https://graph.facebook.com/13608786/feed?limit=25&until=1364080909"
}
}
Based on the language of your app, you should be able to the parse response correctly. In this case to have a near persistent stream of feed data from a user profile. You will need t o store the user access token so that the app can request access any time.
Normally a user access token only lasts for two hours so extending the token to last two months will be a wise choice. You can extend the token by using the following call
https://graph.facebook.com/oauth/access_token?
grant_type=fb_exchange_token&
client_id=APP_ID&
client_secret=APP_SECRET&
fb_exchange_token=SHORT_LIVED_ACCESS_TOKEN
You can exchange this token for a longer-lived one (that will valid for up to 60 days) by passing it to the /oauth endpoint from your server (so that the secret is not exposed) with a grant_type parameter of fb_exchange_token
Now you should store this in a database, e.g. MySQL for retrieval later.
So in summary, load your SQL
CREATE TABLE IF NOT EXISTS `facebook_data` (
`ID` int(11) NOT NULL,
`access_token` varchar(255) NOT NULL,
UNIQUE KEY `ID` (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Pre-populate the data if you wish
INSERT INTO `facebook_data` (`ID`, `access_token`) VALUES
(1, 'temptoken');
Normally I tend to allow JS SDK to handle the user authentication and PHP SDK to handle the API calls. At the same time allowing the cookie set by the JS SDK to be picked up by the PHP SDK
Once the PHP SDK is set up with the cookie and has parsed the signed request
I will extend the access token and the set the new access token in the database.
$facebook->setExtendedAccessToken();
$fbdb_result = $fbdb->query("UPDATE facebook_data SET access_token='" . $facebook->getAccessToken() . "' WHERE ID = 1");
Now in my presentation page, whenever I need I will pull in the access token from the database and set the PHP SDK to the correct user.
$result = $fbdb->query("SELECT access_token FROM facebook_data WHERE ID = 1");
$access_token = mysql_result($result, 0);
$facebook->setAccessToken($access_token);
Then I ensure that no invalidation has occurred since I last stored it
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
$user_posts = $facebook->api('me/feed'); // The user's feed on their wall
}
Then start handling each post and displaying it with some styled CSS
foreach($user_posts['data'] as $post){
$post_link = $post['actions'][0]['link'];
$page_id = $post['from']['id'];
$page_name = $post['from']['name'];
$message = ($post['message']) ? $post['message'] : " ";
$name = ($post['name']) ? $post['name'] : " ";
$story = ($post['story']) ? $post['story'] : " ";
$post_time = $post['updated_time'];
}
You can create a badge for your site (the gear wheel at the top-right of your FB profile) and click on "edit badge". There are quite a few options available.