Facebook SDK V4 Error - php

I am trying to implement Login with Facebook to my website.
My Code works perfectly fine on Localhost. But when I upload it to server. It gives error like this:
Facebook\FacebookSDKException Object ( [message:protected] => couldn't connect to host [string:Exception:private] => [code:protected]
You can try DEMO: http://dkclan.co/facebook_user_authentication.php
Here is my Code:
<?php
// include required files form Facebook SDK
require 'facebook-php-sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( 'abc','xyz' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://dkclan.co/facebook_user_authentication.php' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
Any idea why I am getting this error?

Most likely your provider blocks outgoing CURL calls (the Facebook SDK uses CURL for calls to the Facebook API).
See this thread with the same error: https://stackoverflow.com/questions/9425406/facebook-api-exception-object-error-on-facebook-app
It makes sense as it works on your local server. The only thing you can do is ask your provider to allow calls to the Facebook API.

Related

Get Facebook User Email Using Graph API PHP SDK

I'm Using a Graph API of Facebook with php i'm trying to get user information to login user to my site but after a lot of searching and reading i'm getting all my required data expect email.
<?php
include_once('../dashboard/includes/db_connection.php');
// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( '1393606834280204','3faf1ede6ccc48d6adf096f1a6850359' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://lhefficise.com/facebook/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,last_name,name,email' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// $fbid = $graphObject->getProperty('id'); // To Get Facebook ID
// $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
// $fbfirstname = $graphObject->getProperty('name'); // To Get Facebook First Name
// $fblastname = $graphObject->getProperty('name'); // To Get Facebook First Name
// $femail = $graphObject->getProperty('email'); // To Get Facebook email ID
$obj = $graphObject->asArray();
echo "<pre>";
print_r($obj);exit;
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
i'm sending request for /me?fields=id,first_name,last_name,name,email but i'm not getting email all other information is fine.
Array
(
[id] => xxxxxxxxxx83xxxx
[first_name] => Shan
[last_name] => Khaliq
[name] => Shan Khaliq
)
I might be doing something wrong while getting the record..
I already have permission for email check the link for that.
http://prntscr.com/9steek
Thanks in advance.
I just figure it out just after i posted this.
$loginUrl = $helper->getLoginUrl(array('scope' => 'email'));
i need to put scop to get login url from facebook.
guys Thanks i really appropriate who were upto this question.

Why does "use" not work when included in php?

I'm updating my apps to work with the new PHP SDK, but I'm having this issue:
I want to do the Facebook stuff in a separate php file to keep things clean.
For example, this is my fb.php page:
<?php
require_once('sdk/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication(...,...);
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
//logged in
} else {
//user is not logged in
?>
<script>window.location="...link to login page...";</script>
<?php
exit;
}
A page which uses the Facebook session, could look like this (testing.php):
<?php
require_once('fb.php');
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
echo "Welcome, ".$graphObject['first_name'];
This returns this error:
Fatal error: Class 'FacebookRequest' not found
The code works fine when I put use Facebook\FacebookRequest; in testing.php , but I don't want to do that, since that was the point of putting all the Facebook session stuff in a separate fb.php file...
What is the reason for this, and is there a solution how to keep all my Facebook stuff in a separate file?
Thanks!
File in which you are including fb.php is in different scope so can't use that imports.
You have to specify them again.
You can read more about that in PHP manual.

Facebook Ads API Cron Job

We are trying to use the facebook ad reporting api to update a 3rd party app to keep up-to-date on our daily spending on facebook. We would like for these values to update automatically via a cron job but this doesn't appear to work. We have to go to the page and refresh it, for it to refresh the api data. Is it possible to get our script to update automatically? Here is our access token code.
I thought it was possible to get a long lived token and save it to the database and use that but we are unable to retrieve the accessToken because its :protected in the return json.
use FacebookAds\Api;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdGroup;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Fields\AdGroupFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSDKException;
use Facebook\Entities\AccessToken;
// Initialize the SDK
FacebookSession::setDefaultApplication( $app_id, $app_secret );
// Create the login helper and replace REDIRECT_URI with your URL
// Use the same domain you set for the apps 'App Domains'
// e.g. $helper = new FacebookRedirectLoginHelper( 'redirect' );
$helper = new FacebookRedirectLoginHelper( $redirect_uri );
// Check if existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// Create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// Validate the access_token to make sure it's still valid
try {
if ( ! $session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// Catch any exceptions
$session = null;
}
} else {
// No session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
echo $ex->message;
}
}
// Check if a session exists
if ( isset( $session ) ) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();
$access_token = $_SESSION['fb_token'];
$long_session = $session->getLongLivedSession();
//print_r($long_session);
$longtoken = $long_session->getToken();
// Create session using saved token or the new one we generated at login
$session = new FacebookSession( $long_session->getToken() );
} else {
// No session
// Get login URL
$loginUrl = $helper->getLoginUrl( $permissions );
//echo 'Log in';
header('Location: '.$loginUrl.'');
}
// Initialize a new Session and instanciate an Api object
Api::init($app_id, $app_secret, $access_token);
// The Api object is now available trough singleton
$api = Api::instance();
// Get the GraphUser object for the cusrrent user:
try {
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
// echo $me->getName();
} catch (FacebookRequestException $e) {
// The Graph API returned an error
} catch (\Exception $e) {
// Some other error occurred
}
I read two questions in your post, the first is that you would like to have a background process (invoked by cron) that reads your daily spending and second that you don't have a long-lived user access token so your script isn't working correctly.
If I understand your goals correctly, it seems that these two issues are a bit conflated which I recommend separating. Follow the Facebook access token documentation for getting a long-lived token and use it directly in your script. Skip PHP session management and just put the long-lived token in a database, simple config file, or directly into the script.
And then if you're not already, have this script invoked by cron or another scheduled background processing system. It can pull your daily spending data and provide it to the 3rd party app.

