Authentication no longer works after GET to POST change
Asked Answered
S

1

9

I used the PHP code below to successfully get the timeline of a Twitter user (REST API / OAuth 1.0a) Now I would like to follow a user on Twitter. I needed to change the GET to a POST request for it and now the code no longer works. Error:

[code] => 32 [message] => Could not authenticate you.

What needs to be changed to make it work?

PHP:

// ("x" = I removed the values)
$token = "x";
$token_secret = "x"; 
$consumer_key = "x";
$consumer_secret = "x";

$host = 'api.twitter.com';
/*
// NOT WORKING:
$method = 'POST';
$path = '/1.1/friendships/create.json'; // api call path
*/

// WORKS:
$method = 'GET'; 
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitter',
    //'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);
print_R($twitter_data);
?>
Sassy answered 30/6, 2015 at 9:7 Comment(5)
You should award the bounty if the answer answers your question.Hebdomadary
@kelunik: In five minutes, it is lost...Developer
@RichardReiber: In 21 hours, but I just read it's fully awarded for accepted answers.Hebdomadary
@kelunik: But you can award it manually ;-)Developer
@RichardReiber: Yes, you can, but that way you could still change your opinion and award it to another answer, if there comes up a better one during that period. It makes some sense, at least you can't forget to award it, because it will be awarded automatically.Hebdomadary
H
8

You specified the method being used for the signature, but you didn't actually make a POST request.

You have to set curl_setopt($feed, CURLOPT_POST, true) and curl_setopt($feed, CURLOPT_POSTFIELDS, $query) instead of adding your parameters to the URL as query string.

For more information about POST requests with CURL, visit the documentation page. It's a file upload there, but the only difference is the @ that you have to drop.

Note: If Twitter requires the data to be in application/x-www-form-urlencoded format, you have to use http_build_query instead of passing an array for the CURLOPT_POSTFIELDS option.

Hebdomadary answered 2/7, 2015 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.