Using Facebook Graph API from a mobile application - facebook

I have a small card game at Facebook (and few Russian social networks), which gets user's id, first name and avatar through the old REST API.
Now I'm trying to develop the same game as a mobile app with Flex Hero SDK for Android and iPhone. Which means I can't use native SDKs for those platforms, but have to use OAuth as descibed at Facebook page.
I'm trying to write a short PHP script, which would return the user information as XML to my mobile app. My script can get the token already:
<?php
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'XXX');
$code = #$_GET['code'];
# this is just a link for me, for development puposes
if (!isset($code)) {
$str = 'https://graph.facebook.com/oauth/authorize?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&display=touch';
print "<html><body>$str</body></html>";
exit();
}
$req = 'https://graph.facebook.com/oauth/access_token?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&client_secret=' . FB_AUTH_SECRET .
'&code=' . $code;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
parse_str($page, $data);
#header('Content-Type: text/xml; charset=utf-8');
#print('<?xml version="1.0"? ><app>');
print_r($data);
#print('</app>');
?>
This works well and I get back the token:
Array
(
[access_token] => 262578703638|2.OwBuoa2fT5Zp_yo2hFUadA__.3600.1294904800-587287941|ycUNaHVxa_8mvenB9JB1FH3DcAA
[expires] => 6697
)
But how can I use this token now to find the user's name and avatar and especially I'm confused by how will I get the current user id?
While using REST API I've always known the current user id by calling $userid=$fb->require_login()

See docs at: http://developers.facebook.com/docs/api
Use curl to request: https://graph.facebook.com/me/?access_token=XXXXXXX
The "/me" will get you all of the info you need.
$req = 'https://graph.facebook.com/me/?access_token=' . $access_token;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
$user_object = json_decode($page);
var_dump($user_object);
Will return something like:
object(stdClass)#1 (20) {
["id"]=>
string(10) "1017193642"
["name"]=>
string(19) "Lance Scott Rushing"
["first_name"]=>
string(5) "Lance"
["middle_name"]=>
string(5) "Scott"
["last_name"]=>
string(7) "Rushing"
["link"]=>
string(36) "http://www.facebook.com/LanceRushing"
.....

Since I cannot add comments I'll answer here.
In order to get the profile picture you need to request https://graph.facebook.com/ID/picture. If you want only specific fields you can specify it this way: https://graph.facebook.com/ID?fields=uid,name,etc&access_token=token
Alternatively you can use the PHP SDK to authorise and log in the user so that you don't have to get the token manually - it would simplify your code. For instance, instead of every cURL request you could just do $facebook->api(request); A good description and example are here http://apps.facebook.com/graphapidemo/.

Related

Access token for a simple FQL retrieving the number of status for a page

