Facebook Graph API no error - php

I am experimenting with the Facebook Graph API and have this
require 'sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
FacebookSession::setDefaultApplication('<MY APP ID IS HERE>', '<MY APP SECRET IS HERE>');
$helper = new FacebookRedirectLoginHelper('http://whispershare.co.za/dashboard');
$loginUrl = $helper->getLoginUrl();
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
echo $ex;
} catch(\Exception $ex) {
echo $ex;
}
if ($session) {
echo 'yay';
} else echo 'boo';
I set the App ID and App secret but I keep getting the 'echo "boo";' on my page.
My app seems to be set up correctly. If it wasn't then it would give me an error in the try, right?
What could be wrong?

Please check my fb login whats is the error?
Here is the link.
It's say -
Graph returned an error: Can not open the link: Link domain is not included in the list of gadget domains.

Related

Facebook Ad API PHP : Invalid OAuth access token

I am working on the Facebook Ads API and I am totally new for this. I am getting an error to fetch the Ads account. The error is Invalid OAuth access token. After getting this error I came to google and searched a lot like
First Link Another one another one. But didn't find any solution so I decided to come to Stackoverflow so this question is not duplicate
Here is the code how I used the Facebook Ads API
public function login() {
$helper = $this->facebook->getRedirectLoginHelper();
$this->request->session()->write('fb_access_token', false);
$access_token = $this->request->session()->read('fb_access_token');
if ($access_token) {
echo "You are logged in!";
} else {
$permissions = ['email', 'ads_management', 'pages_show_list', 'publish_pages', 'manage_pages', 'ads_read'];
$loginUrl = $helper->getLoginUrl('http://localhost/FacebookManager/Adsmanagement/authenticate', $permissions);
echo 'Log in with Facebook';
}
}
public function authenticate() {
if (isset($_GET['state'])) {
$helper = $this->facebook->getRedirectLoginHelper();
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
$accessToken = $helper->getAccessToken();
if($accessToken) {
echo "got the token";
$this->request->session()->write('fb_access_token', $accessToken);
//echo $accessToken;
$oAuth2Client = $this->facebook->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$this->facebook->setDefaultAccessToken($longLivedAccessToken);
}
}
}
And I am getting the adaccount like this
public function getAdsAccount() {
$accesstoken = $this->request->session()->read('fb_access_token');
//$accesstoken = "AQwfmuNgKZCZCiZBuhAMGB8xZBty5dgNR7J9ZBO2ZCDl1SWYxnBLn9ahIn5FQTWxkJ0FPKbemeG0vUAwPsZCN2FFxOFey9BQr8CZBW07IwlZB0FK81SH8ozOil2GllR35BCyxQGhQ7JrtuCdNE6kjEOU0FZCAZDZD";
Api::init(
$this->app_id, // App ID
$this->appsecret,
$accesstoken // Your user access token
);
//*****************
$account = new AdAccount('****************');
$contracts = $account->read();
echo "<pre>"; print_r($contracts->getData());
}
So I am using a developer account, Trying to fetch this with the facebook test user from the APP dashboard-> Roles->Test User. I am setting the proper permissions etc. Don't know where I am wrong.
Update
Now the issue is if I create access token from Graph Explorar It works but if i create with SDK its giving me the error "invalid aouth Tokan"
Please help me. Thanks in advance.
Hello #manoj Kumar Please check with below URL with administrator login for app debug your AccessToken.
https://developers.facebook.com/tools/explorer/
Please check below code from facebook PHP SDK for getting the valid access token with permission ads_management.
require_once __DIR__ . '/vendor/autoload.php';
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => '{your-app-id}',
'app_secret' => '{your-app-secret}',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['facebook_access_token'])) {
$_SESSION['facebook_access_token'] = null;
}
if (!$_SESSION['facebook_access_token']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['facebook_access_token']) {
echo "You are logged in!";
} else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
echo 'Log in with Facebook';
}
After that, You have to get AdAccount so use below code
use FacebookAds\Object\AdUser;
// Add after Api::init()
$me = new AdUser('me');
$my_adaccount = $me->getAdAccounts()->current();
It was actually my mistake. Facebook API return us an protect object. If you print the variable it will display it as string.
<?php
echo $longLivedAccessToken;
var_dump($longLivedAccessToken);
?>
The output is something like
I tried $longLivedAccessToken->getValue();
$oAuth2Client = $this->facebook->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$accesstoken = $longLivedAccessToken->getValue();
$this->request->session()->write('fb_access_token', $accesstoken);
$this->facebook->setDefaultAccessToken($longLivedAccessToken);

PHP SDK 4.0 on Google App Engine: cURL error

