'Having trouble creating an OAuth 1.0 signature for Twitter's API in PHP
I want to make a GET request to Twitter's API from PHP and obtain a user's tweets. For this, I need to construct the Authorization header, but I'm stuck on what to do with the signature. This is my code so far:
$url = $this->api_domain . "2/users/" . $this->user_id . "/tweets?exclude=retweets&expansions=attachments.media_keys&media.fields=url";
$timestamp = time();
$nonce = md5(microtime() . mt_rand());
$signature_params = array(
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => $nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $timestamp,
'oauth_token' => $this->oauth_token,
'oauth_verifier' => $this->oauth_verifier,
'oauth_version' => '1.0'
);
uksort($signature_params, 'strcmp');
foreach($signature_params as $key => $value)
{
$signature_params[$key] = rawurlencode($key) . '=' . rawurlencode($value);
}
$signatureBase = array(
rawurlencode('GET'),
rawurlencode($url),
rawurlencode(implode('&', $signature_params))
);
$signatureBaseString = implode('&', $signatureBase);
$signatureKey = array(rawurlencode($this->consumer_secret), rawurlencode($this->oauth_token_secret));
$signatureKeyString = implode('&', $signatureKey);
$signature = base64_encode(hash_hmac('sha1', $signatureBaseString, $signatureKeyString, true));
$signature = urlencode($signature);
$headers = array(
'Authorization: OAuth oauth_consumer_key="' . $this->consumer_key . '",oauth_token="' . $this->oauth_token . '",oauth_signature_method="HMAC-SHA1",oauth_timestamp="' . $timestamp . '",oauth_nonce="' . $nonce . '",oauth_version="1.0",oauth_verifier="' . $this->oauth_verifier . '",oauth_signature="' . $signature . '"'
);
// run curl command
If I try to make a curl request with this $headers array, I always get an Unauthorized error. I'm pretty sure it's because I'm messing up on the signature somehow, because so far I've made other requests that didn't require the signature key to contain the OAuth Token Secret, and those worked fine. According to the the documentation, I just need to URL encode the consumer secret and token secret, and join them with an '&'. After that, base64 encode, and it should work. That's what I did, but their API doesn't seem to like what I'm sending it... I can't figure out where I messed up, does anyone have any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
