Retriving data from facebook events - facebook

I have to create an webpage where i need to show all the events from the past or upcoming ones from an facebook page. I have to retrive the title, description, image, time and place of every single one and make a box with it.
After that, i have to retrive all the interested people.
I'm a beginner trying to make big things! Thank you very much.

This isnt a simple problem - I have just done this so will give you a start.
You need to use Facebooks Graph API to get the data, you will need to read up on the Graph API and how to use it. Documentation can be found here. Its worth noting due to a security breach the API isn't offering all of its services to new developers currently but you can get most - read about this here.
You can query the API using any language but I suggest do it with python and use the requests module. Alternatively you could use this SDK which makes things a lot easier, trust me! With the SDK you need to get a user access token which you can get from here.
SDK
With the SDK its possible to do this
import facebook
graph = facebook.GraphAPI(access_token="your_token", version="2.12")
event = graph.get_object(id='event_id',
fields='attending_count,declined_count')
print(event['attending_count'])
print(event['declined_count'])
You can add more fields to the fields list. However you can use any language you choose to request the data, as you can just construct your own URL's.
Graph API & Requests
This is how I did it in python using requests to query the API.
import requests, json
#Make a requests session to fetch data from URL's
session = requests.Session()
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=10))
#API base URL
baseUrl = 'https://graph.facebook.com/v2.11/'
#Fields you want to get
fields = ['id', 'name', 'start_time', 'end_time', 'description', 'place']
#replace CLIENT_ID and CLIENT_SECRET with ones from a facebook app (make one)
tokenPath= 'oauth/access_token?client_id={0}&client_secret={1}&&'\
'grant_type=client_credentials'.format(CLIENT_ID, CLIENT_SECRET)
#Get the generated token
token = session.get(baseUrl + tokenPath).json()['access_token']
event = session.get(baseUrl, params={
"ids": "event_id",
"fields": ",".join(fields),
"access_token": token,
}
).json()
print(event["name"])
print(event["place"])
You can make a facebook app here which is where the CLIENT_ID & CLIENT_SECRET come from.
Why would you use URL requests and not the SDK?
Using the SDK the generated user access tokens expire every day, its possible to extend them but only for 60 days. If you want to use the SDK it has a method built in which allows you to extend the token, in order to extend the token you also need to create a facebook app. Its also possible to extend tokens using this website, though I cant vouch for its security - it could potentially access and exploit your data.
To extend the token with SDK:
import facebook
graph = facebook.GraphAPI(user_access_short_lived_token)
extended_token = graph.extend_access_token(app_id, app_secret)
print(extended_token)
Using the URL approach, you create a client access token at runtime (read about user access token vs client access token here) and the token is valid so long as your app is active. So if you are going to use this a lot or want to create it and not have to change/extend tokens then use the URL approach.
Hope this gets you started.

Related

Facebook graph api - Unsupported get request

I'm creating a custom module in Drupal, that for part of its functionality must fetch posts from a business page. So for simplicity, I'm using fbapp module as a dependency (drupal.org/project/fbapp), so that I can use it's authentication and request functions (fbapp_app_authenticate() and fbapp_graph_request()) without having to worry about the constant facebook graph updates making my own code obsolete.
I've created a facebook app, so authentication should be app token, using appid and app secret. This seems fine and I'm getting back access_token. However, when I try to read posts from a publicly available page (the clients), I get the response:
"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api"
Here's the queries and responses my code produces:
graph.facebook.com/oauth/access_token?client_id=<redacted>&client_secret=<redacted>&grant_type=client_credentials
array(1) {
["access_token"]=>
string(43) "<redacted>|<redacted>"
}
graph.facebook.com/<page_id>/posts?access_token=<redacted>|<redacted>"
string(183) "{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100}}"
Can anyone verify a correct way to query a Facebook page programmatically, perhaps there's a setting in the page I'm querying that I need to set (although I can't find anything)?
If page restrictions apply, the page's feed can only be retrieved with an user access token as far as I know (because FB needs to evaluate the visibility criteria, and setting your app to the same restrictions doesn't help here):
See
https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed#readperms
It looks like everything you have done is correct. The response you got can be (i am not sure) because you got your clients pageid wrong.

How can I export the feed from a group using Graph API?

I want to export the data of my Facebook group to some sort of file for historical purposes. I understand how to use the API but I don't know what I need to do to work with it. I can make queries in the explorer but it takes way to long for it to execute. I want to know what I need to do to export the data from my group into say a text file. Even just the basic steps in order to use the API would help. Thanks
You'll need to use one of the Facebook SDK's in order to programmatically access the Facebook API. Some popular ones are the JavaScript and PHP SDK's. The docs for each contain how to make API calls, and then you can use your code to handle the response to do whatever you want with them (as long as you stay within Facebook's policies).
An example of an API call in Facebook would be (after loading the SDK and having a valid login):
FB.api('/me', function(response) {
alert(response.name);
});
Let me know if that makes sense, or if you're still unclear how to approach API calls.
You have to get the feeds of the group first using graph api. Here is the code for that.
$groupFeeds = $facebook->api('/GROUP_ID/feed/?access_token='.$accessToken);
Note : $facebook is the object created of facebook class.
You have get the access token. Also you have should have the user_group permissions to extract the feeds of group.

GitHub OAuth in lua

I am working on a library in LUA for an ipad app called Codea. I'm trying to figure out to use OAuth for GitHub Gists. Only part that i can not figure out is how to get an Auth token via code. I used curl in terminal to get myself a token but this seems to be to much work for other users.
I've read through the github api docs multiple times but I cant figure out how to get a Token programmatically. I've tried to duplicate the method I've used to GET and POST gists but it does not seem to work. I'm not sure how to pass the username and password.
I'm creating a table with the needed params then encoding it in json. Everything I try gets a 404 error or 500 error. Thank you all in advance.
local url = "https://api.github.com/authorizations"
local d = {}
d.scopes = {"gist"}
d.note = "AutoGist Codea"
projectAuth = json.encode(d)
opts = { data = projectAuth }
opts.method = "POST"
opts.headers = {Authorization = "basic " .."username:password"}
http.request(url,successCallback,failedCallback,opts)
Scopes are coming, but only in Q4 2013.
See "OAuth changes coming" (October 2013, by Tim Cleam - tclem):
Starting today, we are returning granted scopes as part of the access_token response.
For example, if you are making a POST with the application/json mime-type you’ll see an additional field for the granted scopes.
{
"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a",
"scope":"repo,gist",
"token_type":"bearer"
}
Right now, these scopes will be identical to what you requested, but we are moving towards a feature set that will allow GitHub users to edit their scopes, effectively granting your application less access than you originally requested.
You should be aware of this possibility and adjust your application behavior accordingly.
Some things to watch out for and keep in mind:
Most third party applications using GitHub OAuth to identify users have the best success in adoption by starting out with a request for the minimum access that the application can possibly get away with.
Something like no scopes or just user:email is very sane.
It is important to handle the error cases where a users chooses to grant you less access than you originally requested.
Now that we are surfacing the granted scopes on the access_token response, applications can warn or otherwise communicate with their users that they will see reduced functionality or be unable to perform some actions.
Applications can always send users back through the flow again to get additional permission, but don’t forget that users can always say no.

How to have users 'reconnect' with soundcloud on each page reload?

