How to get Facebook page feed and Filter its fields as Json using Google App script - facebook-graph-api

I am trying to get a Facebook page feed through Google app script.
As of now I tried different scripts but I am getting only app token with the request and if i change it with a usertoken from graph api I got messages but no images and titles
How to get the user token and get the correct fields for as a json ,
var url = 'https://graph.facebook.com'
+ '/love.to.traavel/feed'
+ '?access_token='+ encodeURIComponent(getToken());
// + '?access_token=' + service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
Logger.log(jsondata); //check this and adjust following for loop and ht
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;

You should use a Page Token, not a User Token
You need to ask for fields you want to get, with the fields parameter: https://graph.facebook.com/love.to.traavel/feed?fields=field1,field2,...&access_token=xxx
You get a user token by authorizing your App: https://developers.facebook.com/docs/facebook-login/platforms
Be aware that extended user tokens are valid for 60 days only, so you have to refresh it once in a while. There is no user token that is valid forever. You cannot authorize through code only, it needs user interaction. The easiest way is to just generate a user token by selecting your App in the API Explorer and authorize it, like you did already. Then hardcode it in the script code.
Alternatively, you can try implementing this with the manual login flow, check out the docs for that. You can try adding the functionality using this for a custom interface where you go through the login process: https://developers.google.com/apps-script/guides/html/
Since you donĀ“t own the page, you should read this too: https://developers.facebook.com/docs/apps/review/feature/#reference-PAGES_ACCESS

Related

Identity Server 3 Facebook Login Get Email

Identity server is implemented and working well. Google login is working and is returning several claims including email.
Facebook login is working, and my app is live and requests email permissions when a new user logs in.
The problem is that I can't get the email back from the oauth endpoint and I can't seem to find the access_token to manually request user information. All I have is a "code" returned from the facebook login endpoint.
Here's the IdentityServer setup.
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"]
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then of course I've customized the AuthenticateLocalAsync method, but the claims I'm receiving only include name. No email claim.
Digging through the source code for identity server, I realized that there are some claims things happening to transform facebook claims, so I extended that class to debug into it and see if it was stripping out any claims, which it's not.
I also watched the http calls with fiddler, and I only see the following (apologies as code formatting doesn't work very good on urls. I tried to format the querystring params one their own lines but it didn't take)
(facebook.com)
/dialog/oauth
?response_type=code
&client_id=xxx
&redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&scope=email
&state=xxx
(facebook.com)
/login.php
?skip_api_login=1
&api_key=xxx
&signed_next=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx&cancel_url=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3Dxxx%23_%3D_
&display=page
&locale=en_US
&logger_id=xxx
(facebook.com)
POST /cookie/consent/?pv=1&dpr=1 HTTP/1.1
(facebook.com)
/login.php
?login_attempt=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx
&lwv=100
(facebook.com)
/v2.7/dialog/oauth
?redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&state=xxx
&scope=email
&response_type=code
&client_id=xxx
&ret=login
&logger_id=xxx
&hash=xxx
(identity server)
/id/signin-facebook
?code=xxx
&state=xxx
I saw the code parameter on that last call and thought that maybe I could use the code there to get the access_token from the facebook API https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
However when I tried that I get a message from the API telling me the code has already been used.
I also tried to change the UserInformationEndpoint to the FacebookAuthenticationOptions to force it to ask for the email by appending ?fields=email to the end of the default endpoint location, but that causes identity server to spit out the error "There was an error logging into the external provider. The error message is: access_denied".
I might be able to fix this all if I can change the middleware to send the request with response_type=id_token but I can't figure out how to do that or how to extract that access token when it gets returned in the first place to be able to use the Facebook C# sdk.
So I guess any help or direction at all would be awesome. I've spent countless hours researching and trying to solve the problem. All I need to do is get the email address of the logged-in user via IdentityServer3. Doesn't sound so hard and yet I'm stuck.
I finally figured this out. The answer has something to do with Mitra's comments although neither of those answers quite seemed to fit the bill, so I'm putting another one here. First, you need to request the access_token, not code (authorization code) from Facebook's Authentication endpoint. To do that, set it up like this
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"],
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
return Task.FromResult(0);
}
}
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then, you need to catch the response once it's logged in. I'm using the following file from the IdentityServer3 Samples Repository, which overrides (read, provides functionality) for the methods necessary to log a user in from external sites. From this response, I'm using the C# Facebook SDK with the newly returned access_token claim in the ExternalAuthenticationContext to request the fields I need and add them to the list of claims. Then I can use that information to create/log in the user.
public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
{
var externalUser = ctx.ExternalIdentity;
var claimsList = ctx.ExternalIdentity.Claims.ToList();
if (externalUser.Provider == "Facebook")
{
var extraClaims = GetAdditionalFacebookClaims(externalUser.Claims.First(claim => claim.Type == "urn:facebook:access_token"));
claimsList.Add(new Claim("email", extraClaims.First(k => k.Key == "email").Value.ToString()));
claimsList.Add(new Claim("given_name", extraClaims.First(k => k.Key == "first_name").Value.ToString()));
claimsList.Add(new Claim("family_name", extraClaims.First(k => k.Key == "last_name").Value.ToString()));
}
if (externalUser == null)
{
throw new ArgumentNullException("externalUser");
}
var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId));
if (user == null)
{
ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, claimsList);
}
else
{
ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, claimsList);
}
}
And that's it! If you have any suggestions for simplifying this process, please let me know. I was going to modify this code to do perform the call to the API from FacebookAuthenticationOptions, but the Events property no longer exists apparently.
Edit: the GetAdditionalFacebookClaims method is simply a method that creates a new FacebookClient given the access token that was pulled out and queries the Facebook API for the other user claims you need. For example, my method looks like this:
protected static JsonObject GetAdditionalFacebookClaims(Claim accessToken)
{
var fb = new FacebookClient(accessToken.Value);
return fb.Get("me", new {fields = new[] {"email", "first_name", "last_name"}}) as JsonObject;
}

