Graph API v1.0 from Facebook-PHP-SDK v4 - facebook-graph-api

I have Facebook-PHP-SDK v4 and Facebook-JavaScript-SDK. User authenticates via JS and I work with his access token via PHP.
I'd like to call Graph API v1.0, but when I try to specify version in FacebookRequest I get the same error as I did calling APIv2. I tried to specify version in JS block but it did not help with my problem, I still get:
The global ID is not allowed. Please use the
application specific ID instead
How can I fix it? I know that API v1.0 will be unavailable soon but now I'm looking for a temporary and fast solution.
Here is Javascript Init Request:
FB.init({
appId : document.getElementById("facebook_appid").value,
cookie : true, // enable cookies to allow the server use the cookies
xfbml : true, // parse social plugins on this page
version : 'v1.0' // use version 1.0
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response); //show login status
});
And this is PHP block with the request:
/**
* Use long-live access token
**/
FacebookSession::setDefaultApplication($appid, $secret);
if (empty($extended_user_access_token)) {
$session = new FacebookSession($user_access_token);
$session = $session->getLongLivedSession();
$extended_user_access_token = $session->getToken();
} else {
$session = new FacebookSession($extended_user_access_token);
}
/**
* Validate facebook session
**/
try {
$session->validate();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
/**
* Call user by global id
**/
if ($session) {
try {
$request = new FacebookRequest(
$session,
'GET',
'/<my-global-id>',
null,
'v1.0'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
} catch (Exception $ex) {
echo "Exception code: " . $ex->getCode();
echo ", with message: " . $ex->getMessage();
}
}

It does not matter if you add the v1.0 tag to your call, if the App was created after end of April 2014 it will not be able to use v1.0 and you will only be able to use App Scoped IDs.
That is why the global ID does not work, use FB.login to authorize the User and use the gained (App Scoped) ID for the call.

Related

Facebook Graph API SDK v5 - Publishing a picture to a page's Album

I'm trying to publish a picture to an album belonging to a Facebook page, using the Facebook PHP SDK v5.
I've already checked the (many) similar questions, however they are all related to prior versions of the SDK, when publish_actions was still allowed.
My Setup:
My app is properly configured and I was able to retrieve my access token
I was able to run a few test API queries with no issues
I'm the admin of this page and my access token has the following permissions ['manage_pages','publish_pages','user_photos']
The SDK was properly initialized with 'fileUpload' => true as a parameter
Code publishing the picture to the album
It is based on the example provided in the SDK documentation.
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$access_token = 'mytoken';
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
Here's the error I'm getting
Graph returned an error: (#200) This endpoint is deprecated since the
required permission publish_actions is deprecated
Indeed, changes introduced in April 2018 removed the ability to use publish_actions however it seems the documentation has not been updated accordingly.
What is the new way to publish a picture to a page's album?
Your help is much appreciated!
After several hours of researching alternate solutions, I was able to find a workaround.
Apparently I was using an User Access Token instead of the Page Access Token.
Solution
1 - First, verify if your token is a User/Page Access token
2 - If it is an User Token, you need to request the Page Access Token instead:
$user_access_token = 123456;
$page_id = 123456; // Can be retrieved via right click on your page logo + Copy link address
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
$page_access_token = json_decode($response->getBody())->access_token;
echo $page_access_token;
3 - Finally, post the picture on the Page using the Page Access Token
Full code
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$user_access_token = 'mytoken';
$page_id = 123456;
try {
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$page_access_token = json_decode($response->getBody())->access_token;
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $page_access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
I hope this helps!

The fb access token always get expired in ember app

I am using ember-simple-auth and ember-cli-facebook-js-sdk.I am using the ember-cli-facebook-sdk because I want to get the user photo anytime as facebook only give the access which expires in 60 mins.So I can't save also.Ember-cli-facebook-sdk is working fine.But sometimes I am getting an error in my network console.
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}
I am not able to think why this error is coming.I have a initializer which have facebook id and api version.And Now I am using Fb.api and others in my controller,component and other.But it fails sometimes.Please anwser where I am going wrong.Thanks in advance.
initializer/fb.js
import FB from 'ember-cli-facebook-js-sdk/fb';
export default {
name: 'fb',
initialize: function() {
return FB.init({
appId: '1234567',
version: 'v2.3',
xfbml: true
});
}
};
controller.js
usrphoto:Ember.computed('model',function(){
var currentState = this;
FB.api('/me/picture','Get',{'type':'large'}).then(function(response) {
currentState.set('usrphoto', response.data.url)
})
}
I think what happens here is, that your Facebook session expires. In that case you need to handle the error and manage it. For example, you could check for a valid session and in case the session is expired, require a new token and then do your request:
FB.getLoginStatus().then(function(response) {
if (response.status === 'connected') {
return Ember.RSVP.resolve();
} else {
return FB.login('email,user_photos'); //set your scope as needed here
}
}).then(function() {
return FB.api('/me/picture','Get',{'type':'large'});
}).then(function(response) {
currentState.set('usrphoto', response.data.url);
});
Another possibility is to handle the error in the catch of the FB.api:
FB.api('/me/picture','Get',{'type':'large'}).then(function(response) {
currentStatte.set('userphoto', response.data.url);
}).catch(function(reason) {
...handle your error here...
});

Facebook PHP / JS Sdk This authorization code has been used error

I am using Facebook php an js sdk.
I am login to facebook with js sdk. Login works perfectly.
and I have php part.
private $helper, $api_id, $app_secret, $session;
....
FacebookSession::setDefaultApplication($this->api_id, $this->app_secret);
$this->helper = new FacebookJavaScriptLoginHelper();
try {
$this->session = $this->helper->getSession();
} catch (FacebookRequestException $ex) {
log_message('error', 'Facebook e1 :' . $ex->getCode());
log_message('error', 'Facebook e1 :' . $ex->getMessage());
} catch (\Exception $ex) {
log_message('error', 'Facebook e2 :' . $ex->getCode());
log_message('error', 'Facebook e2 :' . $ex->getMessage());
}
if ($this->session) {
$request = (new FacebookRequest($this->session, 'GET', '/me'))->execute();
$user = $request->getGraphObject()->asArray();
return $user;
} else {
return false;
}
when page loads normally, I get user data without a problem.
But for example, if I press several times f5, to refresh page, I get and error that "This authorization code has been used." or "This authorization code has expired." and user data is empty.
Idea is to login with js, and to use php part to validate is user logged in into facebook or not.
I am using latest facebook php sdk : https://github.com/facebook/facebook-php-sdk-v4
Thank you.
There are several ways how to fix this.
1) You have to update the access token in the cookie every call, FB does not do this automatically. So, be sure you call the FB.init with status: true param.
FB.init({
appId : window.fbId,
cookie : true,
status : true,
version : 'v2.3'
});
Next, every page refresh you have to call FB.getLoginStatus(); no matter if you are connected to Facebook already.
This does not work if your application needs to do some ajax calls - simply because the access token is not updated when you do ajax (unless you call FB.getLoginStatus(); before every ajax call - and that's overkill).
2) Better may be to store the access token in session once user connect via FB JS SDK. The PHP code might look like this:
try {
$fbToken = isset($_SESSION['fbToken']) ? $_SESSION['fbToken'] : NULL;
if ($fbToken !== NULL) {
$session = new \Facebook\FacebookSession($fbToken);
} else {
$helper = new FacebookJavaScriptLoginHelper();
$session = $helper->getSession();
}
} catch(\Facebook\FacebookRequestException $ex) {
log_message('error', 'Facebook e1 :' . $ex->getCode());
log_message('error', 'Facebook e1 :' . $ex->getMessage());
} catch(\Exception $ex) {
log_message('error', 'Facebook e2 :' . $ex->getCode());
log_message('error', 'Facebook e2 :' . $ex->getMessage());
}
if ($session) {
$accessToken = $session->getAccessToken();
$longLivedAccessToken = $accessToken->extend();
$_SESSION['fbToken'] = $longLivedAccessToken;
$request = (new FacebookRequest($session, 'GET', '/me'))->execute();
$user = $request->getGraphObject()->asArray();
return $user;
} else {
return FALSE;
}
}
Hope I did help...
Cheers.
Delete your Browser history,Cookies it's cause you tested your before then session have some bad values

Facebook Graph API class not found

I'm using the facebook graph api to get event information from a page.
I installed the Facebook SDK with composer but when I try to use a class in my controller it gives an error : Class 'Facebook\FacebookSession' not found.
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
class HomeController extends BaseController {
public function index()
{
FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
$session = FacebookSession::newAppSession();
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/1531904510362357/'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
dd($graphObject);
}
Make sure you are using the Composer autoloader correctly.
You can see the instructions here https://getcomposer.org/doc/00-intro.md
Then make sure you are reporting on all errors. I would wrap my query in a try/catch block so you can catch any facebook exception as follows:
try {
$query = (new FacebookRequest(
$this->facebook, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className())
return $query;
} catch (FacebookRequestException $e) {
// The Graph API returned an error
return $e;
} catch (\Exception $e) {
// Some other error occurred
return $e;
}
Make sure to include the request exception class and graph user class too as follows:
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

facebook javascript permission dialog for email

i have a question.... i am actually developing a facebook application with FB javascript SDK. In my application I need email permission for further processing. i am using
FB.Connect.showPermissionDialog("email");
but some how the dialog doesn't appears... here is my code
<script>
appid = '*************';
name = 'Palmchip Test App';
href = 'https://apps.facebook.com/*********/';
FB.init({
appId:appid, cookie:true,
status:true, xfbml:true
});
FB.getLoginStatus(function(response) {
if (response.session) {
alert("You are logged in...");
FB.Connect.showPermissionDialog("email", function(perms) {
if (!perms) {
alert("no access");
} else {
alert("accessed...");
}
});
}
else {
top.location.href='https://graph.facebook.com/oauth/authorize?client_id='+appid+'&redirect_uri='+href+'&display=page';
}
});
</script>
the alert which says you are logged in... works fine but then nothing happens .....
You need to upgrade to OAuth 2.0 ouath: true
You should use the new OAuth Dialog
You should be aware when upgrading that FB.getLoginStatus() will return different objects: response.authResponse
Try this code block
FB.init({appId: <?= APP_ID ?>, status: true, cookie: true, xfbml: true, oauth:true});
function getin(){
FB.login(function(response) {
if (response.authResponse) {
var regurl = "/login";
location.href=regurl;
} else {
var regurl = "/logout";
window.location.href=regurl;
}
}, {scope:'email'});
}
So when you call the getin() function , if the current user already gave you the email address it'll do nothing for him just will redirect him to /login url , but if the user is a new user then he/she will see a pop-up box asking for the email address once he/she allows that you can pull the email address using graph or fql. BTW response inside FB.login has the user id , access_toke and some more useful data so save that for further use.