Created
April 28, 2018 09:23
-
-
Save jayasimhan/0885bbbd2b06f83da965963f5ac18a71 to your computer and use it in GitHub Desktop.
Example twitter api call including construction of the auth header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CONSUMER_KEY="consumer_key"; | |
const CONSUMER_SECRET="consumer_secret"; | |
const ACCESS_TOKEN="access_token"; | |
const ACCESS_TOKEN_SECRET="access_token_secret"; | |
const crypto = require('crypto'); | |
const qs = require("querystring") | |
const request = require("request"); | |
function getTwitterFollowList(){ | |
return new Promise(function(resolve, reject){ | |
let url = "https://api.twitter.com/1.1/friends/list.json"; | |
let method = "GET"; | |
let oauthParams = { | |
oauth_consumer_key: CONSUMER_KEY, | |
oauth_nonce: generateNonce(), | |
oauth_signature_method: "HMAC-SHA1", | |
oauth_timestamp: Math.round(Date.now()/1000), | |
oauth_token: ACCESS_TOKEN, | |
oauth_version: "1.0" | |
}; | |
let requestParams = {} | |
let baseStringParams = Object.assign({},requestParams,oauthParams); | |
let baseString = `${method.toUpperCase()}&${encodeURIComponent(url)}&${encodeURIComponent(qs.stringify(baseStringParams))}` | |
let signingKey = `${encodeURIComponent(CONSUMER_SECRET)}&${encodeURIComponent(ACCESS_TOKEN_SECRET)}`; | |
let signature = crypto.createHmac('sha1', signingKey).update(baseString).digest('base64'); | |
let header = constructHeader(Object.assign({},oauthParams,{oauth_signature: signature})); | |
let requestObj = { | |
"url": url, | |
"method": method, | |
"headers":{ | |
"Authorization": header | |
} | |
} | |
request(requestObj, (e, res, body)=>{ | |
if(e){ | |
return reject(e.message) | |
} | |
resolve({status: res.statusCode, data: JSON.parse(body)}) | |
}) | |
}); | |
} | |
function constructHeader(options){ | |
let headerString = "OAuth ", headerParts=[]; | |
let keys = Object.keys(options); | |
keys.sort(); | |
for (let index = 0; index < keys.length; index++) { | |
const key = keys[index]; | |
headerParts.push(`${key}="${encodeURIComponent(options[key])}"`) | |
} | |
return headerString+headerParts.join(", "); | |
} | |
function generateNonce(){ | |
let nonceString = crypto.randomBytes(32).toString("base64") | |
return nonceString.replace(/[^a-zA-Z0-9]/gi,""); | |
} | |
module.exports = { | |
getTwitterFollowList: getTwitterFollowList | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment