这是我第一次使用OAuth,并且创建了下面的部分起作用的类!我遵循了本手册。
方法methodGet()
和methodPost()
工作正常,但是methodPatch()
返回“ HTTP 401未经授权的错误”。点完需要一个PATCH
请求方法和因为没有固定的PATCH
在OAuth的类,我试图发送一个POST
请求,并试图用额外的覆盖它X-Http-Method-Override
,这样头就变成一个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());
}
}
}
解决方案是使用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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句