Question about the upgrade to v2.2 of the Facebook Platform, in particular, this part:
The previously deprecated REST API has been completely removed in
v2.1, and all apps still using it must migrate to using Graph API.
For the most part, in my Android and iOS app I am not using the REST API. I'm using the Android SDK and the iOS SDK. However, I do have one exception. When I call my server to login or really do basically anything, I try to assure that the person trying to login/access data is indeed the person they say they are. I do this:
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$response = file_get_contents("https://graph.facebook.com/debug_token?input_token=".$accessToken."&access_token=MY_APP_ACCESS_TOKEN", false, $context);
$jsonObject = json_decode($response, true);
$data = $jsonObject["data"];
$facebookId = $this->getFacebookId();
if(isset($data['is_valid']) && $data['is_valid'] === true) {
if(isset($data['user_id'])) {
if($data['user_id'] == $facebookId) {
return true;
A little bit of code missing there, but that's the gist of it. Get an access token and a facebook id. I use the access token to see if it's legitamite and the user_id assigned to that access token is the id of the person trying to get info. If so, I let them in.
My question is, am I understanding correctly that this is going away and I have to use the Graph API to somehow do the same thing? How is this done through the Graph API in PHP given an access token and facebook id from Android/iOS?
EDIT: Just realized this is actually in the 2.0 to 2.1 section, but question still stands, should I be concerned about my server side code?
Thanks!
I'm thinking I don't have anything to worry about. The approach I'm using is in the Facebook Platform docs here:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#checktoken
Under inspecting access tokens. Nothing on this page talks about it being deprecated.
Related
im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/
I have an android client, that initiate log-in to facebook, receives access token and other details about the profile.
The android client passes the access_token and details to the Server (PHP).
Both have facebook sdk installed.
When I initiate a FacebookRequest from the PHP, for example '/me/' It's working.
BUT when I initiate a (friends who have installed the APP) FacebookRequest from the PHP
'/me/friends'. I get "null".
When I use the graph explorer provided by facebook the result is :
{
"data": [
]
}
Additional information for the helpers:
The app contains only two users at the moment, which are friends on facebook.
Those users are both administrators of the app.
Currently the app is not live\published.
We haven't "Start a Submission" in Stats and Reviews as suggested somewhere.
We asked for the permission 'user_friends'.
Since everything in stack overflow requires reputation,
This is how the permissions look like:
http://i.stack.imgur.com/kURwB.png
Thanks
EDIT:
OK I added two test users, Made them friends of each other, and /me/friends through graph explorer is working for them.
BUT why doesn't it work for non-test-users?
Okay,
So apparently Facebook had a problem providing new Access Tokens.
Don't know why, but it provided the same access token, for new Log-Ins.
Now that they fixed that here is a Handy function that I wrote in PHP that will let users
Parse Facebook responses, this might come in hand since there is NOTHING explained over the Docs, Google, StackOverFlow.
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
function find_my_facebook_friends($access_token){
require_once 'facebook-php-sdk-v4-4.0-dev/autoload.php';
FacebookSession::setDefaultApplication('app_key','secret_key');
$session = new FacebookSession($access_token);
$request = new FacebookRequest(
$session,
'GET',
'/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
return $graphObject;
}
Usage:
include_once 'path/to/function.php';
//You wanna use it, just so the PHP file contains your app_key, secret_key Wont be exposed.
$access_token = isset($_POST['access_token']) ? $_POST['access_token'] : NULL;
$facebook_object = find_my_facebook_friends($access_token);
for($i = 0 ; $i < count($facebook_object['data']) ; $i++){
$id = get_object_vars($facebook_object['data'][$i]);
echo $id['id'];
echo $id['name'];
//You don't have to echo, you could handle those fields as you wanted.
}
This function refers to a Mobile Client passing his Log In User's access token to the server.
I hope this will save you lots of time!
As a total stranger to facebook and its uses, I ask you the following question about login a user:
When using the latest php SDK (as of today, php-sdk-3.2.3), I read the SDK documentation (https://developers.facebook.com/docs/reference/php/) and can login a user and get information from them according to the permissions requested.
Still, there's this other document, about manually building a login flow:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
There's a few points there about "Confirming identity" and exchanging tokens I thought were worth toying with. When I try to combine the SDK methods with these other aspects, the second one to execute always fails (something about "this authorization code has been used", that I can understand as a part of the Oauth specs). I am going crazy exchanging and renewing tokens but maybe that's not neccesary...
... Here's the question: does the php SDK part do these kind of confirmations for you?. Is it secure enough?. In that case, this - almost too familiar, quick and dirty - code is just what I need to get the user info, right?
$facebook = new Facebook(array( [something something]));
if($facebook->getUser())
{
try
{
$user_profile = $facebook->api('/me','GET');
}
catch(FacebookApiException $e)
{
echo 'login.';
}
}
else
{
echo 'login.';
}
Yes, the SDK does all this for you - the manually building a login flow documentation is intended for people who are not using an SDK (for example where no SDK exists for the language they are using).
I checked the PHP SDK source, just to be sure - getUser() calls getUserFromAvailableData() which, if you're not an app inside Facebook (with a signed request) it calls getAccessToken() which calls getUserAccessToken() which in turn calls getAccessTokenFromCode() which does the exchange of a code for an accessToken. If it has a signed request (is an app on Facebook) then the access token is provided in the POST data and a code does not need to be exchanged. Phew!
I've been implementing an OAuth login via the Google Identity toolkit in php. I've got as far as getting an authenticated session, the userdata, id, photo etc, which seems to be working more or less ok.
However, I'd like to be able to login using methods that don't rely on redirection on the user's browser (thinking of remote APIs for an application), but bit lost on how to achieve this.
Imagine a request which is something like:
$details = new stdClass();
$details->secret = $config->secret;
$details->client_id = $config->client_id;
$details->app_name = 'my awesome oauth app';
$details->login = array();
$details->login['email'] = 'some google account email # example.com';
$details->login['password'] = '1234';
$token = $this->do_auth($details);
if($token) {
// do stuff, setup cookies, insert token in session table etc
}
I'm using CodeIgniter. Are there any libraries that can do this..? I've seen android apps doing similar things, using custom login forms, so I'm guessing it's achievable in php.
You HAVE to redirect, it's a core essential of the way OAuth works, there is no way around this. That's why there is a redirect_uri parameter.
You only have to do this once though: when the user is logging in and you are requesting an access token. After that, you simply use curl for example to request your data.
I'm trying to use the Google API v3 to access one google calendar and according to the documentation here : http://code.google.com/apis/calendar/v3/using.html#intro and here : https://code.google.com/apis/console/, the solution I need is the "Simple API Access" & "Key for server apps (with IP locking)".
Now, when I create a page with this code :
session_start();
require_once 'fnc/google-api-php-client/src/apiClient.php';
require_once 'fnc/google-api-php-client/src/contrib/apiCalendarService.php';
$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);
if (isset($_SESSION['oauth_access_token'])) {$apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $apiClient->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
and in my "config.php" file I add ONLY my developper key (in place of the "X") :
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
But then I get errors and it tells me it's trying to authenticate using the "OAuth 2.0" system which I don't want to use. I only want to access one calendar with an API key.
And amazingly, when I search in google "Simple API Access key" I find nothing, nothing on their docs, no examples, no tutorials, nothing. Am I the only one using this thing?
So can someone tell me what I'm doing wrong?
(i know this is an old question but i would've been glad if someone
gave a real answer here so i'm doing it now)
I came on the same problem, Simple API access is not well documented (or maybe just not where i searched), but using the Google API Explorer i found a way to get what i need, which is in fact pretty straightforward. You don't need specific lib or anything : it's actually really simple.
In my case i simply needed to search a keyword on G+, so i just had to do a GET request:
https://www.googleapis.com/plus/v1/activities?query={KEYWORD}&key={YOUR_API_KEY}
Now, for a calendar access (see here), let's pretend we want to fetch access control rules list. We need to refer to calendar.acl.list which give us the URI :
https://www.googleapis.com/calendar/v3/calendars/{CALENDAR_ID}/acl?key={YOUR_API_KEY}
Fill in the blanks, and that's pretty much all you need to do. Get a server key (API Access submenu), store it somewhere in your project and call it within URIs you're requesting.
You cannot access your calendar information using API Key. API keys (or simple API acess key) are not authorized tokens and can only be used for some API calls such as a Google search query etc; API keys will not let you access any user specific data, which I am assuming is your objective through this calendar application.
Also, from what I see in your code, you are creating a client object which is going to use OAuth 2.0 authentication and hence you are getting authentication error messages.
There is no such a thing called Simple API Access key.
Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.
If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.
I got to this thread when trying to do the same today. Although this is way late, but the answer is YES, there is actually simple API key for those apis that does not need user authorizations, and the official client library support this.
The api library do this by Options, which is key, value pair.
Take the example of get information of a given youtube video, you would use this api: https://godoc.org/google.golang.org/api/youtube/v3#VideosListCall.Do
To use api key, simply make a type that implements the CallOption interface, and let it return the api key:
type APIKey struct {
}
func (k *APIKey) Get() (string, string) {
return "key", "YOU API KEY HERE"
}
Then when calling the API, supply the APIKey to it:
youtube, err := youtube.New(&http.Client{})
call := youtube.Videos.List("snippet,contentDetails,statistics").Id(id)
rsp, err := call.Do(opt)
This way, you can construct the youtube client with the vallina http client, rather than oauth client, and enjoy the simple api key.
The first answer said you can use http GET directly, but then you will need to handle the errors and parse the result yourself.
See below link which is helpfull to you. The Google API Client Library enables you to work with Google APIs such as Analytics, Adsense, Google+, Calendar, Moderator, Tasks, or Latitude on your server, in the language of your choice.
http://code.google.com/p/google-api-php-client/
Thanks,
Chintu