How to get profile-picture from facebook sdk? - php

I need get the profile-picture from facebook then user login into web app with facebook login php sdk. And then show this into
I'm using this code:
$fb = new Facebook\Facebook([
'app_id' => 'xxx...x',
'app_secret' => 'xx....xx',
'default_graph_version' => 'v2.4',
'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : 'xx..xx'
]);
try {
$response = $fb->get('/me?fields=id,name,email,picture');
$user = $response->getGraphUser();
$image = $user['picture'];
echo "<img src='$image' height='42' width='42'>";
exit; //redirect, or do whatever you want
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
How can I get the profile-picture and show this correctly?

Some error? I was checking the example of facebook docs and the access token is passing as argument with the call get()
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,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;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
https://developers.facebook.com/docs/php/howto/example_retrieve_user_profile/5.0.0
Edit. If doesn't work try this example: http://www.howtobloger.com/2013/10/how-to-access-app-user-name-and-profile.html

You assigned at $image the array picture:
"picture": {
"data": {
"height": 50,
"is_silhouette": false,
"url": "...",
"width": 50
}
}
So to retrieve the url you should use $image['url'].
PS The question is from 4 years ago, this answer is for reference

Related

Facebook : Fatal error: Uncaught exception 'Facebook\Exceptions\FacebookSDKException' with message 'Signed request has an invalid signature.'

I just copied the following script from facebook
https://developers.facebook.com/docs/php/gettingstarted
I downloaded the main code using composer
<?php
session_start();
require_once '../../Facebook/autoload.php';
print_r($_SESSION);
//if(!isset($_SESSION['user']) || ($_SESSION['user'] < 1) || ($_SESSION['user'] == '')){
$fb = new Facebook\Facebook([
'app_id' => '1444966872674589',
'app_secret' => '54362fa0c423jdui348758ea172537fb',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getCanvasHelper();
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)) {
try {
$response = $fb->get('/me');
$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 'Logged in as ' . $userNode->getName();
print_r($userNode->getName());
}
//}
But above code throws error
Fatal error: Uncaught exception 'Facebook\Exceptions\FacebookSDKException' with message 'Signed request has an invalid signature.'
I have already read this links
Integrating facebook in php giving invalid signed request with oAuth data
and
Integrating facebook php sdk in Facebook Canvas App giving Blank page or oauthData error
But it didn't solve my problem
please help I can't solve the problem
If you are calling your script from your website you can try this:
replace:
$helper = $fb->getCanvasHelper();
with:
$helper = $fb->getRedirectLoginHelper();
also replace:
if (isset($accessToken)) {
try {
$response = $fb->get('/me');
$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 'Logged in as ' . $userNode->getName();
print_r($userNode->getName());
}
with:
$permissions = 'list of facebook permissions';///optional
if (isset($accessToken)) {
try {
$response = $fb->get('/me');
$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 'Logged in as ' . $userNode->getName();
print_r($userNode->getName());
}else{
$loginUrl = $helper->getLoginUrl('url-of-calling-script.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}

Access Token not retrieving data from Facebook PHP sdk

Here's my code to retrieve user's info from Facebook. I am using PHP SDK.
public function indexAction()
{
$fb = new Facebook\Facebook([
'app_id' => '934741473308351',
'app_secret' => 'de001d018a7769eb17eb11300e772a0c',
'default_graph_version' => 'v2.5',
'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : 'APP-ID|APP-SECRET'
]);
try {
if(isset($_SESSION['facebook_access_token'])){
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
Mage::log("Email====>Before".$userNode->getFirstName());
// echo 'Name: ' . $user['first_name'];
$this->_redirectUrl('/app-new/app/#/myAccount');
exit;
}
//redirect, or do whatever you want
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_likes']; // optional
$loginUrl = $helper->getLoginUrl(Mage::getBaseUrl().'facebook/facebook/authenticate', $permissions);
echo $loginUrl;
}
public function authenticateAction(){
Mage::log("Authenticate=======");
$fb = new Facebook\Facebook([
'app_id' => '934741473308351',
'app_secret' => 'de001d018a7769eb17eb11300e772a0c',
'default_graph_version' => 'v2.5',
]);
$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!
Mage::log("Access Token=================>".(string) $accessToken);
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$fb->setDefaultAccessToken((string) $accessToken);
$_SESSION['facebook_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
Mage::log("Email====>Before".$userNode->getFirstName());
$customer = $this->checkIfUserExists($userNode);
$this->_redirectUrl('/app-new/app/#/myAccount');
exit;
} 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;
}
}
}
I got the result first, but I am not getting result after that. Is it due to access taken or something else. What am I doing wrong here
You are missing a new feature of v2.4 of the Graph API, it´s called "Declarative Fields". You now have to add a field parameter to specify the fields you want to get, else you will only get id and name: https://developers.facebook.com/docs/apps/changelog#v2_4
Also, make sure your login works correctly and you get asked for the email permission when you authorize your App.

How to get local insights of Facebook page using graph API?

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

Facebook PHP SDK v5 Post to Fan Page

I would like to use the Facebook PHP SDK v5 to automatically post to a FAN PAGE. I have the code below which successfully posts to my own wall, but how do I alter the code to post to my fan page? From what I've read, I need to pass in the page id of the fan page?
$params["message"] = 'test';
$params["link"] = 'https://example.com';
$params["picture"] = 'https://example.com/images/logo_hod.jpg';
$params["description"] = 'testtt';
$access_token = $accessToken;
try {
$response = $fb->post('/me/feed', $params, $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;
}
$graphNode = $response->getGraphNode();
echo 'Posted with id: ' . $graphNode['id'];
I tried replacing this line:
$response = $fb->post('/me/feed', $params, $access_token);
with this to substitute in the fan page id:
$response = $fb->post('/229107363768165/feed', $params, $access_token);
and got the error:
Graph returned an error: Unsupported post request.
UPDATE: I also made the app "public" in an attempt to get past the "unsupported post request" error. No luck.
i think your $params is not right.
I use this:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$params = [
'link' => 'https://example.com',
'photo' => 'https://example.com/images/logo_hod.jpg',
'message' => 'A test post!',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $params, '{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;
}
Post Links Using the Graph API
I assumes that you've already obtained an access token and the access token must have the publish_actions permission for this to work.

Facebook user Graph does not return Email PHP

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.

Categories