I'm making a PHP application running on Google App Engine, and I'm trying to implement a Facebook Login.
After accessing to the login webpage, I am redirected to Facebook, and after I accept to log in for the application and I get redirected, I get the error "Error : Option 10065 is not supported by this curl implementation."
I have curl_lite enabled, and I'm running it on localhost for the time being. Here's my code:
<?php
session_start(); //Session should be active
#region Settings
$app_id = 'xxxxxxx'; //Facebook App ID
$app_secret = 'yyyyyyy'; //Facebook App Secret
$required_scope = 'public_profile'; //Permissions required
$redirect_url = 'http://localhost:8080/signup_fb.php'; //FB redirects to this page with a code
#endregion
#region Imports
//include autoload.php from SDK folder, just point to the file like this:
require_once "../libraries/facebook-php-sdk-v4-4.0-dev/autoload.php";
//import required class to the current scope
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\GraphUser;
use Facebook\FacebookRedirectLoginHelper;
#endregion
FacebookSession::setDefaultApplication($app_id , $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
//try to get current user session
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
die(" Error : " . $ex->getMessage());
} catch(\Exception $ex) {
die(" Error : " . $ex->getMessage());
}
if ($session){ //if we have the FB session
$user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
//do stuff below, save user info to database etc.
echo $user_profile->getProperty('name');
}else{
//display login url
$login_url = $helper->getLoginUrl( array( 'scope' => $required_scope ) );
echo 'Login with Facebook';
}
Thank you for your answers :)
It's understandable that with curl_lite enabled (curl interface backed by urlfetch and with fewer features) you would see such an issue. Check the docs as another commenter mentioned, and you should definitely be using the real curl if you intend to run such specific advanced functionality with your box's devserver as the client to facebook's login flow.

cannot get Facebook Session for login (FB PHP SDK 4.0.0)

