Как вы получаете успешный ответ от POST oauth / request_token в API Twitter? - PullRequest
0 голосов
/ 19 июня 2019

Мне не повезло, пытаясь получить успешный ответ от 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.' }

ЯЯ явно делаю что-то не так, и мне просто нужен кто-то, чтобы быть резиновой уткой и сказать мне, где я ошибся!Заранее спасибо

...