I'm doing a really simple PHP app using the latest Facebook PHP SDK which aims to display the number of status a page of mine has.
To do so I created an app to have the app id and the app secret but after I'm kinda lost.
I thought I needed an app secret token so I first tried like this:
<?php
public function getFacebookPosts() {
require __DIR__ . '/libs/facebook-sdk/facebook.php';
$appId = 'myID';
$appSecret = 'mySecret';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
));
$token = $this->getFacebookAppToken($appId, $appSecret);
try {
$jinnove = $facebook->api('/my.page');
$fql = '/fql?q=SELECT+status_id+FROM+status+WHERE+uid=' . $jinnove['id'] . '&' . $token;
var_dump($facebook->api($fql));
} catch(FacebookApiException $e) {
var_dump($fql, $e);
}
}
/**
* Function to Get Access Token from Facebook
* #param $appId
* #param $appSecret
* #return string
*/
protected function getFacebookAppToken($appId, $appSecret)
{
$args = array(
'grant_type' => 'client_credentials',
'client_id' => $appId,
'client_secret' => $appSecret
);
$ch = curl_init();
$url = 'https://graph.facebook.com/oauth/access_token';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
return $data;
}
But it returns me an error 102 with the following message: "A user access token is required to request this resource.".
So then I asked on IRC and someone told me I need a user access token to do that.
Of what I've understood a user access token can only be generated when a user explicitly log into facebook to authorize this app and renew the token sometimes.
Is that true? Is there no way to use a token which doesn't imply the user to be logged? Basically anyone can view this number of status, even people who don't have a Facebook account and I want no UI dialog at all.
For some reason, Facebook has decided that querying a status can only be done by a user.
You can get around this by querying the stream table, and only returning posts with type = 46, which are status updates:
SELECT post_id FROM stream WHERE source_id= YOUR_PAGE_ID AND type = 46 LIMIT 100
The stream table has a lot of restrictions on it. Even with a high LIMIT, you may not get all the status updates if the page has been around for a while.
You can also speed up your program by cutting the number of API calls from 3 to 1 with the following changes:
If you want to get a page's ID from its username replace = YOUR_PAGE_ID in the above query with IN (SELECT id FROM profile WHERE username = 'YOUR_PAGE_USERNAME')
You don't need the 'getFacebookAppToken()` function. The PHP SDK will automatically get you an app access token if you don't have an authenticated user.

Facebook Registering Achievement access_token issue

Solution Edit:
Turns out you can't use the PHP SDK to return the correct App Token, nor can you hit the OpenGraph options in the App section of the Developer site, click "Get Code" and grab the app access token from there.. you have to do this:
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id=' . $fbConfig['appId'] . '&client_secret=' . $fbConfig['appSecret'] . '&grant_type=client_credentials';
$accessToken = explode('=',file_get_contents($token_url));
$accessToken = $accessToken[1];
Original issue:
Using the PHP SDK, I've been trying unsuccessfully in registering my achievements. I keep getting the following error:
"This method must be called with an app access_token."
However, when I enter the token I'm using into opengraph (https://graph.facebook.com/app?access_token=ACCESS_TOKEN) I get my app information correctly.
Here are the methods I've tried thus far in registering my achievements:
$param = array(
'access_token' => $accessToken,
'achievement' => 'http://domain.com/path/to/my/achievement/page',
'display_order' => $achievements['achievementWeight']
);
$achievement = $fb->api('/'.$this->CI->config->item('app_id').'/achievements', 'POST', $param);
$superCurl = "curl -F 'achievement=" . $achieveUrl . "&access_token=" . $accessToken . "' https://graph.facebook.com/" . $appId . "/achievements";
exec($superCurl,$result);
$url = 'https://graph.facebook.com/' . $this->CI->config->item('app_id') . '/achievements?access_token=' . $accessToken;
$c = curl_init ($url);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $param);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
if(curl_errno($c)){
$this->CI->firephp->log(curl_error($c));
}
$page = curl_exec ($c);
curl_close ($c);
Everything always comes back saying it needs an access_token.
See the Authenticating as an App document - you must use the app's access token which allows you to act on behalf of the app - a user access token won't suffice for this case (and several others)

CURL communication with Facebook's graph not working

everyone.
I have the following issue:
I'm using curl to get some info from facebook's graph (and this used to work until just a few days ago), but now I just get an empty answer.
The request is quite simple:
https://graph.facebook.com/?ids=XXX&access_token=YYY
The ids parameter is just a list of ids for elements in the graph (in this case, application requests). When I copy/paste the url on a browser, it works, but when using curl it gets stuck without an answer.
The full code for the curl call is:
require 'php/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'YYY',
));
$url = "https://graph.facebook.com?ids=".$_POST['data']."&access_token=".$_POST['access_token'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$results = curl_exec($ch);
curl_close($ch);
echo $results;
Could anyone shed some light on this?
Cheers!
try {} graph.facebook.com/ with trailing slash
$url = "https://graph.facebook.com/?ids=".$_POST['data']."&access_token=".$_POST['access_token'];
also i am unsure where you are trying to retrieve the post from so you could try request method instead.
$url = "https://graph.facebook.com/?ids=".$_REQUEST['data']."&access_token=".$_REQUEST['access_token'];
example ajax call to php:
// get albums
function showAlbums(pageid,limit,offset){
thealbums = "albums";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("albums").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","plugins.albums.php?pageid="+pageid+"&limit="+limit+"&offset="+offset+"",true);
xmlhttp.send();
}
Try for cURL:
function GetCH(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com?ids=".$_POST['data']."&access_token=".$_POST['access_token']");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT_MS,20000);
if(substr($url,0,8)=='https://'){
// The following ensures SSL always works. A little detail:
// SSL does two things at once:
// 1. it encrypts communication
// 2. it ensures the target party is who it claims to be.
// In short, if the following code is allowed, CURL won't check if the
// certificate is known and valid, however, it still encrypts communication.
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}
$sendCH = curl_exec($ch);
curl_close($ch);
return $sendCH;
};
$ThisId = GetCH();
echo $ThisId;

Login on facebook using username and password. Is there any way to do that?

I have a mobile application where I want the user to send to the server his facebook credentials infos and the server will act in behalf of him in facebook (get friends list and so on).
I am researching about it, but I only find information about this oauth2, where the user logs himself in Facebook in a special link, so my app can access his FB information. This doesn't help me because I would like to access this information on the server side, not by the app itself. Is there any way that I can log in using username and password?
I have a WP7 application for facebook chat where I enter my username and password and I connect, so it should be some way to perform it, correct?
edit
Because it is against the TOS, I am thinking about doing the following:
My server sends to my client the URL so the user can login and allow my app to access its informations. After that, my server accesses it.
Would that be possible?
FB is removing the offline_access token.
No solution for this question i guess.
No offline_access, token expires in 60days, No access with username and password(AGAINST TOS)
This is against their tos, but you could use
<?php
/* EDIT EMAIL AND PASSWORD */
$EMAIL = "";
$PASSWORD = "";
function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_NOBODY, $header);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if ($p) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
}
$result = curl_exec($ch);
if ($result) {
return $result;
} else {
return curl_error($ch);
}
curl_close($ch);
}
$a = cURL("https://login.facebook.com/login.php?login_attempt=1",true,null,"email=$EMAIL&pass=$PASSWORD");
preg_match('%Set-Cookie: ([^;]+);%',$a,$b);
$c = cURL("https://login.facebook.com/login.php?login_attempt=1",true,$b[1],"email=$EMAIL&pass=$PASSWORD");
preg_match_all('%Set-Cookie: ([^;]+);%',$c,$d);
for($i=0;$i<count($d[0]);$i++)
$cookie.=$d[1][$i].";";
/*
NOW TO JUST OPEN ANOTHER URL EDIT THE FIRST ARGUMENT OF THE FOLLOWING FUNCTION.
TO SEND SOME DATA EDIT THE LAST ARGUMENT.
*/
echo cURL("http://www.facebook.com/",null,$cookie,null);
?>
http://www.daniweb.com/web-development/php/code/290893
A solution you could use that is TOS friendly would be to have the user sign up on your website and grant the offline_access token using the Facebook SDK. Your mobile app could use that token to make requests on behalf of the user in you mobile app. I would be clear as your requesting the permission with what you intend to with it.

Add a wall post to a page or application wall as page or application with facebook graph API

I wan't to create a new wall post on a appliaction page or a "normal" page with the facebook graph API. Is there a way to "post as page"? With the old REST-API it worked like this:
$facebook->api_client->stream_publish($message, NULL, $links, $targetPageId, $asPageId);
So, if I passed equal IDs for $targetPageId and $asPageId I was able to post a "real" wall post not caused by my own facebook account.
Thanks!
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$args = array(
'access_token' => $page_access_token,
'message' => "I'm posting as a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
To publish as Page you need to add manage_pages permission first of all (and get the tokens).
Next use something like this:
$url = 'https://api.facebook.com/method/stream.publish?message=TEST&target_id=PAGEID&uid=PAGEID&access_token=YOUR_TOKEN';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
Set the value of targetpageid=null and check the output...