I want to get the user data of facebook.
I´m using a this example :
<?php
session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.4',
]);
$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');
$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
print_r($profile);
// 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('https://sohaibilyas.com/fbapp/', $permissions);
echo 'Log in with Facebook!';
}
In this case, although I am logged in facebook, the first time It always show me "Log in with Facebook!" and it only get the token after redirect. I don´t know it I am doing something wrong, but I would like if the user is logged in Facebook it is not necessary to click in Log in.
Edit, resolves
After writing, I realized that I just needed to do header("location: ".$loginUrl); to avoid click in the link.
Related
I have a problem with the Facebook API, I try to test fairly regularly ids facebook pages liked by the user who uses my API. But soon enough I got this message: (# 4) Application request limit reached. (in php)
Here's how I connect to the API and get pages:
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXX',
'default_graph_version' => 'v3.1',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = []; // 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');
$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
print_r($profile);
$res = $fb->get('/me/likes?limit=1000', $_SESSION['token']);
$res = $res->getGraphEdge()->asArray();
foreach($res as $page) {
$pages[] = $page['id'];
}
} 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://localhost/index.php', $permissions);
echo 'Log in with Facebook!';
}
I'm looking for a way to keep the page consultation but every time after a while, 4/5 times I have the error message.
If not before it works. Do you have an idea to keep the $ fb object without necessarily making the call? In $ _SESSION it's the same thing.
Thanks
I am trying to integrate facebook api in laravel.
I had update my composer.
I am stuck with the error :
Symfony\Component\Debug\Exception\FatalErrorException thrown with
message "Illuminate\View\Engines\PhpEngine::main(): Failed opening
required
'C:\xampp\htdocs\mero-theatre-sm-integration\storage\framework\viewsfb/fb/src/Facebook/autoload.php'
(include_path='C:\xampp\php\PEAR')"
<?php
session_start();
require_once __DIR__ .'fb/fb/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '369611640182768',
'app_secret' => '909...................',
'default_graph_version' => 'v2.12',
]);
$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');
$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
print_r($profile);
// 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('https://sohaibilyas.com/fbapp/', $permissions);
echo 'Log in with Facebook!';
}
I've this simply facebook login integration.
I need to pass to the callback (that in this case is this same page) a custom parameter but the new $helper->getLoginUrl does not allow adding params. Previuosly I see that there was a next parameter that can be used to store a string but now it was removed.
It seems that I can't add a custom param neither in the session.
Is there any method to achieve my purpose?
<?php
require '../facebooksrc/autoload.php';
$userdata='/me?fields=name,first_name,last_name,email,gender,location,birthday';
$permissions = ['email, user_location, publish_actions, user_birthday'];
$fb = new Facebook\Facebook([
'app_id' => $appid,
'app_secret' => $appsecret,
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
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($userdata);
$profile = $profile_request->getGraphNode()->asArray();
} 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;
}
$firstname=$profile["first_name"];
$lastname=$profile["last_name"];
// MY INSERT QUERY
} else {
$url="myurl";
$loginUrl = $helper->getLoginUrl($url, $permissions);
//REDIRECT
header("Location: $loginUrl");
}
I'm using the code below on my website to try and post a message on a Facebook page that I manage. I'm using the Facebook PHP SDK v5. Whenever I run the code I get directed to Facebook with an error window that says,
"URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs."
However, if I go to the Graph API Explorer and request a User Access Token, then hard code the access token into the script it works just fine. I added Facebook Login to the products tab on my app setting, since that's the only place you can add in the "Valid OAuth redirect URIs". I'm pretty sure the problem is coming from the "Valid OAuth redirect URIs" field in the setting area. I'm not sure what to put in that field or if that is even the problem at all. Currently, I've tried putting the following in the "Valid OAuth redirect URIs" field with no luck;
just my domain i.e. www.my-domain.com
the full path the the calling script i.e. www.my-domain.com/calling-script.php
the full path to a blank page on my server i.e. www.my-domain.com/blank.html
None are working. This is my first go at trying to use the Facebook PHP SDK so I'm sure I'm doing it all wrong... Wondering if anyone is able to give me some guidance on this?
UPDATE:
See answer posted below with fix. My original post was not very clear regarding my intentions. My goal was to successfully post a message to a Facebook Page as the Page, not as an individual user. Hope this helps someone down the road.
Here are my app settings:
Here is the PHP script I am using:
session_start();
$path = "path-to-Facebook-autoloader-on-my-server";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-from-app-settings',
'app_secret' => 'app-secret-number-from-app-settings',
'default_graph_version' => 'v2.7',
]);
/////////////////////////////////////////////////////////////////////////
// If I uncomment the below line the script works fine, but the token expires often
// and I do not want to have to keep updating it
// $_SESSION['facebook_access_token'] = "access-token-obtained-from-Graph-API-Explorer";
/////////////////////////////////////////////////////////////////////////
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // 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{
$_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;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try{
$request = $fb->get('/me');
}catch(Facebook\Exceptions\FacebookResponseException $e){
// When Graph returns an error
if($e->getCode() == 190){
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
}catch(Facebook\Exceptions\FacebookSDKException $e){
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
try{
// message must come from the user-end
$data = ['message' => 'test message...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphNode();
}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 $response['id'];
}else{
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
i checked your script. all looks fine except one thing. can u try after changing
$helper = $fb->getCanvasHelper();
to
$helper = $fb->getRedirectLoginHelper();
and see what error it throws if any?
also u can refer to the shared gist. do let us know your error.
https://gist.github.com/gunnrryy/c2c828fc2a77124cc1bed57af5e216df
So I ended up figuring it out. I played around with the script I originally posted and finally got it to work...sort of. No matter how I ran the script messages were always being sent to the page I manage as a notification. They would not show up on the wall. The end goal I was looking for was to post on to a page that I manage as the page, not as myself. Just in case anyone else comes across this the code below works perfect. Also, it does not require you to submit privileges for approval with Facebook.
The answer to my original question in regards to the "Valid OAuth redirect URIs" field. I ended up putting the path to the calling script in that field and it worked fine.
session_start();
$path = "server-path-to-Facebook-autoloader.php";
$permissions = ['manage_pages', 'publish_pages'];
$callback = "full-path-to-the-calling-script(this-script).php";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-number-here',
'app_secret' => 'app-secret-here',
'default_graph_version' => 'v2.7',
]);
$helper = $fb->getRedirectLoginHelper();
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
$res['myresponse'] = 'Error: Graph returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
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']);
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach ($pages as $key) {
if ($key['name'] == 'name-of-page-to-post-to') {
$post = $fb->post('/' . $key['id'] . '/feed', array('message' => 'this is an automated test message from Affordable HomeCare...'), $key['access_token']);
$post = $post->getGraphNode()->asArray();
if($post['id'] <> ''){
$res['myresponse'] = "Successfully Posted to Facebook";
}else{
$res['myresponse'] = "Error: Unable to verify post ID";
}
echo $res['myresponse'];
}
}
} else {
$loginUrl = $helper->getLoginUrl($callback, $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
I am having a problem with the Facebook SDK,
I am always getting the same error:
Error:
Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
PHP Script:
<?php
if(!session_id()) {
session_start();
}require_once __DIR__ . '/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxxxxxxxxxxx',
'app_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
'default_graph_version' => 'v2.5',
]);
$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');
$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
print_r($profile);
// 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://localhost/myquizlife/', $permissions);
echo 'Log in with Facebook!';
}