EzDevInfo.com

facebook-node-sdk

Modeled from the (Facebook Javascript SDK), now with the facebook-node-sdk you can now easily write the same code and share between your server (nodejs) and the client (Facebook Javascript SDK).

Automatic post to my facebook page from Node.js server

I have a Node.js server running a social network site and I also have a facebook page for that site. For certain actions performed by users on my site, I want to post details on the facebook page of my app.

I referred to Thuzi facebook node sdk here on how to post to facebook wall. However, it requires app id, app secret and a temporary access token. App id and app secret are constant so I can put them somewhere in my config file and use from there. But how do I get the access token without any interaction from front-end ? All posts will be published by our app only and that too on our own page. I just want this to be triggered by the end user's actions. Any help ?

I am using Sails.js framework btw.


Source: (StackOverflow)

Bluebird.js in Node and asynchronous api calls

So I'm trying to build my first webapp with Facebook integration (using facebook-node-sdk). I have it making simple calls to the api, but now it's time to put this all in a simple server and make the calls upon request (this isn't going to be the webapp, itself, but more of an API server).

The problem I'm running into is that, even though I've (presumably) used bluebird to Promisify the Facebook sdk and my makeCall method, I'm still getting "hi" printed and then "undefined" - console.log is getting called before makeCall can return anything.

Here's my app.js:

var Promise = require('bluebird')
    , http = require('http')
    , Facebook = Promise.promisifyAll(require('facebook-node-sdk'))
    , config = require('./config')
    , fb = new Facebook({ appId: config.fb.api, secret: config.fb.secret });

var makeCall = new Promise.method(function (username) {
    return fb.api(username, function(err, data) {
        console.log('hi')
        if (err) return err;

        return data;
    });
});

http.createServer( function (req, res) {
    makeCall('/me').then(console.log)
}).listen(8001);

Source: (StackOverflow)

Advertisements

Facebook access token not accepted to Open Graph using Node.js facebook-node-sdk

Posting an Open Graph action using the Node.js facebook-node-sdk module gives me {"error": "An active access token must be used to query information about the current user."}.

var FB = require( 'fb' )
var path = '/me?' + namespace + ':' + action_type_name
var body = {
     access_token: myAccessToken,
     myAction : myCustomObjectURL
}
FB.api( path, 'post', body, function( res )
{
    if( res.error ) {
        console.log( 'the call to open graph failed: ' + res.error.message );
    }
    else {
        console.log( 'success' )
    }
})

If I print this access token and use it with cURL (curl https://graph.facebook.com/me?access_token=myAccessToken), it returns correctly, no error. Facebook also shows that the app has permission to post as this user. So what am I doing wrong here?


Source: (StackOverflow)

Fetching Facebook Status updates using NodeJS

I want to Fetch Every Facebook Status update i make from my Fb Account using NodeJS and print it in my console ...Can this process be event driven,Is there a way wherein a event is generated and the NodeJs server is notified when a new facebook status update is made without polling for it ???


Source: (StackOverflow)

Integrate Facebook apis in the web app [closed]

I'm working on a web app which can post and read user posts from facebook. In search of achieving this, I found various tutorials which are doing it through different approach. I decided to pick the official documentation of Facebook Deveopers guide to accomplish my task but somehow it's not working for me.

Development Environment: Angularjs Express Node.js

Since there is no official node.js based Facebook SDK, I decided to choose https://github.com/Thuzi/facebook-node-sdk and started following examples along with the formal documentation https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.4#logindialog

var FB = require('fb');
var config = require('../../config/environment');
var mongoose = require('mongoose');


FB.options({
  appId: config.facebook.appId,
  appSecret: config.facebook.appSecret,
  redirectUri: config.facebook.redirectUri
});

exports.login = function(req, res) {
  console.log(req);
  var loginUrl = FB.getLoginUrl({
    scope: 'public_profile,email,user_friends,publish_actions'
  });
  console.log(loginUrl);
  res.send(200, {
    redirect: loginUrl
  });
}

So, far I have achieved getting a redirect url which will ask for user permission but my problem is:

  1. FB.login() as mentioned in the documentation is not working. What I would like to achieve is show a login pop up and once a user logs in the facebook, I will show permissions pop up to user.
  2. Not all functions mentioned in the FB Documentation for javascript SDK are working for Thuzi's Node.js SDK ? Any work around for this ?
  3. Design wise what I'm doing is hit the backend for doing all the processing and give my redirect urls to the ui where I can show the appropriate window. Is this correct approach ?
  4. Can anyone give me some code snippets/pointers to some github gists which can help me in acheiving my task ?
  5. I'm following this but somehow this is not very clear as this uses different modules like Step. https://github.com/Thuzi/facebook-node-sdk/blob/master/samples/scrumptious/routes/home.js Any other pointers to some tutorials will be helpful.
  6. Is the node.js package correct ? I picked this package as this seems to be mentioned on may SO threads. Please let me know of any other node-facebook-sdk if they are better than this.

Source: (StackOverflow)

How to respect RESTful with Data synchonized from Facebook

I’m trying to build a web-app with integration of some Facebook data. (Facebook Events in particular).

I would like to know what are the best practices/recommandations to handle synchronization.

Here is my current thought: In my database, I need to have:

  • User: with Facebook ID, and list of friends
  • Event: with list of User

In mongoose syntax it means the following schema:

var UserSchema = new Schema({
  id: { type: String, default: '' },
  friends: [{type : Schema.ObjectId, ref : 'User'}]
})
mongoose.model(‘User', UserSchema )

var EventSchema = new Schema({
  eid: { type: String, default: '' },
  users: [{type : Schema.ObjectId, ref : 'User'}]
})
mongoose.model('Event', EventSchema)

For now, I’m using Passport-Facebook to handle authentication and Facebook-Node-SDK (https://github.com/Thuzi/facebook-node-sdk) to make graph call. So I can set my accessToken during my Passport FacebookStrategy:

passport.use(new FacebookStrategy({
  clientID: config.facebook.clientID,
  clientSecret: config.facebook.clientSecret,
  callbackURL: config.facebook.callbackURL
 },
 function(accessToken, refreshToken, profile, done) {
   FB.setAccessToken(accessToken); //Setting access token
   User.findOne({ 'id': profile.id }, function (err, user) {
      //handling creation in case of error 
      //then synchronization of friends
   })
]);

Once the user is logged, I redirect him to an URL which first call a static method which synchronize FB events of current user then redirect him to the following route:

app.get('/events', events.index)

But this is not compliant with RESTful standards ? For example, with my method I didn’t need route like this:

app.post('/events', events.add)
app.put('/events', events.update)
app.del('/events', events.destroy)

In fact, I don’t see how to proper implement this kind of syntonization and I’m worry with the future integration of front-end solution.

Can someone point me what I am missing and eventually give some advices/link to handle this situation ? Is it better to handle the listing of event on client-side with Official Facebook SDK and just give to my API the IDs needed? In this case, how to secure the data ?

Thanks you!

Update: It's an extand of this question Web app integration with facebook ( architecture issues ) Regarding the answer, I can't figure it out with my particular case.


Source: (StackOverflow)

facebook-node-sdk for node.js scope parameter?

https://github.com/amachang/facebook-node-sdk decided to use this module to build my facebook integrated login for node.js following the example with express:

var express = require('express');

var Facebook = require('facebook-node-sdk');

var app = express.createServer();
app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'foo bar' }));
  app.use(Facebook.middleware({ appId: 'YOUR_APP_ID', secret: 'YOUR_APP_SECRET' }));
});

