Giter Site home page Giter Site logo

linkedin-js's Introduction

linkedin-js

Easy peasy linkedin client for connect.

npm install linkedin-js

Usage

linkedin-js has two methods.

  • getAccesToken(req, res, callback): Uses oAuth module to retrieve the access_token
  • apiCall(http_method, path, params, callback): Does a call to the linkedin API.

Params are sent as JSON. Params must contain the token.

Using JSON with linkedin API

Example using express.js

var express = require('express')
  , linkedin_client = require('linkedin-js')('key', 'secret', 'http://localhost:3003/auth')
  , app = express.createServer(
      express.cookieParser()
    , express.session({ secret: "string" })
    );

app.get('/auth', function (req, res) {
  // the first time will redirect to linkedin
  linkedin_client.getAccessToken(req, res, function (error, token) {
    // will enter here when coming back from linkedin
    req.session.token = token;
    
    res.render('auth');
  });
});

app.post('/message', function (req, res) {
  linkedin_client.apiCall('POST', '/people/~/shares',
    {
      token: {
        oauth_token_secret: req.session.token.oauth_token_secret
      , oauth_token: req.session.token.oauth_token
      }
    , share: {
        comment: req.param('message')
      , visibility: {code: 'anyone'}
      }
    }
  , function (error, result) {
      res.render('message_sent');
    }
  );
});

app.listen(3003);

Test

linkdin is fully tested using testosterone

make

linkedin-js's People

Contributors

gmodena avatar masylum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

linkedin-js's Issues

Cannot find module 'linkedin-js' -- probably a problem with NPM install

Hi,

Thanks for the libs, I hope I get to use them.

I installed linkedin-js via npm and used similar code to the example, like this,

app.get('/linkedin/share/:message', function (req, res) {
  var linkedinClient = require('linkedin-js').linkedinClient( '[redacted]',
  '[redacted]' );

  linkedinClient.getAccessToken(req, res, function (error, token) {
    linkedinClient.apiCall('POST', '/people/~/shares',
      {
        token: token,
        share: {
          comment: message,
          visibility: {code: 'anyone'}
        }
      },
      function (error, result) {

        console.log('err: ' + sys.inspect(error) + ', result: ' + result );

        // res.render('linkedin_share.jade', {locals: {result: result}});
      }
    );
  });
 });    

But when I go to this page I get an error in the console that it cannot find the package linkedin-js like this

Error: Cannot find module 'linkedin-js'
   at loadModule (node.js:275:15)
   at require (node.js:411:14)

....

I'll also post this on the npm board if you'd like me to but isaacs usually says to bug the dev.

Thanks man,

Paul.

tests fail because callback is wrapped

assert.equal(_callback, callback); throws in the first GET test - I think this is because the callback is wrapped with requestCallback in linkedin_client.js.

How do you specify member permissions using the client interface?

I've been looking through usage examples and the actual code, and I'm not sure how to actually specify which member permissions I need for the endpoint I'm requesting, e.g. /people/~/connections, which requires 'r_network' scope permissions.

Is this a current capability of the system and I'm just not seeing how to do it, or is the library limited to requests that only require r_basicprofile?

Thanks in advance.

Special characters cause JSON parse error

I've found that special characters and accented letters (such as à and ù) result in an error from the LinkedIn API. An example is below:

{ statusCode: 400,
  data: '{\n  "errorCode": 0,\n  "message": "Couldn\'t parse Json body: Unexpected end-of-input: was expecting closing quote for a string value\\n at [Source: java.io.StringReader@6698b427; line: 1, column: 1175]",\n  "requestId": "P2QMS7NT0H",\n  "status": 400,\n  "timestamp": 1387218280516\n}' }

The JSON object that causes the error looks like the following. Note that removing special characters fixes the problem.

{
    "comment": "Quali prospettive per un Content Marketing finalizzato al Consumer Engagement?",
    "content": {
        "title": "Il Content Marketing nel B2C: quali prospettive?",
        "description": "Il Content Marketing, come molti sapranno, nasce (inconsapevolmente) negli Stati Uniti già a cavallo tra Ottocento e Novecento come tecnica di vendita dedicata al mercato Consumer. Solo più di recente, anche grazie ai mutamenti di …",
        "submittedUrl": "http://sanfrancisco.bizjournals.com/sanfrancisco/stories/2010/06/28/daily34.html",
        "submittedImageUrl":  "http://images.bizjournals.com/travel/cityscapes/thumbs/sm_sanfrancisco.jpg"
    },
    "visibility": {
        "code": "anyone"
    }
}

Cannot make POST request

When making a POST request (i.e. sharing something or trying to send a message), I get a 401 error:

error: [Messaging] error: { statusCode: 401,
data: '\n\n 401\n 1336572233851\n Q9YREZSZ2Z\n 0\n [unauthorized]. OAU:blablabla (token etc)=\n\n' }

When trying to do a GET request, everything goes fine (i.e. getting my connections). Here is the code for the POST request:

this.userManager.getLITokens(this.email, function (err, doc) {
            if (err) {
                log.error(util.inspect(err));
            } else if (doc != null) {
                var token = crypto.decrypt(doc.token);
                var secret = crypto.decrypt(doc.secret);
                log.debug('sending message: ' + message);
                linkedin.apiCall('POST', '/people/~/shares',
                    {
                        'token': {
                            'oauth_token': token,
                            'oauth_token_secret': secret
                        },
                        // 'mailbox-item': {
                        //     'recipients' : {
                        //         'values' :
                        //             [{
                        //                 'person' : {
                        //                     '_path' : '/people/~',
                        //                 }
                        //             }]
                        //     },
                        //     'subject' : subject,
                        //     'body' : message
                        // }
                        'share' : {
                            'comment' : message,
                            'visibility' : {code: 'anyone'}
                        }
                    }, 
                    function (error, result) {
                        if (error) {
                            log.error('[Messaging] error: ' + util.inspect(error));
                            callback(error, null);
                        } else {
                            callback(null, result);
                        }
                    }
                );
            } else {
                log.error('Something has gone wrong.');
            }
        });

I don't know if this is a real issue (i.e. bug) with the library or something else is wrong. The token and secret definitely work (get the same error when I hard-code them unencrypted). Someone who knows what's wrong?

Consecutive call to apiCall does not reset paramAppender

If in callback of the linkedin_client.apiCall we make another call to linkedin_client.apiCall
paramAppender does not reset which can cause problem for the next call.

Example:

linkedin_client.apiCall(
'GET'
,'/job-search?country-code=us&postal-code=90210&count=1'
, {token: myToken}
, searchCallback);

var searchCallback = function (error, response, body) {

if(error === null)
{


    var results = response.jobs.values;

    for(var i=0; i<jobs.length; i++)
    {
        linkedin_client.apiCall(
          'GET'
        ,'/jobs/' + jobs[i].id + 
        , {token: myToken}
        , anotherCallback);
    }
}

}

Solution:
add paramAppender = "?"; upon entering apiCall()

PUT method; raw JSON values; 201 status responses

Hopefully I can follow up with a patch soon but I wanted to let you know about the errors I'm seeing...

In the LinkedIn developer documentation for JSON API usage at https://developer.linkedin.com/documents/api-requests-json there are some examples of translating XML to JSON for API request payloads.

The API request I'm using is a PUT to /people/~/network/updates/key={ID}/is-liked - this requires adapting linkedin_client.js to allow a PUT or a POST where it currently only allows POST, and to choose the correct method on the OAuth client instance.

To PUT a new is-liked value to LinkedIn you are required to send just true as the body of the HTTP request. This means that sending the params object, even with other parameters deleted, is not sufficient. I ended up detecting this case specifically and setting isLiked on my parameters object, but it seems like splitting the token parameters from the API payload would be a smarter approach. I'll look at this next.

Anyway, here's what I ended up with in linkedin_client.js:

    } else if (method.toUpperCase() === 'POST' || method.toUpperCase() == 'PUT') {
      return CLIENT.oauth[method.toLowerCase()](
        _rest_base + path
      , token.oauth_token
      , token.oauth_token_secret
      , JSON.stringify(params.isLiked ? true : params)
      //, 'application/json; charset=UTF-8'
      , 'application/json'
      , requestCallback(callback)
      );
    }

I'm not 100% certain that specifying the charset was causing problems - I'll confirm before submitting a pull request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.