0

Following code from other posts: Twitter 1.1 OAuth authenticity_token_error(99), https://gist.github.com/lgladdy/5141615 <-- Life saver and others.

I've made sure that: - I am logged out of Twitter. - Request contains all that it needs. - I have CORS enabled via chrome plugin. - Base64 encoded keys match.

I still get "code":99,"message":"Unable to verify your credentials". I can reproduce this 99 error when I change any parameter in the request with CURL and PHP. So something must be wrong with the React code. I could not find a javascript working version of the code around.

Curl works:

curl --request 'POST' 'https://api.twitter.com/oauth2/token' --header 'Authorization: Basic ENCODED_KEY+ENCODED_SECRET, Content-Type: "application/x-www-form-urlencoded;charset=UTF-8"' --data "grant_type=client_credentials" --verbose

PHP - document works:

<?php
//This is all you need to configure.
$app_key = 'KEY';
$app_token = 'SECRET';
//These are our constants.
$api_base = 'https://api.twitter.com/';
$bearer_token_creds = base64_encode($app_key.':'.$app_token);
//Get a bearer token.
$opts = array(
  'http'=>array(
    'method' => 'POST',
    'header' => 'Authorization: Basic '.$bearer_token_creds."\r\n".
               'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
    'content' => 'grant_type=client_credentials'
  )
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'oauth2/token',false,$context);
$result = json_decode($json,true);
if (!is_array($result) || !isset($result['token_type']) || !isset($result['access_token'])) {
  die("Something went wrong. This isn't a valid array: ".$json);
}
if ($result['token_type'] !== "bearer") {
  die("Invalid token type. Twitter says we need to make sure this is a bearer.");
}
//Set our bearer token. Now issued, this won't ever* change unless it's invalidated by a call to /oauth2/invalidate_token.
//*probably - it's not documentated that it'll ever change.
$bearer_token = $result['access_token'];
//Try a twitter API request now.
$opts = array(
  'http'=>array(
    'method' => 'GET',
    'header' => 'Authorization: Bearer '.$bearer_token
  )
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'1.1/statuses/user_timeline.json?count=1&screen_name=lgladdy',false,$context);
$tweets = json_decode($json,true);
echo "@lgladdy's last tweet was: ".$tweets[0]['text']."\r\n";
echo $bearer_token_creds;

?>

React 99 error:

var R = require('request'); //default React
    var consumer_key = 'KEY';
    var consumer_secret = 'SECRET';
    var encode_secret = new Buffer(consumer_key + ':' + consumer_secret).toString('base64');
    console.log('encode_secret', encode_secret)
R({
      url: 'https://api.twitter.com/oauth2/token',
      method: 'POST',
      header: {
        'Authorization': 'Basic ' + encode_secret,
        'Content-Type': "application/x-www-form-urlencoded;charset=UTF-8"
      },
      content: "grant_type=client_credentials"

    }, function (err, resp, body) {

      console.log("B1", body); // <<<< This is your BEARER TOKEN !!
      console.log("R1", resp);
      console.log("E1", err);
    });

Can someone help?

ben_lize
  • 107
  • 9

1 Answers1

1
  • data should be a string not an object.
  • client doesn't support because of CORS, even CORS chrome extension doesn't work.
  • below is the working Node JS code.

Working Node JS code:

const http = require('http');
const axios = require('axios');


http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });

  var consumer_key = 'YOUR_KEY';
  var consumer_secret = 'YOUR_SECRET';
  var encode_secret = new Buffer(consumer_key + ':' + consumer_secret).toString('base64');

  var url = "https://api.twitter.com/oauth2/token"

  var data = "grant_type=client_credentials"

  var options = {
    headers: {
      'Authorization': 'Basic ' + encode_secret,
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    }  
  };

  axios.post(url,data,options)
  .then(result => console.log("success", result))
  .catch(error => console.log("error", error))

}).listen(8080);
ben_lize
  • 107
  • 9