我正在创建一个应用程序,我需要在该应用程序中代表不同的用户在Twitter上发布推文。因此,我使用应用程序用户身份验证。对于我来说,要将用户重定向到Twitter页面以提供访问权限,我需要Twitter的oauth_token。 为此,我正在使用Request_token_api。 但是每次都无法对您进行身份验证,twitter api页面说此API不需要授权
我尝试使用许多库,例如通行证,Twit,OAuth等。但是没有任何效果,我很确定我的所有开发人员帐户Consumer_key,consumer_secret,access_token,access_token_secret都是正确的。
function getAuthorization(httpMethod, baseUrl, reqParams) {
// Get acces keys
const consumerKey = keysJson.TWITTER_CONSUMER_KEY,
consumerSecret = keysJson.TWITTER_CONSUMER_SECRET,
accessToken = keysJson.TWITTER_ACCESS_TOKEN,
accessTokenSecret = keysJson.TWITTER_ACCESS_TOKEN_SECRET;
// timestamp as unix epoch
let timestamp = Math.round(Date.now() / 1000);
// nonce as base64 encoded unique random string
let nonce = crypto.randomBytes(32).toString('base64').replace(/[^0-9a-zA-Z]/g, '') ;
let cburl = percentEncode(keysJson.cb);
// generate signature from base string & signing key
let baseString = oAuthBaseString(httpMethod, baseUrl, reqParams, consumerKey, accessToken, timestamp, nonce);
console.log(baseString);
let signingKey = oAuthSigningKey(consumerSecret, accessTokenSecret);
// console.log(signingKey);
let signature = oAuthSignature(baseString, signingKey);
console.log(signature);
// return interpolated string
return 'OAuth ' +
'oauth_nonce="' + nonce + '", ' +
'oauth_callback="' + cburl + '", ' +
'oauth_signature_method="HMAC-SHA1", ' +
'oauth_timestamp="' + timestamp + '", ' +
'oauth_consumer_key="' + consumerKey + '", ' +
'oauth_signature="' + signature + '", ' +
'oauth_version="1.0"' ;
}
function oAuthBaseString(method, url, params, key, token, timestamp, nonce) {
return method
+ '&' + percentEncode(url)
+ '&' + percentEncode(genSortedParamStr(params, key, token, timestamp, nonce));
};
function oAuthSigningKey(consumer_secret, token_secret) {
return consumer_secret + '&' + token_secret;
};
function oAuthSignature(base_string, signing_key) {
var signature = hmac_sha1(base_string, signing_key);
return percentEncode(signature);
};
function percentEncode(str) {
return encodeURIComponent(str).replace(/[!*()']/g, (character) => {
return '%' + character.charCodeAt(0).toString(16);
});
};
function hmac_sha1(string, secret) {
let shaObj = new jsSHA("SHA-1", "TEXT");
shaObj.setHMACKey(secret, "TEXT");
shaObj.update(string);
let hmac = shaObj.getHMAC("B64");
return hmac;
};
function mergeObjs(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
return obj1;
};
function genSortedParamStr(params, key, token, timestamp, nonce) {
// Merge oauth params & request params to single object
let paramObj = mergeObjs(
{
include_entities: 'true',
oauth_consumer_key : key,
oauth_nonce : nonce,
oauth_signature_method : 'HMAC-SHA1',
oauth_timestamp : timestamp,
// oauth_token : token,
oauth_version : '1.0'
},
);
// Sort alphabetically
let paramObjKeys = Object.keys(paramObj);
let len = paramObjKeys.length;
paramObjKeys.sort();
// Interpolate to string with format as key1=val1&key2=val2&...
let paramStr = paramObjKeys[0] + '=' + paramObj[paramObjKeys[0]];
for (var i = 1; i < len; i++) {
paramStr += '&' + paramObjKeys[i] + '=' + percentEncode(decodeURIComponent(paramObj[paramObjKeys[i]]));
}
return paramStr;
};
var redirect_uri = encodeURIComponent('http://localhost:4200/admin/marketing/loginsuccess');
var auth = getAuthorization('POST','https://api.twitter.com/oauth/request_token',{oauth_callback:redirect_uri});
console.log(auth);
var options = {
"method": "POST",
"hostname": "api.twitter.com",
"port": null,
"path": '/oauth/request_token',
"headers": {
'Authorization' : auth
}
};
try {
console.log(options);
var req = https.request(options, function (res1) {
var chunks = [];
console.log('statusCode:', res1.statusCode);
console.log('headers:', res1.headers);
res1.on("data", function (chunk) {
chunks.push(chunk);
});
res1.on("end", function () {
var body = Buffer.concat(chunks);
var disp = JSON.parse(body.toString());
console.log(disp);
});
});
req.end();
} catch (error) {
console.log(error);
res.json({success:false,message:error});
}
我需要Twitter API的oauth访问令牌,但正在获取。
{ errors: [ { code: 32, message: 'Could not authenticate you.' } ] }
我努力了3天。请让我知道,有没有其他方法可以在nodejs中实现twitter API或在github中实现一些示例代码。
先谢谢了。