Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ A `cURL error 60` means PHP cannot find a CA bundle that trusts the API certific

All the API responses that do not fall in the 2** status codes, the SDK will throw a `CheckoutApiException`.

The exception encapsulates `http_metadata` and `$error_details`, if available.
The exception encapsulates `http_metadata` (status, reason phrase and response headers, cookies excluded) and `$error_details`, if available.

A request argument that cannot be sent as given (for example an empty id, or a query filter value that is not a string, number, boolean or `DateTime`) throws a `CheckoutArgumentException` before any request is sent. Both exceptions extend `CheckoutException`: catch `CheckoutException` to handle the two.

Expand Down
12 changes: 7 additions & 5 deletions lib/Checkout/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ private function submit(
string $multipart
): array {
try {
$this->logger->info("POST " . $path . " file: " . $fileRequest->file);
$this->logger->info("POST " . $path);
$headers = $this->getHeaders($authorization, null, null);

// Provide a stream with explicit size so Guzzle can set Content-Length correctly.
Expand All @@ -234,11 +234,12 @@ private function submit(
]);
return $this->getResponseContents($response);
} catch (\Throwable $e) {
$this->logger->error($path . " error: " . CheckoutUtils::describeFailure($e));
$description = CheckoutUtils::describeFailure($e);
$this->logger->error($path . " error: " . $description);
if ($e instanceof RequestException) {
throw CheckoutApiException::from($e);
}
throw new CheckoutApiException(CheckoutUtils::describeFailure($e));
throw new CheckoutApiException($description);
}
}

Expand Down Expand Up @@ -298,11 +299,12 @@ private function invoke(
]);
return $this->getResponseContents($response);
} catch (\Throwable $e) {
$this->logger->error($path . " error: " . CheckoutUtils::describeFailure($e));
$description = CheckoutUtils::describeFailure($e);
$this->logger->error($path . " error: " . $description);
if ($e instanceof RequestException) {
throw CheckoutApiException::from($e);
}
throw new CheckoutApiException(CheckoutUtils::describeFailure($e));
throw new CheckoutApiException($description);
}
}

Expand Down
83 changes: 70 additions & 13 deletions lib/Checkout/CheckoutApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,94 @@
namespace Checkout;

use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;

class CheckoutApiException extends CheckoutException
{
/**
* @var array
* @var array|string|int|float|bool|null the decoded JSON body of the response, usually an
* array (a JSON scalar decodes to its value); an empty array when there is no response or
* its body cannot be read, null when the body is not JSON
*/
public $error_details;
/**
* @var HttpMetadata
* @var HttpMetadata|null the reason phrase, status code, headers (cookies excluded) and
* protocol version of the response; null when there is none or it cannot be read
*/
public $http_metadata;

/**
* @param RequestException $requestException
* @return CheckoutApiException
* @param RequestException $requestException a failed request of the HTTP client
* @return CheckoutApiException with the response status in its message, or the failure's own
* code when there is no readable response (0 for the HTTP client's own errors), the
* response body in error_details and the response metadata in http_metadata
*/
public static function from(
#[\SensitiveParameter]
RequestException $requestException
) {
$response = $requestException->getResponse();

$response = CheckoutUtils::responseOf($requestException);
$status = CheckoutUtils::statusOf($response);
if ($status === null) {
$code = $requestException->getCode();
$status = is_int($code) ? $code : 0;
}
$ex = new CheckoutApiException(sprintf(
"The API response status code (%s) does not indicate success.",
$requestException->getCode()
"The API response status code (%d) does not indicate success.",
$status
));
$ex->error_details = isset($response)
? json_decode($response->getBody()->getContents(), true)
: [];
$ex->http_metadata = CheckoutUtils::getHttpMetadata($response);

$body = CheckoutUtils::bodyOf($response);
$ex->error_details = $body === null ? [] : json_decode($body, true);
$ex->http_metadata = self::metadataWithoutCookies($response);
return $ex;
}

/**
* Builds the metadata of a failed response, without its cookies.
*
* @param ResponseInterface|null $response the response of the failed request, if any
* @return HttpMetadata|null the reason phrase, status code, headers without Set-Cookie and
* protocol version; null when there is no response or it cannot be read
*/
private static function metadataWithoutCookies(

Check warning on line 55 in lib/Checkout/CheckoutApiException.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This method has 4 returns, which is more than the 3 allowed.

See more on https://sonarcloud.io/project/issues?id=checkout_checkout-sdk-php&issues=AaI7aewI5Zod1_kY8YtE&open=AaI7aewI5Zod1_kY8YtE&pullRequest=429
#[\SensitiveParameter]
?ResponseInterface $response
) {
if ($response === null) {
return null;
}
try {
$headers = array_filter($response->getHeaders(), function ($name) {
return !in_array(self::plainHeaderName($name), ["set-cookie", "set-cookie2"], true);
}, ARRAY_FILTER_USE_KEY);
$reason = $response->getReasonPhrase();
$status = $response->getStatusCode();
$protocol = $response->getProtocolVersion();
// Implementations without return types (psr/http-message 1.0) may return anything.
if (!is_string($reason) || !is_int($status) || !is_string($protocol)) {
return null;
}
return new HttpMetadata($reason, $status, $headers, $protocol);
} catch (\Throwable $unreadable) {
return null;
}
}

/**
* @param mixed $name a header name
* @return string the name in lower case with only its letters, digits and hyphens, so padding,
* control or format characters that a lenient PSR-7 implementation leaves in it do not hide
* which header it is
*/
private static function plainHeaderName($name)
{
$plain = "";
foreach (str_split(strtolower((string)$name)) as $character) {
if (($character >= "a" && $character <= "z") || ($character >= "0" && $character <= "9")
|| $character === "-") {
$plain .= $character;
}
}
return $plain;
}
}
79 changes: 77 additions & 2 deletions lib/Checkout/CheckoutUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use DateTime;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;

