This is the first time I'm using OAuth and I created the class below which partially works! I followed this manual .
Methods methodGet()
and methodPost()
work fine however methodPatch()
returns "HTTP 401 Unauthorized error". End-point expects a PATCH
request method and since there is no constant for PATCH
in OAuth class , I'm trying to send a POST
request and trying to override it with an extra X-Http-Method-Override
header so that it becomes a PATCH
method behind the scene (may be not!!!). That's the problem, I cannot PATCH it!
As it is highly likely to do with PATCH
(GET and POST work fine), does anyone know a solution to it or am I missing something else?
Note: I can confirm that the end-point works fine so there is no problem at that side.
Thanks in advance
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());
}
}
}
Solution was to use Guzzle Client so the method is below:
Note: $authHeader
holds $oauth->getRequestHeader(...);
so you can generate it and pass it to the method.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.