PHP - Graph API 2.8 not requesting email - php

I'm integrating FB login on my website and for that I need the email of the user. Here's part of the code
$fb = new Facebook\Facebook([
'app_id' => 'app-id',
'app_secret' => 'secret',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
if (isset($accessToken)) {
$fb->setDefaultAccessToken($accessToken);
try {
$requestProfile = $fb->get("/me?fields=name,email");
$profile = $requestProfile->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
print_r($profile);
}
What I'm getting back is name and id. Even the popup that requests users to grant permissions to the app doesnot ask for the email. And understandably it doesn't return it as well.
I've seen this and many other questions but none of the solutions have worked for me. What am I doing wrong?

You need to request permission to obtain the user email.
Please review https://developers.facebook.com/docs/php/howto/example_facebook_login to see how to request it (e.g.: permissions = ['email', 'user_likes', 'user_location', 'user_friends', 'user_birthday', 'user_hometown'];)
Refer to https://developers.facebook.com/docs/facebook-login/permissions for the permission reference and https://github.com/thephpleague/oauth2-facebook for more example.

Thanks to CBroe who pointed this out in the comments above, the permissions were supposed to be set in the javascript, not the php. It's because the php code is run when the authorization is complete and you have received all information you were supposed to.
To fix it, I changed
FB.login(function(response){
// take action based on response
});
To
FB.login(function(response){
// take action based on response
}, {scope: 'public_profile, email'});
And it works now. Thanks

Related

how to publish on pages and groups where facebook where I granted php API permission

Friends, I have a problem that is spinning around me. I am learning to use the Facebook API, I have 24 hours with this and I am already understanding how it works, I feel a little sorry because in reality it is easy the problem is that I do not understand much English so it is difficult for me.
The specific question is: How do I automatically publish in the selected groups and pages when I log in with Facebook? For example, of the following groups that I manage, I only select one.
The problem is that when the group is posted, the group id is necessary, using this code snippet.
$response = $this->fb->post('/123456789/feed', $linkData, $accessToken);
So? The specific question, How do I get that list of groups (and also for the pages) to which I granted permission to be able to (it occurs to me), go through an array and do the post automatically.
Right now I am clear about the following points:
1.- I need to create an app: https://developers.facebook.com/
2.- Have the Facebook SDk installed: https://github.com/facebook/php-graph-sdk
3.- My class has saved these permissions and this configuration:
require_once "/../vendor/autoload.php";
class facebookController{
private $appid ='XXXXX';
private $appsecret='XXXXXXXXXXXXXXXXXXXXXXXXXX';
public $fb;
public $helper;
public $permisos = ['email', 'manage_pages', 'publish_pages' , 'publish_to_groups', 'user_posts', 'groups_access_member_info'];
public $callbackurl = 'http://localhost/misitio.com.mx/auth/fb-callback.php';
public $loginurl;
function __construct(){
$this->fb = new Facebook\Facebook([
'app_id' => $this->appid,
'app_secret' => $this->appsecret,
'default_graph_version' => 'v3.2',
]);
$this->helper = $this->fb->getRedirectLoginHelper();
$this->loginurl = $this->helper->getLoginUrl($this->callbackurl, $this->permisos);
}
}
4.- I must obtain the Access Token, it can be debugged here: https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Did%2Cname&version=v3.2
$this->helper = $this->fb->getRedirectLoginHelper();
try {
$accessToken = $this->helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
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;
}
5.- For some cases I need the user_id, I already have it saved:
$oAuth2Client = $this->fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
$userid = $tokenMetadata->getUserId();
6.- To post for example in a group, I use the following and this is where the inconvenience is: (Based on the official documentation: https://developers.facebook.com/docs/graph-api/reference/v3. 2 / user / groups)
public function toPost($titulo, $url){
$empresa = new configuracionController();
$userid=$empresa->getFbUserId();
$accessToken = $empresa->getFBToken();
try {
// Returns a `Facebook\FacebookResponse` object
$this->fb->post('/123456789/feed', $url, $accessToken);
} 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();
}
From already thank you very much.

Is possible to get facebook user access token without user interaction?

I want that my Php script (myscript.php ) that i have deployed on a public host gets the Facebook user access token (with my facebook account) from Facebook. I don't want user interaction with login procedure where to inser user and pass. Is it possibile and how can be made? I understand the SDK is not useful for this scenario.
For now my script is:
require_once ('../php-graph-sdk-5.x/src/Facebook/autoload.php');
$fb = new \Facebook\Facebook([
'app_id' => 'myappid',
'app_secret' => 'mysecret',
'default_graph_version' => 'v2.10',]);
$helper = $fb->getRedirectLoginHelper();
$accessTokenEntity=$helper->getAccessToken();
try {
$accessTokenEntity=$helper->getAccessToken();
$response = $fb->get('/me', $accessTokenEntity->getValue());
}
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;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
Copied from gitub example but i think it s not good for my scenario.
And the output is
"Fatal error: Call to a member function getValue() on null in ..."

Post an image on instagram using Oauth2 - PHP

All I want to post an image on the instagram using Oauth2 & PHP pretty similar like wall post for Facebook and Tweet post for Twitter like:
User click on share on Instagram button from my website, they redirect to the Instagram app approval page, they approve and the image gets posted on their account.
I have searched almost entire internet for this requirement. But I didn't get exact code to achieve this.
I have already checked these:
https://github.com/mgp25/Instagram-API
https://github.com/cosenary/Instagram-PHP-API
Some people says that it is not possible, Instagram doesn't allow that.
So all I want is a clear answer whether is it possible or not? If yes then how?
Thanks
Clear answer
It's not possible and not official in any way. All the Unofficial APIs / packages / libraries... whaterver you might find are barely tentatives of reverse engineering of the traffic generated by the Instagram App.
So they might work for a while, but then Instagram will block them.
Think about it. If there's somewhere an official way to upload stuff to instagram there will be a lot of alternative apps and spammers using it.
If you don't believe me, check the official API documentation. There's no reference to the upload of pictures.
Post istagram image with caption using facebook api(business account - without login)
ref - https://github.com/facebookarchive/php-graph-sdk
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__.'/src/Facebook/');
require_once(__DIR__.'/src/Facebook/autoload.php');
$instaData = [
'image_url' => 'image_url',
'caption' => htmlspecialchars('your message')
];
$pageAccessToken ='your access token';
$fb = new Facebook\Facebook([
'app_id' => 'fb_app_id',
'app_secret' => 'app secrect',
'default_graph_version' => 'v12.0',
]);
try {
$response = $fb->post('INSTA_PAGE_ID/media/?', $instaData, $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();
$creation_id = json_decode($graphNode);
$publish_image = [
'creation_id' => intval($creation_id->id)
];
try {
$response1 = $fb->post('INSTA_PAGE_ID/media_publish/?', $publish_image, $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;
}
echo "<pre>"; print_r($response1); echo "</pre>";
?>

What to place in header to use the Facebook PHP web SDK properly?

I have a website with a working user signup and login system. Recently, I decided that I should add Facebook signup option. I wish to add a Facebook sign in button in the signup page and get their email, first name and last name on sign in so they don't have to insert their details.
I read though most of the Facebook developer help docs including:
https://developers.facebook.com/docs/php/howto/example_facebook_login
https://developers.facebook.com/docs/php/howto/example_retrieve_user_profile
Those links tells me how to let a user to login and how to get user data from their profile.
I understand how all those parts work but I don't know how to put them together. Can anyone please teach me how to do so? Thank you soooo much!
Ok, I finally found how to do it...
So, the first part is to set up files correctly. Here is how you do it:
Download the php sdk kit from fb (here)
Place the files in the "src" folder to your website main directory
The second part is to make the page where you want to link with fb:
Include the fb autoload page in your php page by doing
require_once 'autoload.php'; at the top of the file
Authorize fb to use your app by placing
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
'default_graph_version' => 'v2.6',
]);
right after the code in 1st step
This is basicly how you should start your code to link with fb user profile. The following code is what i used to get a user's name, email and profile image.
<?php
session_start();
require_once 'Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
'default_graph_version' => 'v2.6',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=300');
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// printing $profile array on the screen which holds the basic info about user
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
// replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
$loginUrl = $helper->getLoginUrl('http://xxxxx', $permissions);
echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $loginUrl . '">';}
?>
I wish that this could help anyone who is also stuck like me, bye~

SDK Error The "state" param from the URL and session do not match

I am use this code from Facebook
https://developers.facebook.com/docs/php/gettingstarted/5.0.0
But now its show Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
I cant understand whats wrong
my login callback page code
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxx',
'app_secret' => 'xxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$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']
$_SESSION['facebook_access_token'];
}
Insert this code after: $helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
and it will work or for more detail visit facebook login apps
You are likely not accessing your server using the domain registered to the app. Are you running your webserver on localhost? If so, edit your /etc/hosts file to include something like
127.0.0.1 local.<yourdomain>.com
and then go to local..com and that should take care of it

Categories