class CheckoutUtils
{
Expand Down Expand Up @@ -97,6 +98,79 @@ public static function getHttpMetadata(?Response $http_response = null): ?HttpMe
);
}

/**
* The response of an HTTP client failure. For internal use by the SDK.
*
* @internal
* @param \Throwable $failure any failure; only HTTP client request failures have a response
* @return ResponseInterface|null null when the failure has no response or it cannot be read
*/
public static function responseOf(
#[\SensitiveParameter]
\Throwable $failure
): ?ResponseInterface {
if (!$failure instanceof RequestException) {
return null;
}
try {
return $failure->getResponse();
} catch (\Throwable $unreadable) {
return null;
}
}

/**
* The status code of a response. For internal use by the SDK.
*
* @internal
* @param ResponseInterface|null $response the response to read, if any
* @return int|null null when there is no response or its status cannot be read
*/
public static function statusOf(
#[\SensitiveParameter]
?ResponseInterface $response
): ?int {
if ($response === null) {
return null;
}
try {
$status = $response->getStatusCode();
} catch (\Throwable $unreadable) {
return null;
}
return is_int($status) ? $status : null;
}

/**
* The body of a response: all of it when the stream is seekable, otherwise what remains
* unread. For internal use by the SDK.
*
* @internal
* @param ResponseInterface|null $response the response to read, if any
* @return string|null null when there is no response or its body cannot be read
*/
public static function bodyOf(
#[\SensitiveParameter]
?ResponseInterface $response
): ?string {
if ($response === null) {
return null;
}
// Read with rewind() and getContents(), not __toString(): an exception thrown inside
// __toString() cannot be caught before PHP 7.4, on the lines that share this code.
try {
$body = $response->getBody();
if ($body->isSeekable()) {
$body->rewind();
}
$contents = $body->getContents();
} catch (\Throwable $unreadable) {
return null;
}
// Only text is returned: converting another value could call a __toString() that throws.
return is_string($contents) ? $contents : null;
}

/**
* Describes a failure for an SDK error message or log line without copying text the SDK does
* not control. For internal use by the SDK.
Expand All @@ -123,8 +197,9 @@ public static function describeFailure(
if ($failure instanceof CheckoutException && strpos($failure->getFile(), __DIR__ . DIRECTORY_SEPARATOR) === 0) {
return $class . ": " . $failure->getMessage();
}
if ($failure instanceof RequestException && $failure->getResponse() !== null) {
return $class . " (status " . $failure->getResponse()->getStatusCode() . ")";
$status = self::statusOf(self::responseOf($failure));
if ($status !== null) {
return $class . " (status " . $status . ")";
}
// Transfer errors of the HTTP client carry the transport error number in their context.
if (method_exists($failure, "getHandlerContext")) {
Expand Down
30 changes: 16 additions & 14 deletions lib/Checkout/OAuthSdkCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use DateInterval;
use DateTime;
use GuzzleHttp\Exception\RequestException;

class OAuthSdkCredentials implements SdkCredentialsInterface
{
Expand Down Expand Up @@ -124,10 +123,10 @@ private function getAccessToken()
"scope" => implode(" ", $this->scopes)
]
]);
$body = json_decode((string)$response->getBody(), true);
} catch (\Throwable $e) {
throw new CheckoutException(self::tokenFailureMessage($e));
}
$body = json_decode((string)$response->getBody(), true);
if (!self::isValidTokenResponse($body)) {
throw CheckoutAuthorizationException::invalidAccessTokenResponse();
}
Expand All @@ -144,19 +143,22 @@ private function getAccessToken()
* failed token request; otherwise a description of the failure. No text of the response or
* of another library is copied.
*/
private static function tokenFailureMessage(\Throwable $failure)
{
if ($failure instanceof RequestException && $failure->getResponse() !== null) {
$response = $failure->getResponse();
$message = "OAuth token request failed with status " . $response->getStatusCode();
$body = json_decode((string)$response->getBody(), true);
$error = is_array($body) ? ($body["error"] ?? null) : null;
if (is_string($error) && in_array($error, self::OAUTH_ERROR_CODES, true)) {
$message .= " (" . $error . ")";
}
return $message;
private static function tokenFailureMessage(
#[\SensitiveParameter]
\Throwable $failure
) {
$response = CheckoutUtils::responseOf($failure);
$status = CheckoutUtils::statusOf($response);
if ($status === null) {
return "OAuth token request failed: " . CheckoutUtils::describeFailure($failure);
}
$message = "OAuth token request failed with status " . $status;
$body = json_decode((string)CheckoutUtils::bodyOf($response), true);
$error = is_array($body) ? ($body["error"] ?? null) : null;
if (is_string($error) && in_array($error, self::OAUTH_ERROR_CODES, true)) {
$message .= " (" . $error . ")";
}
return "OAuth token request failed: " . CheckoutUtils::describeFailure($failure);
return $message;
}

/**
Expand Down
Loading
Loading