Facebook Graph API getAccessToken() not working - facebook

I have been working on the Graph API for the past few days. When I try to make an API call using the PHP-SDK, i get an empty json object as a response. But when i copy the access token from the links that are provided by FB in http://developers.facebook.com/docs/reference/api/, i get a json response.
I assume that this is because of the Access Token that i am sending in the request.
Help Appreciated.
My Code :
include_once "fbInit.php";
$access = $facebook->getAccessToken();
$user = $facebook->getUser();
echo $access;
if(!$user)
{
$loginUrl = $facebook->getLoginUrl();
header("Location:".$loginUrl);
}
$userWall = $facebook->api('/me/feed',array('access_token'=>$access)) ;
var_dump($userWall);

getAccessToken() only returns the internally stored access token in the SDK, it doesn't generate or fetch one. One advantage of using the SDK is that you don't need to pass in the access token directly like you're doing toward the end of your example. Once the user clicks the link generated by getLoginUrl(), the access token will automatically be stored in the SDK and the api method will work. Posting to a user's wall requires more parameters than you're passing in, however. You can see a complete example of how to do this in the recently-released PHP SDK docs at https://developers.intern.facebook.com/docs/reference/php/facebook-api/

This works for me:
index.php
<?php
require_once("./config.php");
$me = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
$userWall = $facebook->api('/me/feed',array('access_token'=>$access_token));
var_dump($userWall);
?>
config.php
<?php
require_once("facebook.php");
$app_id = "app_id";
$app_secret = "app_secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
if(is_null($facebook->getUser()))
{
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos'))}");
exit;
}
?>

The api suppose to fetch the access token for you - it form a access_token graph api at base_facebook.php line 664. Unfortunately this api call maybe failed due to your redirect uri - some had mentioned that you should not have a "?" in your redirect uri and in my case - there is a tail "/", which caused this call failed. And same redirect uri had no problem if you direct call through "https://graph.facebook.com/oauth/access_token?".
Try to put a log to print out the response result from facebook in _graph() function within base_facebook.php will help you quickly determine whether you are hit by same problem as me.

Related

Facebook Login error - Can't Load URL

