dylanthelion
dylanthelion

Reputation: 1770

Request user email from Twitter in node.js

I'm trying to enable oauth2 login through Twitter in a node app. I have my Twitter account, I am whitelisted for email, have changed the settings on the Twitter development page (so that on login, the user is informed that my app can access their email).

But the user object still does not contain an email entry. Is email a different request, or am I missing something? I'll put the server code below, and can fire up the web server on demand, in case anybody wants to see the console output.

Relevant code in my server.js:

var express = require('express'),
request = require('request'),
path    = require('path'),
fs = require('fs'),
bodyParser = require("body-parser");

var Twitter = require("node-twitter-api");
var app = express();
...
var twitter = new Twitter({
    consumerKey: 'XXXXXXX',
    consumerSecret: 'XXXXXX',
    callback: 'http://thelionstestingjungle.com'});

var _requestSecret;

app.get("/tokenRequest", function(req, res) {
console.log('Token request');
twitter.getRequestToken(function(err, requestToken, requestSecret) {
    if (err) {
        console.log('Token request error');
        res.status(500).send(err);
    } else {
        console.log('Request secret: ' + requestSecret);
        _requestSecret = requestSecret;
        res.redirect("https://api.twitter.com/oauth/authenticate?oauth_token=" + requestToken);
    }
});});

app.get("/accessToken", function(req, res) {
console.log('Access token');
var requestToken = req.query.oauth_token,
verifier = req.query.oauth_verifier;

twitter.getAccessToken(requestToken, _requestSecret, verifier, function(err, accessToken, accessSecret) {
        if (err) {
            console.log('Get info error');
            res.status(500).send(err);
        } else {
            twitter.verifyCredentials(accessToken, accessSecret, function(err, user) {
                if (err) {
                    console.log('Verification in get info error');
                    res.status(500).send(err);
                } else {
                    console.log('User: ' + JSON.stringify(user));
                    res.send(user);
                }
            });
        }
    });});

...

Upvotes: 2

Views: 1043

Answers (1)

dylanthelion
dylanthelion

Reputation: 1770

SO! The call is indeed different. The verify_credentials call to the API takes a handful of optional params. See the doc page:

https://dev.twitter.com/rest/reference/get/account/verify_credentials

To retrieve user email, add a include_email=true param to your URL. To do this with the node-twitter-api module:

var params = {
                'include_email' : true
            };
twitter.verifyCredentials(accessToken, accessSecret, params, function(err, user)

The module takes a dictionary, and parses the key-value pairs into URL params, and adds them for you.

EASY!

Upvotes: 2

Related Questions