@blog.justoneplanet.info

日々勉強

PHPとcurlでOAuthしてみる

Zendでもできるがベタに書いてみる。

<?php
$url              = 'http://example.org/';
$consumer_key     = '1235694568147893b0123b15';
$consumer_secret  = '663333123263456c8d789f58';
$version          = '1.0';
$signature_method = 'HMAC-SHA1';
$timestamp        = time();
$nonce            = (string)rand();
$realm            = 'realm';
$request_body     = array('hello' => 'world');

$body_hash   = urlencode(base64_encode(hash('SHA1', $request_body, true)));
$auth_header = sprintf(
    'OAuth realm="%s",oauth_body_hash="%s",oauth_consumer_key="%s",oauth_version="%s",oauth_timestamp="%d",oauth_nonce="%s",oauth_signature_method="%s",oauth_signature="%s',
    $realm,
    $body_hash,
    $consumer_key,
    $version,
    $timestamp,
    $nonce,
    $signature_method,
    urlencode(
        base64_encode(
            hash_hmac(
                'SHA1',
                'POST&' . urlencode($url) . '&' . urlencode(
                    "oauth_body_hash={$body_hash}&oauth_consumer_key={$consumer_key}&oauth_nonce={$nonce}&oauth_signature_method={$signature_method}&oauth_timestamp={$timestamp}&oauth_version=$version"
                ),
                $consumer_secret . '&',
                true
            )
        )
    )
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt(
    $ch,
    CURLOPT_HTTPHEADER,
    array(
        "Authorization: {$auth_header}"
    )
);
$result = curl_exec($ch);
curl_close($ch);

こんな感じ。

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment