【发布时间】:2021-02-24 14:33:36
【问题描述】:
我正在尝试使用 PHP 7.4 在网络服务器上发出 Twitter verify_credentials 请求。
只有当我像这样在 Postman 中设置 OAuth1.0 请求标头设置时,我才会收到 http 200 代码和正确响应:
使用相同数据发出请求的任何其他方式都会向我返回一个带有 401 http 状态代码的错误
{"errors":[{"code":32,"message":"Could not authenticate you."}
我需要在 GUZZLE 的 PHP CURL 或其他 http 请求客户端代码中转换此 Postman 设置。但是当我从 Postman 导入 CURL 示例时,它总是抛出相同的 401 异常。所以我尝试了不同的方法:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.twitter.com/1.1/account/verify_credentials.json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: OAuth oauth_consumer_key=\"oauth_consumer_key\",oauth_token=\"oauth_token\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1605187800\",oauth_nonce=\"hmkiezWh6xqlfJYpK55rDVgcGydQkuBH\",oauth_version=\"1.0\",oauth_callback=\"http%3A%2F%2Fmyurl.com\",oauth_signature=\"signature\""
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
或者另一个:
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$client = new Client;
$headers =[
'Authorization' => 'OAuth oauth_consumer_key="oauth_consumer_key",oauth_token="oauth_token",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1605187800",oauth_nonce="hmkiezWh6xqlfJYpK55rDVgcGydQkuBH",oauth_version="1.0",oauth_callback="http%3A%2F%2Furl.com",oauth_signature="SdB60Nr6AhJzOdAIWlW%2FwdmeJM4%3D"',
];
$request = new Request('GET', 'https://api.twitter.com/1.1/account/verify_credentials.json', $headers);
$client->send($request);
$response = $client->getResponse();
echo $response->getBody();
或者那样:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/1.1/account/verify_credentials.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Authorization: OAuth oauth_consumer_key=\"oauth_consumer_key\",oauth_token=\"oauth_token\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1605187800\",oauth_nonce=\"hmkiezWh6xqlfJYpK55rDVgcGydQkuBH\",oauth_version=\"1.0\",oauth_callback=\"http%3A%2F%2Furl.com\",oauth_signature=\"H%2FpmcdPUnlMD8RN42RpfBs%2Fs7Cc%3D\"';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
每次都会收到 401 错误。那么,如何在 PHP CURL 中设置所有 OAuth1.0 属性,以在 Postman 中使用相同的标头重现相同的请求?
附:我已经尝试过 abraham/twitteroauth、laravel/socialite 和其他解决方案,结果相同
【问题讨论】:
-
以下答案对您有用吗?
标签: php oauth twitter-oauth guzzle php-curl