Why does "use" not work when included in php? - 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.

Related

Facebook LIKE Button Using Facebook Graph API

I am working on a website in which there are more than three Facebook Page Like Button. Once user click on the button. First, I need to authenticate the user and then like the respective page. However User authentication is working fine now I need to Like a page. I am following the Facebook Like Documentation. But I am getting confused with {object-id} metioned in the documentation. What is this object-id and How do I get this ?
Like Page Code :
session_start();
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;
FacebookSession::setDefaultApplication( 'App_ID','App_Secret' );
$helper = new FacebookRedirectLoginHelper('http://localhost/fb/like.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// Facebook returns an error
} catch( Exception $ex ) {
// validation fails or other local issues
}
if ( isset( $session ) ) {
// Get Basic Userinfo
$getUserInfoObj = new FacebookRequest( $session, 'GET', '/me' );
$getUserInfoProcess = $getUserInfoObj->execute();
$getUserInforesult = $getUserInfoProcess->getGraphObject();
$id = $getUserInforesult->getProperty('id');
// Once Use Logged In Like the respective page
// Like page code
echo '<pre>';print_r($getUserInforesult);exit;
//header("Location: index.php");
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
Object Id is your page, comment, post even photo id that want to make liked.
For example stackoverflow facebook page link is,
https://www.facebook.com/pages/Stack-Overflow/105665906133609?fref=ts
so the object_id is 105665906133609

Facebook connect API : Get user email

I am working on a website in php where i have integrated a Facebook Connect API which enabled the Facebook login button.
My code to get user details looks like this:
<?php
session_start();
// 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\GraphUser;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
$appID = 'app id';
$appSecret = 'app secret code';
FacebookSession::setDefaultApplication( $appID, $appSecret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://localhost/test/facebook_new/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' );
$response = $request->execute();
// get response
$profile = $response->getGraphObject('Facebook\GraphUser');
var_dump($profile);
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
After eecuting this code, var_dump($profile) displays only the User Facebook ID and his Full Name as displayed on the picture below:
What I want to get is the email. The email can be accessed through 'Facebook\GraphUser' but I really dont know what is wrong with my code.
Kindly help me solve this problem
$request = new FacebookRequest($session, 'GET', '/me?fields=name,email');
It is called "Declarative Fields", you have to specify the fields you want to get returned since v2.4 of the Graph API.
Also, make sure the user is authorized with the email permission.
Facebook users in their settings can set their email as private or public. This might be the reason it is not showing up for you.

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.

Facebook SDK V4 Error

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.

Facebook Connect PHP session variable won't set

I am using the Facebook PHP API 4.0 and trying to get the session variable to be set, so I can use the user's Facebook data.
The app, and Facebook approval page have all worked as expected, but the $session variable remains to be unset no matter what I try. I have tried to find the solution from similar questions on Stack with no success. This is the code I am using:
session_start();
//start fb login stuff
require_once( $config['basedir'].'/Facebook/FacebookSession.php' );
require_once( $config['basedir'].'/Facebook/FacebookRedirectLoginHelper.php' );
require_once( $config['basedir'].'/Facebook/FacebookRequest.php' );
require_once( $config['basedir'].'/Facebook/FacebookResponse.php' );
require_once( $config['basedir'].'/Facebook/FacebookSDKException.php' );
require_once( $config['basedir'].'/Facebook/FacebookRequestException.php' );
require_once( $config['basedir'].'/Facebook/FacebookAuthorizationException.php' );
require_once( $config['basedir'].'/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;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($fb_app, $fb_secret);
$helper = new FacebookRedirectLoginHelper( $config['baseurl'] );
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
echo $ex;
} catch(\Exception $ex) {
// When validation fails or other local issues
echo $ex;
}
if ($session) {
echo 'Session var is finally being seen';
}
//end Facebook login stuff
The $session remains unset because you aren't logging the user in. You should modify the last part of the code to something like:
if ( isset( $session ) ) {
echo 'Session var is finally being seen';
} else {
// show login url
echo 'Login';
}
If the $session is not set, your code will ask the user to login. After they login, the $helper->getSessionFromRedirect(); part of your code should execute and set $session. See my tutorial on how to tackle this.
Edit:
If you are logging the user in from a different page, you need to make sure that $helper = new FacebookRedirectLoginHelper( '{your-url}' ); is the same on both pages. If they differ, then you will get a exception from the API related to redirect_uri mismatch.

Categories