app.get('/', Facebook.loginRequired(), function (req, res) {
  req.facebook.api('/me', function(err, user) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, ' + user.name + '!');
  });
});

how to add additional permissions like "email"?


Source: (StackOverflow)

Controlling visual appearance of a url published on facebook from node.js server

I am publishing a facebook post on my app's page from a node.js server. I asked a question related to how to get an access token with long expiration period and now know how to post on facebook. Here is the link to that question. Now I am sharing a url from a website. Now, normally when we copy paste a url from a site like youtube, it does not appear as a text link but facebook automatically detects that it's a video link and displays it with a thumbnail of the video and some summary as well. Similarly, same happens if we share an article from a site.

But when I share the url from my code (sample code mentioned below), it just appears as a text url. How can I make sure that it appears with the thumbnail and the description ? I could not find this option in the documentation.

          FB.api('me/feed', 'post', 
            { 
              message: encodeURI(link)
            }
            , function (res) {
            if(!res || res.error) {
              console.log(!res ? 'error occurred' : res.error);
              return;
            }
            console.log('Post Id: ' + res.id);
          });

Source: (StackOverflow)

How to capture results from end of FOR loop with Nested/Dependent APIs calls in Node JS

This is my first JavaScript & Node project and I am stuck….

I am trying to call a REST API that returns a set of Post IDs... and based on the set of retrieved IDs I am trying to call another API that returns details for each ID from the first API. The code uses Facebook API provided by Facebook-NodeSDK.

The problem I am having is that the second API fires of in a FOR Loop…. As I understand the for loop executes each request asynchronously…. I can see both the queries executing however I can’t figure out how to capture the end of the second for loop to return the final result to the user…

Following is the code…