PHP Facebook SDK Posting to wall with SDK 4

Before you all tell me there is already alot of tutorials on how to do this but their isn't any tutorials I foud on the brand new sdk so I am looking for some help.
I have just finished coding my facebook login but every time I login it doesn't ask for permission? And I was wondering how you ask for permission to post to their wall because I want to post on their wall saying they logged in every time they do
<?php
// include required files form Facebook SDK
require_once( 'fb/Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'fb/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'fb/Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'fb/Facebook/Entities/AccessToken.php' );
require_once( 'fb/Facebook/Entities/SignedRequest.php' );
require_once( 'fb/Facebook/FacebookSession.php' );
require_once( 'fb/Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'fb/Facebook/FacebookRequest.php' );
require_once( 'fb/Facebook/FacebookResponse.php' );
require_once( 'fb/Facebook/FacebookSDKException.php' );
require_once( 'fb/Facebook/FacebookRequestException.php' );
require_once( 'fb/Facebook/FacebookOtherException.php' );
require_once( 'fb/Facebook/FacebookAuthorizationExcetion.php' );
require_once( 'fb/Facebook/GraphObject.php' );
require_once( 'fb/Facebook/GraphSessionInfo.php' );
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( '798029503541633','e31a63ad8d46d3c5f4c9aea15af4b163' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://mywebsite.com/fblogin.php' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}

Class 'FacebookSession' not found - API Facebook 4.0

i'm trying the new Facebook API (4.0) and I have serious problem with this.
The code of my page loginUser.php is:
<?php
require_once("autoload_fb.php");
// init app with app id and secret
FacebookSession::setDefaultApplication( '647345538685342','6ea4dc94874b31a637b6fe368bcfba76' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://www.radiobrunoestate.mumbleserver.it/api/loginUser' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} else {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
echo $ex->message;
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
?>
and the autoload_fb.php is simply:
<?php
session_start();
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
?>
I get this error on first server:
Fatal error: Class 'FacebookSession' not found in /home/jack/provaprova/api/loginUser.php on line 6
Testing the same code on another Server i have this error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/eyikmdnu/public_html/jack/provaprova/api/Facebook/FacebookSession.php on line 140
Where could be the problem? could be a problem of the server configuration?
Thanks
Facebook PHP SDK v4 requires PHP 5.4. You are most likely using an older version of PHP.
I think you have to put the "use" statements also in the top of the "loginUser.php" file.
Suppose you've already made it work, but I think that was the problem.
Maybe this can help someone else.
Your use statements from the include file won't import them for the main file. So you'll need to move the use statements to your main file right after your include of the autoload_fb.php file.
But then you'll have another issue. Your autoloader isn't a real autoloader. Here's more info on that.

Categories