这是我第一次使用OAuth而且我创建了下面部分有效的类!我跟着this manual。
方法methodGet()
和methodPost()
工作正常methodPatch()
返回“HTTP 401 Unauthorized error”。终点需要一个PATCH
请求方法,因为is no constant中的PATCH
OAuth class,我正在尝试发送POST
请求并尝试覆盖它带有一个额外的X-Http-Method-Override
标题,以便在场景后面it becomes PATCH
方法(可能不是!!!)。那就是问题,我无法修补它!
因为它很可能与PATCH
(GET和POST工作正常)有关,有没有人知道它的解决方案或我错过了其他的东西?
注意:我可以确认终点工作正常,所以那边没有问题。
提前致谢
use Exception;
use OAuth;
use OAuthException;
class ApiClient
{
// End-point accepts GET request - This works fine
public function methodGet()
{
return $this->call(
OAUTH_HTTP_METHOD_GET,
array('id' => 123)
);
}
// End-point accepts POST request - This works fine
public function methodPost()
{
return $this->call(
OAUTH_HTTP_METHOD_POST,
array('name' => 'inanzzz')
);
}
// End-point accepts PATCH request - This returns HTTP 401 Unauthorized
public function methodPatch()
{
return $this->call(
OAUTH_HTTP_METHOD_POST,
array('id' => 123, 'name' => 'inanzzz123'),
['X-Http-Method-Override' => 'PATCH']
);
}
private function call($method, $params = array(), $headers = array())
{
try {
$oAuth = new OAuth('api_key_goes_here', 'api_secret_goes_here');
$oAuth->setNonce(md5(uniqid(mt_rand(), true)));
$oAuth->setTimestamp(time());
$oAuth->setVersion('1.0');
$oAuth->fetch(
'http://api.domain.com/1/products/service.json',
$params, $method, $headers
);
return json_decode($oAuth->getLastResponse(), true);
} catch (OAuthException $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
}
}
答案 0 :(得分:0)
解决方案是使用Guzzle Client,方法如下:
注意:$authHeader
拥有$oauth->getRequestHeader(...);
,因此您可以生成它并将其传递给方法。
private function call($uri, $method, $authHeader, array $payload = [])
{
try {
$client = new Client();
$request = $client->createRequest($method, $uri);
$request->addHeader('Authorization', $authHeader);
$request->addHeader('Content-Type', 'application/json');
$request->setBody(Stream::factory(json_encode($payload)));
$response = $client->send($request);
} catch (RequestException $e) {
$message = $e->hasResponse()
? $e->getResponse()
: 'An unknown error occurred while trying to process your request.';
throw new Exception($message);
}
return json_decode($response->getBody(), true);
}