我正在尝试从 Twitter API 获取请求令牌,以便使用他的 Twitter 帐户登录用户,并且我不断收到“无法验证 oauth 签名和令牌”的 401 响应。我正在通过 PHP 执行此操作。我寻找了类似的问题,但显然我是唯一一个疯狂到没有图书馆从头开始做的人。
在他们的 API 文档中,他们谈论“百分比编码”在授权标头中发送的值,我正在使用 urlencode() 函数这样做,不确定它是否正确。
为了计算我使用 hash_hmac('SHA1', $signParameters, $hashKey) 的签名,也不确定它是否适合使用。
这是通过 cURL 生成的请求:
POST /oauth/request_token HTTP/1.1
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.soytumascota.com%2Ftwitter%2Fuser.php", oauth_consumer_key="MY_APP_KEY", oauth_nonce="0dde25902bde5f3b280f58ea642047cf", oauth_signature_method="HMAC_SHA1", oauth_timestamp="1334697987", oauth_version="1.0", oauth_signature="8313277875f20cd8a8631966a2ba273a5d13aeda"
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
我非常感谢您能提供的任何帮助,谢谢。
编辑:这是我到目前为止编写的代码。
<?php
DEFINE( 'CONSUMER_KEY', 'MY_APP_KEY' );
DEFINE( 'CONSUMER_SECRET', 'MY_APP_SECRET' );
$url = 'https://api.twitter.com/oauth/request_token';
//setting OAuth parameters
$Oauth = Array();
$Oauth['oauth_callback'] = 'http://www.soytumascota.com/twitter/user.php';
$Oauth['oauth_consumer_key'] = CONSUMER_KEY;
$Oauth['oauth_nonce'] = md5( $Oauth['oauth_callback'] . CONSUMER_KEY . time() );
$Oauth['oauth_signature_method'] = 'HMAC_SHA1';
$Oauth['oauth_timestamp'] = (string) time();
$Oauth['oauth_version'] = '1.0';
//signature and authorization header are calculated inside functions
$Oauth['oauth_signature'] = calculateSignature( 'POST', $url, $Oauth );
$authorization = getAuthorizationHeader( $Oauth );
ksort( $Oauth );
//setting and sending request using cURL
$curl_session = curl_init( $url );
curl_setopt( $curl_session, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_session, CURLOPT_POST, true );
curl_setopt( $curl_session, CURLINFO_HEADER_OUT, true );
curl_setopt( $curl_session, CURLOPT_HTTPHEADER, Array( 'Authorization: ' . $authorization ) );
$result = curl_exec( $curl_session );
function getAuthorizationHeader( $parameters )
{
$authorization = 'OAuth ';
$j = count( $parameters );
foreach( $parameters as $key => $val )
{
$authorization .= $key . '="' . urlencode( $val ) . '"';
if( $j-- > 1 )
{
$authorization .= ', ';
}
}
return $authorization;
}
function calculateSignature( $method, $url, $parameters, $accessToken = '' )
{
foreach( $parameters as $key => $val )
{
$foo = urlencode( $key );
unset( $parameters[$key] );
$parameters[$foo] = urlencode( $val );
}
ksort( $parameters );
$signBase = '';
$j = count( $parameters );
foreach( $parameters as $key => $val )
{
$signBase .= "{$key}={$val}";
if( $j-- > 1 )
{
$signBase .= '&';
}
}
$signBase = strtoupper( $method ) . '&' . urlencode( $url ) . '&' . urlencode( $signBase );
$signKey = urlencode( CONSUMER_SECRET ) . '&' . urlencode( $accessToken );
$signature = hash_hmac( 'SHA1', $signParameters, $hashKey);
return $signature;
}