自己解決しました.参考までに.
<?php
ini_set('display_errors', 1);
require '../config/config.php';
class hatena
{
public $oauthCallback = OAUTH_CALLBACK;
public $oauthConsumerKey = OAUTH_CONSUMER_KEY;
public $oauthConsumeSecret = OAUTH_CONSUMER_SECRET;
public $oauthToken = '';
public $oauthTokenSecret = '';
public $oauthSignature = '';
public $oauthParameters = [];
public function oauthInitiate($method = "POST", $url = 'https://www.hatena.com/oauth/initiate', $contentType = 'application/x-www-form-urlencoded')
{
$this->oauthParameters = [
'oauth_callback' => $this->oauthCallback,
'oauth_consumer_key' => $this->oauthConsumerKey,
'oauth_nonce' => uniqid(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
];
$params = [
'scope' => 'read_public,write_public'
];
$this->getSignature($url, $method, $params);
$authorization = $this->getPostParam($this->oauthParameters, true, ',');
$headers = [
'Authorization: OAuth ' . $authorization,
'Host' => 'www.hatena.com',
'User-Agent: '=>$_SERVER['HTTP_USER_AGENT'],
'Content-Type: ' . $contentType,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params, '', '&', PHP_QUERY_RFC3986));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($ch);
if (curl_error($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
//oauth_token=?????oauth_token_secret=?????&oauth_callback_confirmed=true
parse_str($response, $responseParams);
header('Location:https://www.hatena.ne.jp/oauth/authorize?oauth_token='.rawurlencode($responseParams['oauth_token']));
return $this;
}
public function getSignature($url, $method = 'POST', $params = [], $oauthTokenSecret = '')
{
$base_string = implode('&', array(
rawurlencode($method),
rawurlencode($url),
rawurlencode(http_build_query($this->oauthsort(array_merge($this->oauthParameters, $params)), '', '&', PHP_QUERY_RFC3986))
));
$key = implode('&', array(rawurlencode($this->oauthConsumeSecret), rawurlencode($oauthTokenSecret)));
$this->oauthParameters['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_string, $key, true));
ksort($this->oauthParameters);
return $this;
}
//OAuth式 パラメータのソート関数
public function oauthsort($a)
{
$b = array_map(null, array_keys($a), $a);
usort($b, ['hatena', 'oauthcmp']);
$c = array();
foreach ($b as $v) {
$c[$v[0]] = $v[1];
}
return $c;
}
public function oauthcmp($a, $b)
{
return strcmp($a[0], $b[0])
? strcmp(rawurlencode($a[0]), rawurlencode($b[0]))
: strcmp(rawurlencode($a[1]), rawurlencode($b[1]));
}
public function getPostParam($value, $rawurlencodeSwitch = false, $separator = '&')
{
$str = [];
foreach ($value as $key => $val) {
$val = $rawurlencodeSwitch ? rawurlencode($val) : $val;
$str[] = $key . '=' . $val . '';
}
return implode($separator, $str);
}
}
(new hatena)->oauthInitiate();
0Like