我正在尝试将Twitter登录与Twitter API集成在一起。当我尝试请求OAuth令牌时,我收到400状态代码(215 Twitter代码),并且对原因感到mb目结舌。我将API文档放在T后面。
这是我关注的文档的链接:
Implementing Sign in with Twitter
这是我的代码:
const http_method = 'POST';
const base_url = 'https://api.twitter.com/oauth/request_token';
const oauth_callback = 'http://127.0.0.1:5000';
const oauth_consumer_key = 'consumerKey';
const oauth_consumer_secret = 'consumerSecret';
const oauth_nonce = crypto
.randomBytes(32)
.toString('ascii')
.replace(/\W/g, '');
const oauth_signature_method = 'HMAC-SHA1';
const oauth_signing_key = encodeURIComponent(oauth_consumer_secret) + '&';
const oauth_timestamp = Math.round(new Date().getTime() / 1000.0);
const oauth_version = '1.0';
// Normalized parameter string
const parameter_string =
encodeURIComponent('oauth_callback') +
'=' +
encodeURIComponent(oauth_callback) +
'&' +
encodeURIComponent('oauth_consumer_key') +
'=' +
encodeURIComponent(oauth_consumer_key) +
'&' +
encodeURIComponent('oauth_nonce') +
'=' +
encodeURIComponent(oauth_nonce) +
'&' +
encodeURIComponent('oauth_signature_method') +
'=' +
encodeURIComponent(oauth_signature_method) +
'&' +
encodeURIComponent('oauth_timestamp') +
'=' +
encodeURIComponent(oauth_timestamp) +
'&' +
encodeURIComponent('oauth_token') +
'=' +
'' +
'&' +
encodeURIComponent('oauth_version') +
'=' +
encodeURIComponent(oauth_version);
// Create signature string
const signature_string =
encodeURIComponent(http_method) +
'&' +
encodeURIComponent(base_url) +
'&' +
encodeURIComponent(parameter_string);
// Create OAuth signature
const oauth_signature = crypto
.createHmac('sha1', oauth_signing_key)
.update(signature_string)
.digest('base64');
// Header parameter string
const oauth_header_string =
'OAuth ' +
encodeURIComponent('oauth_callback') +
'=' +
'"' +
encodeURIComponent(oauth_callback) +
'"' +
', ' +
encodeURIComponent('oauth_consumer_key') +
'=' +
'"' +
encodeURIComponent(oauth_consumer_key) +
'"' +
', ' +
encodeURIComponent('oauth_nonce') +
'=' +
'"' +
encodeURIComponent(oauth_nonce) +
'"' +
', ' +
encodeURIComponent('oauth_signature') +
'=' +
'"' +
encodeURIComponent(oauth_signature) +
'"' +
', ' +
encodeURIComponent('oauth_signature_method') +
'=' +
'"' +
encodeURIComponent(oauth_signature_method) +
'"' +
', ' +
encodeURIComponent('oauth_timestamp') +
'=' +
'"' +
encodeURIComponent(oauth_timestamp) +
'"' +
', ' +
encodeURIComponent('oauth_version') +
'=' +
'"' +
encodeURIComponent(oauth_version) +
'"';
// Request OAuth Token
axios
.post(base_url, {
headers: {
Authorization: oauth_header_string,
},
})
.then(res => console.log(res))
.catch(console.error);
谢谢您的帮助!