Facebook Graph API not returning email - facebook

I have the following code:
$fb = new Facebook([
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.9',
]);
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetaData = $oAuth2Client->debugToken($accessToken);
dump($tokenMetaData);
$graphUser = $fb->get('/me?fields=first_name,last_name,email', $accessToken)->getGraphUser()->asArray();
dump($graphUser);
The output for the above is the following:
$metaData:
[
"app_id" => "..."
"application" => "My App Name"
"expires_at" => "2017-07-01 11:40:09.000000"
"is_valid" => true
"issued_at" => "2017-05-02 11:40:09.000000"
"metadata" => array:2 [
"auth_type" => "rerequest"
"sso" => "ios"
]
"scopes" => array:2 [
0 => "email"
1 => "public_profile"
]
"user_id" => "102..."
]
}
$graphUser:
array:3 [
"first_name" => "John"
"last_name" => "Smith"
"id" => "102...",
]
As you can see, the scopes in $metaData clearly has email so it isn't a permission issue. Despite this, the graph user sometimes does not have the email (although in some cases it does).
Why is this and how can I solve this issue?

Add the fields you need to the URL of your request:
https://graph.facebook.com/me?fields=email,name

First check if your access token gets the user's permission for the email
https://graph.facebook.com/me/permissions?
access_token=(access-token)
&debug=all
if in the answer, this content does not appear:
{
"data": [
{
"permission": "email",
"status": "granted"
},
{
"permission": "public_profile",
"status": "granted"
}
]
}
Maybe in obtaining your access token I do not request mail ownership: Add scope=email to the request
https://www.facebook.com/v2.10/dialog/oauth?
client_id=(app-id)
&redirect_uri=(redirect-uri)
&scope=email

One possibility which i came across today is, if i am registering a account where i am not logging in using my email ID, may be using mobile number to login, and even in my profile primary email is not set or set to a mobile number, in this case facebook returns null for email.
I have updated the account and added email to primary email field under settings in facebook page, then i was able to get the email id from facebook.
Hope this helps someone.
Happy coding...

You have to check these steps.
check if your access token gets the user's permission for the email . for that login to your developer account of your app, then tools->graph api explorer then enable user's permission for the email.
check the facebook version, use the latest version.
add email scope in face book login script as below
app.get(
'/auth/facebook',
passport.authenticate('facebook', {
scope: ['user_location', 'email', 'user_friends']
})
);
or
FB.login(function(response) {
// your ajax script
},{
scope: 'email',
return_scopes: true
});

Goto your app > App review > Permissions and Features
Request Advanced access for email which should turn Standard Access into Advanced Access

I solved this issue by specifying the graph api version.
My requested fields first_name,last_name,email,picture
To url: https://graph.facebook.com/me
Did NOT return email.
To url: https://graph.facebook.com/v2.9/me
Did return email.
Hope this helps.

Related

Error pulling companies user is admin of in LinkedIn

I'm currently trying to pull the list of company pages a user is the admin of with the LinkedIn API and am getting the following response:
Array
(
[response] => {
"errorCode": 0,
"message": "Member does not have permission to get companies as admin.",
"requestId": "R1LHP32UKD",
"status": 403,
"timestamp": 1482357250945
}
[http_code] => 403
)
The call works perfectly when authenticated as the same user in the LinkedIn API Console.
Has anyone else come across this?
I figured out the problem.
Even though I had made sure the app had the rw_company_admin permission checked off, I wasn't passing that in the scope when requesting oath2 authorization.
My fixed code below:
The call:
return $linkedin->getAuthorizationUrl("r_basicprofile w_share rw_company_admin", $thisurl);
The function:
public function getAuthorizationUrl($scope, $callback)
{
$params = array('response_type' => 'code',
'client_id' => $this->api_key,
'scope' => $scope,
'state' => uniqid('', true), // unique long string
'redirect_uri' => $callback,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['Linkedin_state'] = $params['state'];
$_SESSION['Linkedin_callback'] = $callback;
// this is where to send the user
return $url;
}
First you have to get user token of linkedin user
Use Socialite or REST API package for oauth.
Once you having user token it is pretty simple to fetch Company list under admin user
$token = 'uflefjefheilhfbwrfliehbwfeklfw'; // user token
$api_url = "https://api.linkedin.com/v1/companies?oauth2_access_token=".$token."&format=json&is-company-admin=true";
$pages = json_decode(file_get_contents($api_url));
You have get $pages json array of list of company profile.

How to get email from facebook through Guzzle in laravel?

I am using below code to login via facebook in laravel.
Referring https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps for token based authentication and using https://github.com/sahat/satellizer for social media integration.
$params = [
'code' => $request->input('code'),
'client_id' => $request->input('clientId'),
'redirect_uri' => $request->input('redirectUri'),
'client_secret' => 'XXXXXXXXXXXXXXXXXXX'
/*'client_secret' => Config::get('app.facebook_secret')*/
];
// Step 1. Exchange authorization code for access token.
$accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [
'query' => $params
]);
$accessToken = json_decode($accessTokenResponse->getBody(), true);
// Step 2. Retrieve profile information about the current user.
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
'query' => $accessToken
]);
$profile = json_decode($profileResponse->getBody(), true);
$profile returning only fb id and user name.
What changes should I do to get email from facebook.
Use below code in your step 2.
$fields = 'id,email,first_name,last_name,link,name';
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [
'query' => [
'access_token' => $accessToken['access_token'],
'fields' => $fields
]
]);
Replace this:
'https://graph.facebook.com/v2.5/me'
with this:
'https://graph.facebook.com/v2.5/me?fields=name,email'
It´s called "Declarative Fields", see changelog.
Also, you need to authorize with the email permission, of course. And the email has to be confirmed. You can´t be 100% sure to get an email, some users use their phone number to login.
You should also check this out: https://github.com/sahat/satellizer/issues/615

cant get email with Net::Facebook::Oauth2

my $fb = Net::Facebook::Oauth2->new(
application_id => 'your_application_id',
application_secret => 'your_application_secret',
callback => 'http://yourdomain.com/facebook/callback'
);
my $access_token = $fb->get_access_token(code => $cgi->param('code'));
###save this token in database or session
##later on your application you can use this verifier code to comunicate
##with facebook on behalf of this user
my $fb = Net::Facebook::Oauth2->new(
access_token => $access_token
);
my $info = $fb->get(
'https://graph.facebook.com/me' ##Facebook API URL
);
print $info->as_json;
when i try to print the json format of response i am missing the email the followin is the output what i get
{"id":"100001199655561","name":"Pavan Kumar Tummalapalli","first_name":"Pavan","middle_name":"Kumar","last_name":"Tummalapalli","link":"http:\/\/www.facebook.com\/pavan.tummalapalli","username":"pavan.tummalapalli","hometown":{"id":"125303864178019","name":"Kodada, India"},"location":{"id":"115200305158163","name":"Hyderabad, Andhra Pradesh"},"favorite_athletes":[{"id":"108661895824433","name":"AB de Villiers"}],"education":[{"school":{"id":"129163957118653","name":"City Central School"},"type":"High School"},{"school":{"id":"124833707555779","name":"Anurag Engineering College"},"year":{"id":"136328419721520","name":"2009"},"type":"College"}],"gender":"male","timezone":5.5,"locale":"en_US","verified":true,"updated_time":"2012-12-30T09:13:54+0000"}
'https://graph.facebook.com/me?fields=email
the i get the following reponse as
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
Probably you do not have adequate permission to access that data. The code you provided doesn't indicate if you have requested email permission on authorization process so I'm guessing you didn't request it.
When you redirect your user to Auth Dialog, which is like https://www.facebook.com/dialog/oauth/?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URL&state=YOUR_STATE_VALUE&scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES , you have to specify scope=email to acquire permission to access email field.
To check if you have the permission, you can access the URL below and see if you have it.
my $permission_ref = $fb->get(
'https://graph.facebook.com/me/permissions'
);
The returning value should be something like below.
{
"data": [
{
"installed": 1,
"email": 1
}
]
}
If it includes email, you have the permission to access user email.
If not you'll have to request permission to get it. With Net::Facebook::OAuth2, you can generate this dialog url like below.
my $fb = Net::Facebook::Oauth2->new(
application_id => 'your_application_id',
application_secret => 'your_application_secret',
callback => 'http://yourdomain.com/facebook/callback'
);
my $url = $fb->get_authorization_url(
scope => ['email'],
);
Redirect your user to this url and you'll get the permission.
And even if you have email permission, sometimes email is not returned because of a bug. You might want to check this bug report, "API call to /me is missing user's email even with email permission."