I know this has been ask3d before but I have tried several of the posts but still cannot get it to work. I am being forced to use strict mode for url redirects and no matter what I put for the domain nothing works.
<?php
if(!session_id()){
session_start();
}
// Include the autoloader provided in the SDK
require_once __DIR__ . '/src/Facebook/autoload.php';
// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
/*
* Configuration and setup Facebook SDK
*/
$appId = '********'; //Facebook App ID
$appSecret = '***************'; //Facebook App Secret
$redirectURL = 'https://www.themathouse.com/'; //Callback URL
$fbPermissions = array('email'); //Optional permissions
$fb = new Facebook(array(
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.2',
));
// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();
// Try to get access token
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$accessToken = $helper->getAccessToken();
}
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
?>
On the facebook app I have themathouse.com as the app domain and https://www.themathouse.com as the Valid OAuth redirect URIs.
When I try logging in with facebook I get the following error:
Graph returned an error: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
Any help would be greatly appreciated.
Make sure that your Redirect Url matches what is set in your App Settings, under Facebook Login -> Settings -> Valid OAuth redirect URIs
In this case, it seems to be https://www.themathouse.com/
EDIT: Also, as it seems that you are using the PHP SDK, make sure that you are using the currently latest version, 5.6.2, as this one fixed an issue present on 5.6.1 and older that may affect you.
THIS worked for me!! (after fiddling with a bunch of stuff suggested on various forums, to no avail)
I updated the 'FacebookRedirectLoginHelper.php' file:
https://github.com/facebook/php-graph-sdk/blob/5.x/src/Facebook/Helpers/FacebookRedirectLoginHelper.php and voila! Pesky login error fixed :)
(Oh, I also updated code for other recently changed files [within last few months or so] in the Facebook PHP/SDK, so you should also do this as well: https://github.com/facebook/php-graph-sdk). Good luck!
Update with the latest SDK, it will solve your problem.

Facebook API - Retrieve my own albums and photos

I'm trying to retrieve my albums and photos from facebook using the Facebook api for php. I've created an app now i have my AppId and my AppSecretId. I don't need any login window because I want to display my own photos, not the ones from any other user, but everytime I try to retrieve them, I receive this message "An active access token must be used to query information about the current user."
I know that if I were going to show the photos from another users, then I should ask for their login and then generate the access token, but this is not the case.
I have tried generating an App token and tried to use this as an access token but it's not working either.
This is the code I'm using:
require_once("facebook/facebook.php");
try{
$facebook = new Facebook(array(
'appId' => '<APPID>',
'secret' => '<SECRETID>',
'cookie' => true
));
echo($facebook->getUser());
if(is_null($facebook->getUser()))
{
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos'))}");
exit;
}
$me = $facebook->api('/me');
$albums = $facebook->api('/me/albums', array('access_token' => $facebook->getAccessToken()));
echo($albums);
}catch(Exception $e){
echo "THIS IS THE ERROR: " . $e->getMessage();
die;
}
I hope you can help me with this. Thank you so much!!
The easiest way to generate a Facebook access token for your personal account is to visit their Graph API Explorer. It will automatically generate an access token that you can copy/paste into your code.
https://developers.facebook.com/tools/explorer
Additionally, you can use the 'Get Access Token' button on that page to request an access token with specific permissions.

Any way to get signed_request via FB PHP SDK outside of tab/app?

I've been working on a way to determine if a user likes a particular page so a tab on that page can be fangated or not. I didn't want to prompt the user for authorization for user_likes, so I avoided the JS SDK and used the PHP SDK:
<?php
require 'src/facebook.php';
$app_id = "...";
$app_secret = "...";
$facebook = new Facebook(array('appId' => $app_id, 'secret' => $app_secret, 'cookie' => true));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
/* testing response */
if ($like_status) {
/* liked content */
} else {
/* not liked content */
}
?>
My problem is signed_request is passed only when the code is on the FB tab--if I hit the PHP page outside of FB, I get nothing. I wondered if there's a way to get this user info outside of Facebook.com.
You can try saving the signed_request in a session or cookie so you can use it until it expires. After which, the user will have to come through the tab again to renew it. Naturally, if you are planning to use cookies, you should keep the signed_request decoded so no one can find and use the access_token from the cookie.
Sounds like this isn't really feasible outside of the Facebook tab. We've begun deploying our tabs in PHP in order to pull this data without an action on the user's part.
Thanks!

Upload to specific Fan Page Album without user perms

I'm trying to replicate the same functionality as someone else has already achieved on this page here:
http://www.facebook.com/PowerPhotoUploader?sk=app_152884604799537
am not bothered about the forced like fangate part, can do that no probs.
I need to achieve this without requesting any user perms the same way they have
I've got close, but not quite right yet.
Have created a test album on this page: http://www.facebook.com/pages/Demo-Album-Upload/227979503931257?sk=app_153866511376478
The code I have is uploading my specified image, however it is ignoring the album id I input and instead, uploading to an album on my own profile.
Code so far is:
<?php
$app_id = "XXXXXXXXXXX";
$app_secret = "XXXXXXXXXXXX";
require 'facebook.php';
$facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true, 'fileUpload' => true,));
$signed_request = $facebook->getSignedRequest();
//print_r ($signed_request);
$page_id = $signed_request["page"]["id"];
//Upload To Page Album
$facebook->setFileUploadSupport(true);
$album_id ='59125';
$file_path ='image2.gif';
$args = array('message' => 'Photo Caption');
$args['image'] = '#' . realpath($file_path);
$data = $facebook->api('/'.$album_id.'/photos', 'post', $args);
print_r($data);
?>
Have already read through a lot of forum material, have set the filuploadsupport, set file upload to true, but most of the info I can find so far reuires perms & access token, however sample above has managed to achieve with neither - any thoughts?
Regards Tony
Tony the trick here is that you only need one access token, not a new one for each user. The idea is that the user is not posting to the page, you are posting to the page, so you do not need an access token from the user. However since this is a secure call to Facebook you still need to provide an access token that has the ability to publish to the page.
The simplest route to get an access token that you can use would be to manually give the application the manage_pages and offline_access permissions for your account. Then just grab the access token for for your account and use it for all calls.

Facebook API to retrieve wall feed

I've never done any facebook development and am working on a project which I only require to pull out wall stream from a certain user. Is there such an API I could use for this purpose?
Facebook exposes a generic API. You can write your own methods of accessing it, or you can use Facebook's libraries (if your preferred language is available). Check out the following link to get started:
Getting started
Well, if you're happy with JSON, just using the graph API is a good start.
e.g. https://graph.facebook.com/starbucks/feed
Not too hard to pull that down with Python and put the data in a table...
Though this is an old post, still i am putting in my reply. This might be helpful.
I am using php sdk and here is code for getting the users wall posts (includes posts by other users as well)
$facebook = new Facebook(array(
'appId' => '101874630007036',
'secret' => '2090c8d645ae93e7cacee2217cd3dc0c',
));
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
}
else
{
$params = array('scope' => 'read_stream');
$loginUrl = $facebook->getLoginUrl($params);
}
if ($user)
{
$comments = $facebook->api('/me/home');
}
here $comments contains the wall post json data.