Using Facebook Javascript SDK to get Graph Data - javascript

FIXED NOW! But I can't answer my own question yet. See my comment below. And thanks for helping.
I've searched and searched and read the docs and still can't figure this out.
I have a web page about an event. There's also a public Facebook "event" for my event. I'm trying to use the FB Javascript SDK to get the number of attendees for the Facebook event and add it to the number of people who've registered through the website.
I've created an app and I have an appID and secret string. I can get an access token from:
https://graph.facebook.com/oauth/access_token?client_id=XXXX&client_secret=XXXXX&grant_type=client_credentials
and I can then use that access token to get the attendees for a public event:
https://graph.facebook.com/331218348435/attending?access_token=XXXXXXXXX
That's all fine.
I'm now trying to do this same thing using the Javascript SDK.
I've loaded the SDK and done an init:
FB.init({
appId : 'XXXXXXXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
and I know the SDK is working because I can get an object with the data that doesn't need an access token:
FB.api( '/331218348435', function (response) { console.log ( response ) } );
but when I try to get the attendee data that needs the access token:
FB.api( '/331218348435/attending', function (response) { console.log ( response ) } );
I get an OAuthException: "An access token is required to request this resource."
All the tutorials and information I can find all refers to using the .login method, but I don't want a user to login, I want to login using my app ID without any user interaction.
I'd assumed that the API took the SDK's init request and granted me an access token when I called the .init method, the authentication being done against my website's address (the HTTP referrer - yes I have set my website URL in the Facebook app settings).
Any ideas what might be causing this to not work? How can I get the access token using the Javascript SDK without doing a .login? Am I missing a step? Is this even possible?
Thanks

Form what the rather circular documentations says, getting the attending feed requires a 'generic access_token`. In Facebook terms:
Any valid access_token
Any valid access token returned by our APIs. An access token may not be valid if, for example, it has expired. No special permissions are required. Occasionally, this is referred to as a generic access_token.
So this means that you can use any token you like to access the attending feed, as long as the event is public. The easiest access token to get seems to be an app token: http://developers.facebook.com/docs/authentication/#applogin. You can get this token using only your App ID and Secret, and no user interaction is required.
To summerise the link content: You can get an application access token by sending a GET request to
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
You can then use that access_token to make the call for you attending list
FB.api('MyEvent/attending?access_token=ACCESS_TOKEN');

Oh. OK.
Well, for whatever reason, I went away and had my dinner and when I come back it's working fine.
When I updated the settings for my app Facebook said it might take a few minutes for the change to get around the servers. Turned out to take over an hour!
My code was fine.
Thanks for your help.

Related

Making server to server request to Google Calendar API

I am building a SPA using vue.js which has a PHP backend server (slim framework 3). These are two separate projects, leave on two different servers and the backend has no front end at all.
SPA (vue.js) makes requests to backend via ajax.
Now I want to implement Google Calendar API to create a calendar and events every time user creates a todo item. To do that I need server to server access to Google Calendar API (I might need to make changes to the event on GCAL even if user is not logged in).
What I am trying to understand, how can I get the access token (and refresh token) using Google JS library using vue.js and save this in the db so that my backend can use it to make offline requests to GCAL Api.
When I use the Oauth v.2 using the JS library, all I get is the access_token which cannot be using for server to server communications.
[UPDATE]
Ok, a little bit more information. I am following the guides from Google and my front end looks like this at the moment
jsbin
So I can successfully authorise user and access their calendar using the javascript sdk. But the token Javascript SDK returns is something like this
{
_aa: "1"
access_token: "xxxxxxx"
client_id: "yyyyyyyyyy"
cookie_policy: undefined
expires_at: "1456400189"
expires_in: "3600"
g_user_cookie_policy: undefined
issued_at: "1456396589"
response_type: "token"
scope: "https://www.googleapis.com/auth/calendar"
state: ""
status: Object
google_logged_in: false
method: "AUTO"
signed_in: true
token_type: "Bearer"
}
I send this token to my backend server and try to make a request to GCAL api as follows
$token = $request->getParam('token');
$client = new Google_Client();
$client->setApplicationName('Web');
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setAuthConfigFile(ROOT_DIR . '/client_secret.json');
$client->setAccessType('offline');
$client->setAccessToken(json_encode($token));
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
And it returns error saying the token is expired. I checked the Google Code and found out the reason it returns this error is because of these lines
public function isAccessTokenExpired()
{
if (!$this->token || !isset($this->token['created'])) {
return true;
}
// If the token is set to expire in the next 30 seconds.
$expired = ($this->token['created']
+ ($this->token['expires_in'] - 30)) < time();
return $expired;
}
As you can see the token that comes from the front end doesn't have created field as well as no refresh_token field.
Thanks for updating the question! I am thinking the issue is that using the client-side flow does not allow you to get a refresh token. From the docs:
OAuth 2.0 client-side flow (AKA Implicit flow) is used to obtain
access tokens (it does not support the issuance of refresh tokens) and
is optimized for public clients known to operate a particular
redirection URI. These clients are typically implemented in a browser
using a scripting language such as JavaScript.
The authorization server MUST NOT issue a refresh token.
see for more: How to get refresh token while using Google API JS Client
You'd need to use the server-auth flow to get a token you can refresh and use long-term. Here's a quickstart guide for PHP.
One other thing to consider is that you will only receive a refresh_token the first time someone authorizes your app. After that, auth attempts will only return an access token. So if you lose the refresh token, you will need to either disable the authorization from your google account, or use the "force re-auth" option in the API.

Google access_token is undefined

I am developing a mobile web application which will access the Google Books API and allow the user to add books to their "favorites" book shelf. Its my first time using an API that requires the Google authorization.
I need to send an authorized request to modify private user data. I (think) I have have the proper access_token but I can't figure out how to get to it.
I am using the Google sign in button like so:
` <div class="g-signin2" data-onsuccess="onSignIn"></div> `
I also have this to identify my application to Google:
`<meta name="google-signin-client_id" content="12345.apps.googleusercontent.com"> `
I sign in with my own Google account and the Google button changes over to "Signed In." I am simply trying to log the access token from there:
` function onSignIn(googleUser) {
googly = gapi.auth2.getAuthInstance();
var id_token = googly.currentUser.get().getAuthResponse().access_token;
console.log(id_token);
} `
I've tried everything I can find in the documentation but no matter what I do, I get back that access_token is undefined.
My suspicion is that I don't actually have an access token, but I don't know how to test that.
What is the correct way to find the access_token? Once I have it, how do I send it to the API?
It's so late but if you pass true parameter to getAuthResponse "getAuthResponse(true)" it returns access_token.
Try using gapi.auth in the API Client Library instead of gapi.auth2 in the Identify Platform. You should find gapi.auth.getToken().access_token contains the access token you need.
That said, I believe this is a bug. If you alert(JSON.stringify(googleUser)) I suspect you'll find there is an access_token field buried in there, but getAuthResponse() doesn't contain it, even though the docs suggest there should be one.
If anyone can confirm I'm understanding this correctly and report it, that would be great.
If you include the response_type in the request header as 'token' it will return the access_token with the currentUser

Get an access token without being connected to facebook

I need to retrieve a facebook page's list of posts (feed) using their javascript SDK, just like they explain in their docs: https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed
/* make the API call */
FB.api(
"/{page-id}/posts",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
I need it to be my website's "news section", so users should see it even if they are not connected to facebook.
The problem
Cool, but there is a problem... It returns: An access token is required to request this resource.
Holy cow... I'd like to get some access token for you #facebook, but my app doesn't make use of your authentication tools/plugins.
ANYWAY, I tried with FB.getLoginStatus(); but doesn't work, because the only way it can return an access_token is if the user is actually connected to the application. My users may not even be logged to facebook!
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
I've already payed a look to this SO question, but it doesn't solves my problem, simply because there are no such "generic tokens".
I've also read https://developers.facebook.com/docs/facebook-login/access-tokens/ and that also relies on tokens generated through facebook login methods... So, can't I display a list of fb page's posts in my website, without being connected into facebook, hence an application?
ADD: My app is build with angularJS, I'm not dealing with server-side code. I shall rely purely on javascript methods.
You could either use an page or an app access token, but as you'd be using them on the client-side, neither of them are an option.
See
https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
Note that because this request uses your app secret, it must never be made in client-side code or in an app binary that could be decompiled. It is important that your app secret is never shared with anyone. Therefore, this API call should only be made using server-side code.
I'd strongly recommend to build a simple server-side script (PHP for example) to proxy the request to the Graph API. You could then call this via AJAX for example and load the posts asynchronously (and alse get rid of the FB JS SDK!). There is NO way to handle this in a secure manner if you don't want to use FB Login for all of your users (which also doesn't make much sense IMHO).
I think it's straightforward :)
Since pages' posts are always public, it only needs a valid access token to retrieve page posts.
Quoting what you've written:
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
You only require an access token.
My suggestion would be;
- Generate an access token for yourself (no extra permission needed)
- request page-id/posts
This way you don't require other users to be connected to facebook, you can simply requests page-id/posts to retrieve posts with access token you generated for yourself.
I hope it solves your problem :D
TIP: As long as posts are public, you only require a valid access token, it doesn't need to be user or page specific.

Facebook API - access token works for SOME requests

This is driving me totally crazy. I've set up an FB app and retrieved an access token by visiting: https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET.
Now I want to grab a (publicly available) feed from this URL: https://graph.facebook.com/PAGE_OR_USER_ID/feed?access_token=ACCESS_TOKEN
It works fine when I try it with my own user ID or even when I try another random page but it DOESN'T work when I enter the PAGE_ID I need it to work with.
Here are some examples:
This works fine (a friend of mine's Facebook page):
https://graph.facebook.com/tatchit/feed?access_token=213451182120494|JgAwuCE74lh51t1pKMuRM2mz3GU&limit=10&offset=0
This also works fine (my own Facebook ID):
https://graph.facebook.com/al.dev.7/feed?access_token=213451182120494|JgAwuCE74lh51t1pKMuRM2mz3GU&limit=10&offset=0
This doesn't work (the client's Facebook page):
https://graph.facebook.com/142616539131188/feed?access_token=213451182120494|JgAwuCE74lh51t1pKMuRM2mz3GU&limit=10&offset=0
I don't get any errors but the result is empty.
If I try the Graph API Explorer it also works fine:
https://developers.facebook.com/tools/explorer/?method=GET&path=142616539131188%2Ffeed
But not if I enter my own access token. From what I understand the access tokens you get in the API Explorer are temporary so I don't want to use that.
How can this be?
Also. I've struggled to understand this whole access-token, client-id, app-id-business for ages now - is there a good tutorial where all this stuff is explained? I've never had this work without problems ever.
Thank you
You should be using user access token for all the above queries. App Access token is used when you want to do something like check the app insights so and so.
When the pages has age restrictions or something so, app token wont be able to get through, but since the user is already a member of the page, you can use the user access token to get the data.
Add : Quoting from the documentation,
Note that the **app access token** is for publishing purposes permitted by the publish_actions and publish_stream permissions. You will be **unable to retrieve information** about the status update post with the given ID using the app access token. Instead, you should use a **user access token** for such purposes.
Other Capabilities of an App Access Token
There is a limited set of information that can be retrieved from Facebook using an App Access Token.
Basic Profile Info of a User (ID, Name, Username, Gender)
A User’s Friends and their IDs
Permissions granted by the User to your App
Read : https://developers.facebook.com/docs/opengraph/using-app-tokens/
So you should be querying with the user_access token to access all the informations that you are looking for, not with an app access_token.
You are using an App Access token instead of a User Access token. Some of the pages you are viewing may have a country or age restriction set, so using an app token will not work.
See: http://developers.facebook.com/docs/concepts/login/access-tokens-and-types/

Facebook Page has a fan or not

Im trying to use javascript to determine if a user is a fan of a page that i've created on my account.
I found the facebook graph api which looks like just what i want. However it appears for some functionality i need an access token.
Here it says I can just http get my /user_id/accounts page with the manage_pages permission and it will list the access token for each page.
But when i submit https://graph.facebook.com/myuserid/accounts&scope=manage_pages i get "OAuthException : Access token is required to request this resource."
I also tried from this answer, but then i get "An error occurred, please try later".
Any suggestions most welcome.
You will need an access token to retrieve any information that is not public on facebook.
You can read up on this page about authenticating a user. Once your user is authenticated you can retrieve the access token and use it in your future requests (for that user)..
eg:
https://graph.facebook.com/{YOUR_USER_ID}/accounts&access_token={YOUR_ACCESS_TOKEN}

Categories