exports.getFeeds = function(req, res) {

    var posts = [];
    FB.setAccessToken(’SOME TOKEN');
    var resultLength = 0;


     FB.api(
        //ARG #1 FQL Statement
        'fql', { q: 'SELECT post_id FROM stream WHERE filter_key = "others"' },
        //ARG #2 passing argument as a anonymous function with parameter result
        function (result)
           {

               if(!result || result.error) {
                    console.log(!result ? 'error occurred' : result.error);
                    return;
                } //closing if handling error in this block

                    var feedObj
                    console.log(result.data);
                    console.log(result.data.length);

                        for (var i = 0; i<resultLengthj ; i++) {

                        (function(i) {
                            feedObj             = {};
                            FB.api( result.data[ i].post_id,  { fields: ['name', 'description', 'full_picture' ] },
    //                          fbPost is data returned by query
                                function (fbPost) {
                                    if(!fbPost || fbPost.error) {
                                        console.log(!fbPost ? 'error occurred' : result.error);

                                        return;
                                    }
    //                                else
                                        feedObj=fbPost;
                                        posts.push(feedObj);
                            });
                       })(i);
                    }// end for

           }//CLOSE ARG#2 Function

    );// close FB.api Function

NOTE I need to call…... res.Send(post)…. and have tried to call it at several places but just can’t get all the posts… I have removed the console statements from the above code…which have shown that the data is being retrieved...

Thanks a lot for your help and attention....


Source: (StackOverflow)

Facebook app not working for new users

I have developed a facebook app in node js which is hosted on heroku. It will display some of the users public data.It worked fine for two days but from the next day it is showing an application error for new users but for the users who have already used the app it is working fine.I couldn't understand where the problem lies if I run it locally using "foreman start" or "node web.js" I'm getting an " this web-page has a redirect loop" message only for new users.I have tried it by deleting all the cookies and webpage data also even then I got the same message. I'm using "facebook-node-sdk" for facebook connect and "ejs" for displaying the web-page and express for server.

App looks like this for old users

The app is hosted here

I couldn't find anything in the logs also. Can anyone help me in solving this problem.

The app code:

var express = require('express');
var Facebook = require('facebook-node-sdk');
var app = express.createServer();
var pic;
var cover;
app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'password' }));
  app.use(Facebook.middleware({appId:'12345',secret:'12345'}));
});
app.set('view options', { layout: false });
app.set('view engine', 'ejs');
app.get('/', Facebook.loginRequired(), function (req, res) {
        req.facebook.api('/me?fields=picture.type(square)', function(err, pict) {
            pic=pict.picture.data.url;
        });
    req.facebook.api('/me?fields=cover',function(err,cover_pg){
        cover=cover_pg.cover.source;
        });
    req.facebook.api('/me', function(err, user) {
            res.render('home', {locals: {
        title:'Public-Profile', 
        user:user.name , 
            id:user.id, 
        gender:user.gender,
        hometown:user.hometown.name, 
        current:user.location.name,
        link:user.link,
        pic:pic,
        cover:cover
        }
        });
    });
}); 
var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});

The ejs file code:

<html>
<head>
<title><%= title %></title>
</head>
<body>
<h3>This app is ment to show all your facebook public profile</h3>
<h3>Welcome:</h3>
<h3><img src=<%= pic %>> <%= user %>   </h3> 
<a rel='nofollow' href=<%= cover %> target="_blank"><img src=<%= cover %> height="200"></a>
<h3>Your Facebook Id:<%= id %></h3>
<h3>Gender:<%= gender %></h3>
<h3>Your home-town:<%= hometown %></h3>
<h3>Your Current-Location:<%= current %></h3>
<a rel='nofollow' href=<%= link %> target="_blank"><h2>Visit Your Profile</h2></a>
<br/><br/><br/><br/><br/><br/><br/><br/>
<p>--By Dinesh</p>
<p>This app is still under development it will be ready soon...</p>
</body>
</html>

Source: (StackOverflow)

Facebook sometimes doesn't pass signed request

I have a Facebook Pagetab application I've developed using Node JS and Express. It seems to work perfectly most of the time, but sometimes it doesn't. I'm having issues replicating the issue, which therefore makes it difficult to debug, but I think I've located the problem.

When the home page loads I utilise Thuzi's Facebook module (https://github.com/Thuzi/facebook-node-sdk) to screen the signed request that Facebook passes me, in order to determine if the user likes the page or not:

var fb = require('fb');
var signedRequest  = fb.parseSignedRequest(req.body.signed_request, process.env.FACEBOOK_APP_SECRET);   

if(signedRequest ){
    if( signedRequest.page.liked){
        res.redirect('/authorise');                         
    }
    else {
        res.redirect('/gate');
    }
}
else {
    console.log('No signed request');
}   

However, sometimes the 'No signed request' is being sent to the console, so basically Facebook sometimes doesn't pass a signed request. User's are therefore just being shown a blank screen. If I use code to redirect to the homepage it just gets stuck in an infinite loop. I need the signed request in order to redirect the user accordingly. Is there any reason that Facebook would sometimes not send me a signed request?

If I check the contents of req.body.signed_request it is sometimes empty, so it's not as if the fb module isn't working properly.


Source: (StackOverflow)

facebook api getting full posts with > 2 comments or > 4 likes

when I make the user/feed request on the Facebook Open Graph API, I get a feed object where posts with > 2 comments or > 4 likes don't reveal the detailed information for those specific comments.

I am using https://github.com/Thuzi/facebook-node-sdk to make requests but it is very similar to the 'request' NodeJS library.

I can get the full posts individually by making a separate request for that post's Open Graph ID, but this doesn't lend itself to fun code because requests are asynchronous and nesting more asynchronous calls within asynchronous calls doesn't lend itself to fun code.

Any way I can obtain the full posts?


Source: (StackOverflow)