I'm using the Javascript SDK inside a node.js (Express) App.
Connecting Users works fine, but the connection does not persist between page reloads.
Is this the default behaviour, or is the User supposed to stay connected in new requests?
Do I have to use OAuth token authentication and if so, how can this be done with the JS-SDK?
Inside the "Permission"-Popup, Users are already logged in with soundlcoud, though.
(just have to click the "connect" button each time)
Figured I'd share my answer for those who are unsatisfied with the current answers for automated oauth:
Retrieving access_token:
I had to define get and set cookie functions and then I use the functions to set and retrieve a function holding the access token. I'm not going to give these functions for conciseness but you can easily find them with a google search. I then use this line of code to get the SC access token (once the user has authenticated for the first time)
SC.accessToken()
Setting token:
So this is kind of just an elephant in the room in my opinion that for some reason no one has mentioned. How in the **** do you connect w/ SC using the access token? Do you set it as oauth param? On each call pass it? Well, after experimenting with putting the parameter in every single place I could think, I found out you have to do something like this:
SC.initialize({
client_id: '[removed for security reasons]',
client_secret: '[removed for security reasons]',
redirect_uri: '[removed for security reasons]',
access_token: getCookie("sc_lm2"),
scope: 'non-expiring'
});
//Where "sc_lm2" is the name of my cookie
Hope the helps! Took me a while to figure this out for such a simple thing
EDIT
Using PHP and Wordpress:
$json = wp_remote_get("http://api.soundcloud.com/users/[user_id]/tracks.json?client_id=[client_id]");
$soundcloudData = json_decode($json['body'],true);
(substitue cURL functionality if you're not using Wordpress). #krafty I assume you would just change the endpoint from "/tracks" to "/users" but I can't say I have ever really needed to grab anything but tracks using the Soundcloud API. Hope this helps, though I'm not sure I fully understand what it is that you are trying to accomplish (or rather, how exactly you're going about it) - are you trying to allow user logins? If you want to explain fully what you're trying to accomplish and the steps you're taking I'd be happy to take a crack at it.
Yep, this is the way to do it, officially. :)
For the Next SoundCloud site, we store the token in localStorage (until the user logs out, of course). In each AJAX request to the API from the front end, we put the oauth token in a request header:
jqXHR.setRequestHeader('Authorization', 'OAuth ' + the_oauth_token);

Refresh expired access tokens using serverside flow automatically

Well there seems to be quite a bit of confusion on this topic and I am struggling to get a clear answer, so here is my question...
I am using the serverside flow to obtain access tokens for my web app, I previously used offline_access which is now being depreciated so I need a way to refresh the token in the following situations:
1) User changes FB password
2) Token expires naturally
My app posts results to users FB walls so the refresh needs to be done automatically by our server (no cookies or OAuth dialogs)
I thought I could try to use the new endpoint described here
http://developers.facebook.com/roadmap/offline-access-removal/
, with the following piece of code (Java):
public static String refreshFBAccessToken(String existingAccessToken)
throws Exception{
//Currently not working
String refreshUrl = "https://graph.facebook.com/oauth/access_token?
client_id="+FacebookApp.appId+"
&client_secret="+FacebookApp.appSecret+"
&grant_type=fb_exchange_token
&fb_exchange_token="+existingAccessToken;
URL url = new URL(refreshUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
String result = readURL(uri.toURL());
String[] resultSplited = result.split("&");
return resultSplited[0].split("=")[1];
}
But this doesnt seem to work (I get a response 400), and when I re-read the documentation it seems this endpoint is used for tokens obtained using the client-side flow only...
So what about the serverside flow....?
Can someone tell me if the approach above is correct or there is another way?
Many thanks
From what I understand there is no server side flow for refreshing tokens.
The refresh token call needs to include the response of the user authentication process which is a short lived token.
You will need to include the refresh token process as part of the user login flow or if this doesn't work for your setup you will need to email the user asking them to come back!
I dont know java but syntax is very much like C#, so I can say,you are doing everything right.
But I doubt what does this function readURL do ?
If it works like get_file_contents() of php (i.e. if it does an HTTP get) , I guess thats not a right way to do .
Based on my experience on google's refresh token method, I think you should do an HTTP POST instead of HTTP GET to given url.