Skip to content

Instantly share code, notes, and snippets.

@idancali
Created December 7, 2012 02:02
Show Gist options
  • Save idancali/4230143 to your computer and use it in GitHub Desktop.
Save idancali/4230143 to your computer and use it in GitHub Desktop.
StackMob PHP OAuth2 Client
function oauth_hmacsha1($key, $data) {
return base64_encode(hash_hmac('sha1', $data, $key, true));
}
function generateHeader()
{
$params = array ();
$method = "GET";
$uriAndQuery = "user";
$host = "api.stackmob.com";
$port = "80";
$timestamp = time();
$nonce = substr(number_format(hexdec(sha1(microtime(true).mt_rand(10000,90000))),0,'',''), 0, 17);
$normalizedRequest = $timestamp. "\n" .
$nonce . "\n" .
strtoupper($method) . "\n" .
"/" . $uriAndQuery . "\n" .
$host . "\n" .
$port . "\n\n";
echo $normalizedRequest . "<br><br>";
$mac = $this->oauth_hmacsha1($macKey, $normalizedRequest);
$header = 'MAC id="' . $accessToken . '",ts="' . $timestamp . '",nonce="' .$nonce .'",mac="' . $mac . '"';
echo $header . "<br><br>";
$api = new RestClient(array(
'base_url' => "http://api.stackmob.com",
'user_agent' => 'mobileapostle',
'headers' => array(
'Accept' => 'application/vnd.stackmob+json; version=0',
'X-StackMob-API-Key' => $api_key,
'X-StackMob-User-Agent' => 'mobileapostle',
'Authorization' => $header
),
'format' => ""));
if ($method == 'GET')
{
$result = $api->GET($uriAndQuery, $params);
$http_result_code = $result->info->http_code;
print_r($result);
}
}
@idancali
Copy link
Author

idancali commented Dec 7, 2012

yup :)

@idancali
Copy link
Author

idancali commented Dec 7, 2012

I've updated the gist with the oauth_hmacsha1 method.

@idancali
Copy link
Author

idancali commented Dec 7, 2012

the order of the method arguments are different in PHP, that's all

@idancali
Copy link
Author

idancali commented Dec 7, 2012

I figured it out, I had to remove the 'n' from the nonce when sending the header or add it when computing the hash. The nonce I was hashing was different than the nonce I was sending over.

I updated the gist, it now works!

Thanks for your help, Erick!

@ericktai
Copy link

ericktai commented Dec 7, 2012

Awesome!!!! Do you mind if I share this gist back in the forum?

@idancali
Copy link
Author

idancali commented Dec 7, 2012

sure, go ahead

@ericktai
Copy link

ericktai commented Dec 7, 2012

Thanks Dan, much appreciated.

@ericktai
Copy link

ericktai commented Dec 7, 2012

btw, saw you're in Toronto. Save me a hot dog. You guys have the best ones in the world. I used to grab some at "Mama's Best" on the UT campus when I was visiting - saw you went to UT. Hope you got to share the hot dog experience. They're amazing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment