略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: OAuth::fetch

2024-11-14

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch获取一个 OAuth 受保护的资源

说明

public OAuth::fetch(
    string $protected_resource_url,
    array $extra_parameters = ?,
    string $http_method = ?,
    array $http_headers = ?
): mixed

获取一个资源。

参数

protected_resource_url

OAuth 受保护资源的URL

extra_parameters

和资源请求一起发送的额外参数。

http_method

OAUTH_HTTP_METHOD_* 系列 OAUTH 常量之一,GET、POST、PUT、HEAD 或 DELETE 其中的一个。

HEAD (OAUTH_HTTP_METHOD_HEAD )可以用于先于请求发现信息(如果 OAuth 证书在 Authorization 头部)。

http_headers

HTTP 客户端头信息(像 User-Agent, Accept 等等这样的)。

返回值

成功时返回 true, 或者在失败时返回 false

更新日志

版本 说明
1.0.0 以前失败时返回 null,而不是 false
0.99.5 新增 http_method 参数
0.99.8 新增 http_headers 参数

范例

示例 #1 OAuth::fetch() example

<?php
try {
    
$oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    
$oauth->setToken("access_token","access_token_secret");

    
$oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

    
$response_info $oauth->getLastResponseInfo();
    
header("Content-Type: {$response_info["content_type"]}");
    echo 
$oauth->getLastResponse();
} catch(
OAuthException $E) {
    echo 
"Exception caught!\n";
    echo 
"Response: "$E->lastResponse "\n";
}
?>

参见

add a noteadd a note

User Contributed Notes 6 notes

up
6
chris dot barr at ntlworld dot com
9 years ago
The fetch() method will throw an OAuthException if the returned http status code is in the 4xx or 5xx range:

<?php
// Querying Twitter with bad login details
try {
 
$oauth->fetch('https://api.twitter.com/1.1/favorites/list.json');
}
catch(
Exception $e) {
  echo
$e->getCode(); // 401
  // Message generated by OAuth class
 
echo $e->getMessage(); // Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
  // Message returned from Twitter
 
echo $e->lastResponse; // {"errors":[{"message":"Could not authenticate you","code":32}]}
}
up
2
sun at drupal dot org
10 years ago
Make sure that your $extra_parameters is an array.

If it's not, then OAuth will silently skip the malformed data type and produce a signature base string that is invalid (doesn't contain POST parameters, as defined in the RFC).

You should file a critical bug report against any REST API you find in the wild that accepts such a bogus signature to pass authentication.
up
3
contact info at mech dot cx
11 years ago
I was having troubles getting fetch() to post, the remote server (Twitter, in this case) complained at me that their "resource only supports POST". Turned out to be a known bug in OAuth 1.1, downgrading to 1.0 fixed it.

Don't lose as much time over this as I did :-)
up
3
zverik at textual dot ru
8 years ago
If $extra_parameters is not an array, you have to specify Content-Type header, or else you'll get HTTP 401 error. Example:

<?php
$oauth
->fetch(ENDPOINT, '{"action": "get_user_info"}', OAUTH_HTTP_METHOD_PUT, array('Content-Type' => 'application/json'));
?>
up
1
Lars Stttrup Nielsen
6 years ago
So I'm using this to talk to the Woocommerce REST API, and was having a lot of trouble figuring out what exactly $extra_parameters was supposed to look like (which WC REST API expects, besides being of the type OAUTH_AUTH_TYPE_URI).

The multidimensional array I fed it crashed PHP, so don't do that if you're in my shoes.

What ended up solving it was me looking through the OAuth source and noticing that $extra_parameters can also be a string, which, encoded as json (json_encode), solved all my troubles as WC accepted it.
up
0
Lyuben Penkovski (l_penkovski at yahoo dot com)
11 years ago
If the provider's web server is configured to use Keep-Alive extension to HTTP protocol (HTTP 1.1), there can be a big delay in the response time from the provider. By default Apache is configured to use Keep-Alive for 5 seconds. This is the delay after which the response will come back to the consumer. If you have this issue of delayed result, you can pass in HTTP headers when calling $consumer->fetch():

<?php
$consumer
= new OAuth("consumer_key", "consumer_secret", OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
$consumer->fetch('http://example.com/api/', null, OAUTH_HTTP_METHOD_POST, array('Connection'=>'close'));
?>

Then the provider will send the result immediately after it's ready with the processing and the connection will be closed. Unfortunately, when calling $consumer->getRequestToken() and $consumer->getAccessToken() there's no way provided to pass in HTTP headers and this delay (if present) cannot be avoided, or at least we could not find a way to avoid it.

The solution that worked for us is to send this header from the provider when returning result to the consumer:

<?php
$result
= 'oauth_callback_accepted=true&oauth_token=' . $this->urlencode($token->oauth_token) .
         
'&oauth_token_secret='.$this->urlencode($token->oauth_token_secret);

header('HTTP/1.1 200 OK');
header('Content-Length: '.strlen($result));
header('Content-Type: application/x-www-form-urlencoded');
header('Connection:close');
echo
$result;
?>

This can work if you have the possibility to modify the code of the provider, e.g. if you are the provider yourself or if you can talk with the people that develop it and ask them to send this header for your request.

官方地址:https://www.php.net/manual/en/oauth.fetch.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3