尝试从https://api.twitter.com/oauth/request_token
获得成功的响应我没有运气,我花了很长时间阅读文档以尝试构建一个头字符串,该字符串将为我提供来自API的访问令牌。我一直在关注https://developer.twitter.com/en/docs/twitter-for-websites/log-in-with-twitter/guides/implementing-sign-in-with-twitter
到目前为止,我已经提出了-
require('dotenv').config();
const axios = require('axios');
const crypto = require('crypto');
const timestamp = new Date().getTime();
(async () => {
const nonce = crypto.randomBytes(32).toString('base64');
const signature = getNewSignature();
const params = {
oauth_callback: 'http://localhost:3000',
oauth_consumer_key: process.env.CONSUMER_KEY,
oauth_nonce: nonce,
oauth_signature: signature,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_token: process.env.ACCESS_TOKEN_KEY,
oauth_version: '1.0'
};
let headerString = 'OAuth ';
const headerStringParams = Object.keys(params);
for (let i = 0; i < headerStringParams.length; i++) {
const param = headerStringParams[i];
headerString += `${encodeURIComponent(param)}="${encodeURIComponent(params[param])}"`;
if (i < headerStringParams.length - 1) {
headerString += ', ';
}
}
try {
const result = await axios.post('https://api.twitter.com/oauth/request_token', {
headers: {
Authorization: headerString
}
});
console.log(result);
} catch (e) {
console.log(e.response);
}
})();
function getNewSignature() {
const nonce = crypto.randomBytes(32).toString('base64');
const params = {
include_entities: true,
oauth_consumer_key: process.env.CONSUMER_KEY,
oauth_nonce: nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_token: process.env.ACCESS_TOKEN_KEY,
oauth_version: '1.0'
};
let signatureString = '';
const paramKeys = Object.keys(params);
for (let i = 0; i < paramKeys.length; i++) {
const param = paramKeys[i];
signatureString += `${encodeURIComponent(param)}=${encodeURIComponent(params[param])}`;
if (i < paramKeys.length - 1) {
signatureString += '&';
}
}
const signatureBaseString = `${encodeURIComponent('POST')}&${encodeURIComponent('https://api.twitter.com/oauth/request_token')}&${encodeURIComponent(signatureString)}`;
const signingKey = `${encodeURIComponent(process.env.CONSUMER_SECRET)}&${encodeURIComponent(process.env.ACCESS_TOKEN_SECRET)}`;
const signature = crypto.createHmac('sha1', signingKey).update(signatureBaseString).digest('base64');
return signature;
}
返回的是{ code: 215, message: 'Bad Authentication data.' }
我显然做错了什么,我只需要一个人做个橡皮鸭,然后告诉我我哪里做错了!预先感谢