Register Achievement ok, Create Achievement Returns false

I've just started implementing FB Achievements for my Game. I'm using the PHP SDK for my app.
I've successfully registered an Achievement using the following code from my class which subclasses the PHP SDK class:
$URL = 'apps.facebook.com/<app_name>/ach1.html';
$AppID = $this->getAppId();
$Params = array('achievement' => $URL);
$res = $this->api($AppID.'/achievements', 'POST', $Params);
I can confirm this has been created via the Graph API Explorer:
{
"data": [
{
"url": "http://apps.facebook.com/<app_name>/ach1.html",
"type": "game.achievement",
"title": "Tutorial",
"image": [
{
"url": "<app_img_url>/1-ach.jpg"
}
],
"description": "Tutorial Completed",
"site_name": "<app_name>",
"data": {
"points": 1
},
"updated_time": "2012-07-13T16:05:44+0000",
"id": "<id>",
"application": {
"id": "<app_id>",
"name": "<app_name>",
"url": "https://www.facebook.com/apps/application.php?id=<app_id>"
},
"context": {
"display_order": 0
}
}
]
}
However when I try to create an achievement for myself it returns false:
$URL = 'apps.facebook.com/<app_name>/ach1.html';
$UserID = 100000466230867;
$AccessToken = $this->getApplicationAccessToken();
$Params = array('access_token' => $AccessToken,
'method' => 'post',
'achievement' => $URL);
$res = $this->api($UserID.'/achievements', 'POST', $Params);
The result is "boolean false". No error code is returned. Am I doing something obviously or fundamentally wrong here? I've tried providing a 'display_order' of value 1 and 0 aswell.
I can confirm I've granted the publish_actions permission aswell.
permissions:Array ( [data] => Array ( [0] => Array ( [installed] => 1 [email] => 1 [publish_actions] => 1 [bookmarked] => 1 ) ) )
My app is correctly configured as a game aswell.
Any help greatly appreciated!!
Cheers
If the app is in sandbox mode, take it out.
Ensure the user has authorised & hasn't removed the app
'false' usually means 'Person or page whose access token you're using can't see the data you're asking for',
This happens most often for blocked users, apps in sandbox mode, deleted content, etc
In this case, i suspect the app can't see / interact with the user (if this a test user created via the app settings interface or API this is especially likely as test users have some strange privacy quirks)

Can I specify the permission when posting status through Graph API?

When I post a status through the graph api, I can then retrieve the status through "me/feed" or "me/home". But now the newly posted status can only be retrieved through "me/home".
By checking the status's origin data, I found the posted status has the following privacy:
"privacy": {
"description": "Friends",
"value": "ALL_FRIENDS"
},
When I post message through Facebook WEB, I can choose the privacy, which can be one of PUBLIC, FRIENDS, ONLY ME or CUSTOMER. Can I do the same thing with the Graph API?
Do you mean something like:
$wallpost = $facebook->api('me/feed','post',array(
'name' => 'Headline',
'message' => '',
'privacy' => array(
'value' => 'CUSTOM',
'friends' => 'EVERYONE'
)....