after various tries, i decided to write here my problem with FB PHP login with SDK 4.0.0.
The problem is that I cannot retrieve the session, and I don't know why.
My code (placed in a file named "social.php") is the follow:
session_start();
define('fbsdk', "/fbsdk/src/Facebook/");
require __DIR__ . '/fbsdk/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\GraphUser;
if(isset($_GET['login'])){
if($_GET['login'] == "fb"){
$appid = "677652872357474";
$appsecret = "******";
FacebookSession::setDefaultApplication($appid, $appsecret);
$helper = new FacebookRedirectLoginHelper('http://localhost/ffideasbox/');
try{
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex){
print_r($ex);
} catch(Exception $ex){
print_r($ex);
}
if(isset($session)){
echo "Session defined: ".$session;
} else {
echo "Session not defined";
}
} elseif($_GET['login'] == "tw"){
} elseif($_GET['login'] == "gp"){
} else {
...
}
} else {
....
}
?>
If I go to the documentation page of Session (https://developers.facebook.com/docs/php/FacebookSession/4.0.0), it says me that I can get session by:
// If you already have a valid access token:
$session = new FacebookSession('access-token');
// If you're making app-level requests:
$session = FacebookSession::newAppSession();
Eventually, which is the access token? And how can I get it?
Then, after have posted here, I added before the session TRY block, this other one:
$session = FacebookSession::newAppSession();
try{
$session->validate();
} catch(FacebookRequestException $ex){
echo $ex->getMessage();
} catch(\Exception $ex){
echo $ex->getMessage();
}
But I still get the same message: "Session not defined" (wrote by me in the session IF block).
Could someone tell me more about the FBSDK? I read the documentation but I don't understand much.
Thank you all.
EDIT: I add also the "map" of the sdk folder
-mainfolder
|-fbsdk
|-autoload.php
|-src
|-Facebook
|-All the complete facebook sdk
After have looked for examples and more, I looked that I didn't had added the piece
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
in the isset($session) else. This because I didn't understand why it was needed and when the session is not defined, I didn't redirect anywhere.
if(isset($session)){
echo "Session defined: ".$session;
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}

facebook SDK 4.0 infinite redirect loop in php

I've a problem with facebook sdk 4.0
After I clear session/cookies it works fine. But sometimes, and I cannot determine when, if I go to the app, it starts an endless redirect loop!
I've put all my code on git, since documentation doesn't provide exact ansswers:
https://github.com/sandrodz/facebook-canvas-app-sample-sdk-4.0/blob/master/index.php
<?php
// Working canvas APP, FB SDK 4.0
session_start();
// Load SDK Assets
// Minimum required
require_once 'Facebook/FacebookSession.php';
require_once 'Facebook/FacebookRequest.php';
require_once 'Facebook/FacebookResponse.php';
require_once 'Facebook/FacebookSDKException.php';
require_once 'Facebook/FacebookCanvasLoginHelper.php';
require_once 'Facebook/GraphObject.php';
require_once 'Facebook/GraphUser.php';
require_once 'Facebook/GraphSessionInfo.php';
require_once 'Facebook/HttpClients/FacebookHttpable.php';
require_once 'Facebook/HttpClients/FacebookCurl.php';
require_once 'Facebook/HttpClients/FacebookCurlHttpClient.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Faceboob\FacebookSDKException;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
// Facebook APP keys
FacebookSession::setDefaultApplication('XXX','XXXXX');
// Helper for fb canvas authentication
$helper = new FacebookCanvasLoginHelper();
// see if $_SESSION exists
if (isset($_SESSION) && isset($_SESSION['fb_token']))
{
// create new fb session from saved fb_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the fb_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
{
// create fb session
$session = $helper->getSession();
}
catch(FacebookRequestException $ex)
{
// When Facebook returns an error
print_r($ex);
}
catch(\Exception $ex)
{
// When validation fails or other local issues
print_r($ex);
}
}
// check if 1 of the 2 methods above set $session
if (isset($session))
{
// Lets save fb_token for later authentication through saved $_SESSION
$_SESSION['fb_token'] = $session->getToken();
// Logged in
$fb_me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject();
// We can get some info about the user
$fb_location_name = $fb_me->getProperty('location')->getProperty('name');
$fb_email = $fb_me->getProperty('email');
$fb_uuid = $fb_me->getProperty('id');
}
else
{
// We use javascript because of facebook bug https://developers.facebook.com/bugs/722275367815777
// Fix from here: http://stackoverflow.com/a/23685616/796443
// IF bug is fixed this line won't be needed, as app will ask for permissions onload without JS redirect.
$oauthJS = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id=1488670511365707&redirect_uri=https://apps.facebook.com/usaidgeorgia/&scope=user_location,email';";
}
?>
I went ahead to debug line by line, and these are my findings:
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token']))
{
echo '$_SESSION and $_SESSION["fb_token"] are set';
// 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;
echo 'access_token is not valid';
}
echo 'access_token is valid';
}
catch (Exception $e)
{
// catch any exceptions
$session = null;
echo 'something error happened ' . $e;
}
}
I get error:
$_SESSION and $_SESSION["fb_token"] are setsomething error happened exception 'Facebook\FacebookSDKException' with message 'Session has expired, or is not valid for this app.' in /home2/nakaidze/public_html/mesamoqalaqo_app/Facebook/FacebookSession.php:247 Stack trace: #0 /home2/nakaidze/public_html/mesamoqalaqo_app/Facebook/FacebookSession.php(221): Facebook\FacebookSession::validateSessionInfo(Object(Facebook\GraphSessionInfo), '148867051136570...') #1 /home2/nakaidze/public_html/mesamoqalaqo_app/user-functions.php(56): Facebook\FacebookSession->validate() #2 /home2/nakaidze/public_html/mesamoqalaqo_app/index.php(2): require('/home2/nakaidze...') #3 {main}
The access token you're using in $_SESSION['fb_token'] has expired. By default the access token returned by Facebook lasts for 2 hours and then it expires.
After you get the FacebookSession for the first time, you need to extend the access token it returned and save it in your $_SESSION['fb_token']:
$session = $helper->getSession();
$accessToken = $helper->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
$_SESSION['fb_token'] = (string) $longLivedAccessToken;
Also, when you validate the access token with validate(), it will throw if it's not valid:
// validate the access_token to make sure it's still valid
try
{
$session->validate();
echo 'access_token is valid';
}
catch (FacebookSDKException $e)
{
$session = null;
echo 'Access token is no longer valid, need to get a new token';
}
This might help clarify info about Facebook access tokens.

FBML Canvas Application Authentication

I'm modifying an FBML canvas app to use the new PHP SDK and authentication instead of the old REST api.
Right now I'm attempting to use this snippet:
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
} else {
$loginUrl = $facebook->getLoginUrl(array('req_perms' => 'user_birthday, publish_stream, email'));
header('Location: '.$loginUrl);
}
However if I use the php header function for any URL that isn't relative, I get this error:
Application Temporarily Unavailable
The URL [https://www.facebook.com/login.php?.........] is not valid.
Sorry, the application you were using is experiencing a problem. Please try again later.
If I need to have authentication on my FBML canvas app using the latest PHP SDK, how do I properly redirect to the app login page that requests the extended permissions?
Looks like you cannot use a server side redirect (header()) to push user to the auth page. I'm using this at the moment:
function redirect($url)
{
echo '<script>top.location="' . $url . '";</script>';
//echo '<fb:redirect url="' . $url . '"></fb:redirect>';
//header("location:$url");
exit();
}

Categories