N
N
Nikolai Stupak2016-08-12 16:12:20
PHP
Nikolai Stupak, 2016-08-12 16:12:20

How to get Twitter API request_token?

Help me figure out how to get Twitter's request_token.
I'm trying to login using the following code:

//вспомогательная функция для заворачивания строки в кавычки
  function quoted($string) {
    return '"'.$string.'"';
  }

  //вспомогательная функция для оправки запросов
  function doPost($url, $data, $headers) {
    $request = curl_init();
    curl_setopt_array($request, array(
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false
    ));

    if ( isset($data) ) {
      $queryData = http_build_query($data);
      curl_setopt($request, CURLOPT_POSTFIELDS, $queryData);

      echo 'queryData='.$queryData.'<br><br>';
    }

    if ( isset($headers) && is_array($headers) ) {
      $preparedHeaders = array();
      foreach ($headers as $header => $value) {
        $preparedHeaders[] = $header.': '.$value;
      }

      curl_setopt($request, CURLOPT_HTTPHEADER, $preparedHeaders);
    }

    $response = curl_exec($request);

    if (curl_errno($request)) { 
      echo 'errors: <br>';
       	print curl_error($request); 
    } 

    curl_close($request);

    return $response;
    }

    $URL_SEPARATOR 		= '&';
    $REQUEST_TOKEN_URL 	= 'https://api.twitter.com/oauth/request_token';

    $redirectUri 		= 'http://megafon.webformula.pro/auth';
    $clientKey 			= 'oYt3vRbHEbz0OhfK23DDFlGjJ';
    $clientSecret 		= 'blabla'

  // хэш случайной строки
  $oauth_nonce = md5(uniqid(rand(), true));
  
  // текущее время
  $oauth_timestamp = time();
  
  // формируем набор параметров
  $signatureParams = array(
    'POST',
    // 'GET',
    REQUEST_TOKEN_URL,
    'oauth_callback='.			$redirectUri,
    'oauth_consumer_key='.		$clientKey,
    'oauth_nonce='.				$oauth_nonce,
    'oauth_signature_method='.	'HMAC-SHA1',
    'oauth_timestamp='.			$oauth_timestamp,
    'oauth_version='.			'1.0',
  );

  // склеиваем все параметры, применяя к каждому из них функцию urlencode
  $oauth_base_text = implode(URL_SEPARATOR, array_map('urlencode', $signatureParams));
  
  echo 'oauth_base_text='.$oauth_base_text.'<br><br>';

  $key = $clientSecret . URL_SEPARATOR;
  
  // хэшируем с помощью алгоритма sha1
  $oauth_signature = base64_encode(hash_hmac('sha1', $oauth_base_text, $key, true));

  echo 'oauth_signature='.$oauth_signature.'<br><br>';
  
  //2. Формирование токена запроса (request token)
  //Теперь формируем строку параметров из тех же данных, которые использовались для формирования подписи запроса:

  // создаем хедер Authorization
  $authorizationHeader = 'OAuth '.implode(', ', array(
    'oauth_callback='.quoted(urlencode($redirectUri)),
    'oauth_consumer_key='.quoted(urlencode($clientKey)),
    'oauth_nonce='.quoted(urlencode($oauth_nonce)),
    'oauth_signature='.quoted(urlencode($oauth_signature)),
    'oauth_signature_method='.quoted('HMAC-SHA1'),
    'oauth_timestamp='.quoted(urlencode($oauth_timestamp)),
    'oauth_version='.quoted('1.0'),
  ));

  echo 'authorizationHeader='.$authorizationHeader.'<br><br>';

  // готовим массив параметров
  $params = array(
    'oauth_callback'			=> urlencode($redirectUri),
    'oauth_consumer_key'		=> urlencode($clientKey),
    'oauth_nonce'				=> $oauth_nonce,
    'oauth_signature'			=> urlencode($oauth_signature),
    'oauth_signature_method'	=> 'HMAC-SHA1',
    'oauth_timestamp'			=> $oauth_timestamp,
    'oauth_version'				=> '1.0',
  );
   
  $headers = array(
    "Authorization" => $authorizationHeader,
    "Content-Type"  => 'application/x-www-form-urlencoded',
  );
  
  // Отправляем запрос для генерации request_token по сформированному url
  $response = doPost(REQUEST_TOKEN_URL, $params, $headers);

  echo 'response='.$response.'<br><br>';

As a result, I get this output
oauth_base_text=GET&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%3A%2F%2Fmegafon.webformulapro%2Fauth&oauth_consumer_key%3DoYt3vRbHEbz0OhfK23DDFlGjJ&oauth_nonce%3De5135f56531b818ceb06a9e9644de175&oauth_signature_method%3DHMAC-SHA1&oauth_timestamp%3D1471006352&oauth_version%3D1.0

oauth_signature=0hRF6G6M/RTaF1QWiZleWY3sWjg=

authorizationHeader=OAuth oauth_callback="http%3A%2F%2Fmegafon.webformula.pro%2Fauth", oauth_consumer_key="oYt3vRbHEbz0OhfK23DDFlGjJ", oauth_nonce="e5135f56531b818ceb06a9e9644de175", oauth_signature="0hRF6G6M%2FRTaF1QWiZleWY3sWjg%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1471006352", oauth_version="1.0"

queryData=oauth_callback=http%253A%252F%252Fmegafon.webformula.pro%252Fauth&oauth_consumer_key=oYt3vRbHEbz0OhfK23DDFlGjJ&oauth_nonce=e5135f56531b818ceb06a9e9644de175&oauth_signature=0hRF6G6M%252FRTaF1QWiZleWY3sWjg%253D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1471006352&oauth_version=1.0

responce={"errors":[{"code":32,"message":"Could not authenticate you."}]}

Tell me, what's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2016-08-12
@nikolaas

Why did people try?
https://github.com/abraham/twitterauth

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question