Getting feeds for Public Pages of Facebook using Spring Social or Restfb

I need to build a server which would get the public feed details of various companies/ brands. For example, I should be able to get the feed for last one week for Cocacola (facebook.com/cocacolaindia) , Pepsi, Levis etc. Since I am only looking for public feeds I thought I dont need to use OAuth for authorization but I see no other way to get this info. For example - i tried below code but none of last three ways works.
String acessTok = "{my app id}|{app seceret key}"; //App level token
Facebook facebook = new FacebookTemplate(acessTok);
FacebookProfile profile = facebook.userOperations().getUserProfile("cocacolaIndia");
Page page = facebook.pageOperations().getPage("cocacolaIndia");
List<Post> list= facebook.feedOperations().getFeed("cocacolaIndia");
Is there a way out ? I can use httpurl to call http://graph.facebook.com/ and
parse the json but then would need my own api's to get different fields which I don't want to do..
You can use an App Access Token. Here's some RestFB example.
AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(MY_APP_ID, MY_APP_SECRET);
Now you can build your FacebookClient with this new access token.
With fetchConnection you can fetch the public posts from the desired "fanpage".
I had the same Problem.
I was trying to access the public Posts of an Facebook Page only with the AppId and AppSecret.
The following worked for me:
private Facebook facebook;
...
this.facebook = new FacebookTemplate("{AppId}|{AppSecret}");
...
Collection<Post> posts =this.facebook.feedOperations().getPosts("{PageId}");
I hope this is helpful.

Setting user's email on Facebook signup with Parse.com

I'm using Parse.com and trying to set up user sign up with Facebook.
Upon authentication with Facebook for the first time a beforeSave is called on _User to fetch additional user details:
function UserBeforeSave(request, response){
var user = request.object,
auth = user.get('authData');
// check if user is newly registered
if (!user.existed()) {
// Check if a user signs up with facebook
if (Parse.FacebookUtils.isLinked(request.object)) {
// Query Graph API for user details
Parse.Cloud.httpRequest({
url:'https://graph.facebook.com/v2.2/me?access_token=' + auth.facebook.access_token,
success:function(httpResponse){
// Map facebook data to user object
if (httpResponse.data.first_name) request.object.set('first_name', httpResponse.data.first_name);
if (httpResponse.data.last_name) request.object.set('last_name', httpResponse.data.last_name);
if (httpResponse.data.email) request.object.set('email', httpResponse.data.email);
response.success();
},
error:function(httpResponse){
console.error(httpResponse);
response.error();
}
});
} else {
response.success();
}
} else {
response.success();
}
}
Problem is that that email line is actually breaking the operation with error:
Can't modify email in the before save trigger
I tried moving this code to the afterSave but the authdata is not available there making it difficult to call the FB API. The email is therefore left blank at the moment.
I'm assuming this is a very common use case of integrating Parse with the Facebook API, am I missing something in the integration process that automatically fetches the email?
I just do the graph query client-side and set email there. This works fine.
Is there a reason you want to do it in the before/afterSave on the User?

Accessing signed Facebook JSON using Play 2.0.1 and RestFB

I'm writing an Play 2.0.1 application that will be deployed within a canvas page on Facebook. I'm using restFB for the Facebook API.
By manually creating an Access Token at https://developers.facebook.com/tools/explorer?method=GET I can get my application to access the Facebook user's name and render it in the Canvas page iFrame on Facebook.
So, my app controller receives the POST and renders a page like this:
public static Result handle_fb_post() {
return redirect(routes.canvas.fb_render_profile_page());
}
public static Result fb_render_profile_page() {
String accessToken = "<access token copied from facebook graph explorer>";
DefaultFacebookClient().getExtendedAccessToken(application_id, application_secret);
FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
User fbUser = facebookClient.fetchObject("me", com.restfb.types.User.class);
return ok(views.html.fbuser.render(fbUser));
}
My routes are set up as:
POST /fbcanvas/ controllers.FBCanvas.handle_fb_post()
GET /fbcanvas/profile controllers.FBCanvas.fb_render_profile_page()
However, how can I get access to the signed JSON that Facebook sends me in the POST? I believe that this also contains the access token from the user (assuming that they have authorised my app) as described here:
https://developers.facebook.com/docs/samples/canvas/ (See section on "signed_request Parameter").
There are a number of examples out there for Java, PHP, Javascript and Python, but I can't find any that describe how to do this in Play 2 or using RestFB. I have tried a number of different approaches, but cannot work out how to access the signed request in Play 2.
Can anyone help and explain how this can be done?
If the token is sent as Json in the POST request, you can grab it via
def handle_post() = Action { implicit request =>
val jsonBody = request.body.asJson
//process it
}

Don't know how to get user data after oAuth Dialog

i'm developing a FB app.
The app is authenticating within a canvas page, redirect to OAuth Dialog upon page load
if(!isset($data['user_id']) && $data['page']['liked']){ ?>
<script>
var oauth_url = 'https://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=XXXX';
oauth_url += '&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/YYYY/');
window.top.location = oauth_url;
</script>
<?php
}
When the user authenticate i just need to read the Name of the User, but i can't find that info into the signed_request.
What am i doing wrong?
You need to do the following steps:
Decode the signed request as mentioned here.
Extract the access token.
Make a new request with the extracted access token to retrieve the user's name.