Skip to content
Open
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
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ class CustomCaHttpClientBuilder implements HttpClientBuilderInterface
{
public function getClient()
{
return new Client(['verify' => '/path/to/ca-bundle.pem']);
// A client you pass gets no default timeouts, so set them too (see HTTP timeouts below).
return new Client(['verify' => '/path/to/ca-bundle.pem', 'connect_timeout' => 10, 'timeout' => 60]);
}
}

Expand All @@ -171,6 +172,26 @@ $checkoutApi = CheckoutSdk::builder()->staticKeys()

A `cURL error 60` means PHP cannot find a CA bundle that trusts the API certificate; fix the CA configuration rather than turning verification off.

### HTTP timeouts

The HTTP client the SDK creates waits up to 10 seconds to connect (`connect_timeout`) and up to 60 seconds for the whole request (`timeout`), sending and receiving the body included, so a large upload or report download on a slow connection needs a client with a longer `timeout`. These bounds hold with Guzzle's cURL handler, which Guzzle uses when the PHP cURL extension is installed; without it, Guzzle's stream handler ignores `connect_timeout` and applies `timeout` to each read instead of the whole request. An API request that exceeds either bound throws a `CheckoutApiException`. With OAuth, a token request that exceeds them throws a `CheckoutException`, both the first one, sent while the SDK is built, and a renewal requested before an API request.

A client passed with `httpClientBuilder()` is used as is and does not get these defaults, so set the bounds you need on it:

```php
use Checkout\DefaultHttpClientBuilder;

$checkoutApi = CheckoutSdk::builder()->staticKeys()
->secretKey("secret_key")
->environment(Environment::sandbox())
->environmentSubdomain("subdomain")
->httpClientBuilder(new DefaultHttpClientBuilder([
'connect_timeout' => 5,
'timeout' => 30,
]))
->build();
```

## Exception handling

All the API responses that do not fall in the 2** status codes, the SDK will throw a `CheckoutApiException`.
Expand Down
21 changes: 20 additions & 1 deletion lib/Checkout/AbstractCheckoutSdkBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@

abstract class AbstractCheckoutSdkBuilder
{
/**
* Seconds the HTTP client created by the SDK waits to connect to the server.
* Guzzle's stream handler (no cURL extension) ignores it.
*/
const DEFAULT_CONNECT_TIMEOUT_SECONDS = 10;

/**
* Seconds the HTTP client created by the SDK waits for a whole request, connection
* included, before it fails.
* With Guzzle's stream handler (no cURL extension) it bounds each read instead.
*/
const DEFAULT_TIMEOUT_SECONDS = 60;

protected $environment;
protected $environmentSubdomain = null;
Expand All @@ -17,7 +29,10 @@ abstract class AbstractCheckoutSdkBuilder
public function __construct()
{
$this->environment = Environment::sandbox();
$this->httpClientBuilder = new DefaultHttpClientBuilder([]);
$this->httpClientBuilder = new DefaultHttpClientBuilder([
'connect_timeout' => self::DEFAULT_CONNECT_TIMEOUT_SECONDS,
'timeout' => self::DEFAULT_TIMEOUT_SECONDS,
]);
$this->setDefaultLogger();
}

Expand All @@ -42,6 +57,10 @@ public function environmentSubdomain($subdomain)
}

/**
* Replaces the HTTP client the SDK creates. The client returned by the given builder is
* used as is: the SDK default timeouts are not applied to it, so set connect_timeout and
* timeout on it yourself.
*
* @param HttpClientBuilderInterface $httpClientBuilder
* @return $this
*/
Expand Down
9 changes: 9 additions & 0 deletions lib/Checkout/CheckoutAuthorizationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ public static function invalidAccessTokenResponse()
);
}

/**
* @param int $statusCode HTTP status code of the token response
* @return CheckoutAuthorizationException
*/
public static function tokenRequestFailed($statusCode)
{
return new CheckoutAuthorizationException("OAuth token request failed with status " . $statusCode);
}

/**
* @param $keyType
* @return CheckoutAuthorizationException
Expand Down
4 changes: 3 additions & 1 deletion lib/Checkout/EnvironmentSubdomain.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ private function createUrlWithSubdomain($originalUrl, $subdomain)
{
$newEnvironment = $originalUrl;

$regex = '/^[0-9a-z]+$/';
// The D modifier anchors $ to the very end of the subject, so a value with a trailing
// newline is not accepted as a subdomain.
$regex = '/^[0-9a-z]+$/D';
if (preg_match($regex, $subdomain)) {
$urlParts = parse_url($originalUrl);
$newHost = $subdomain . '.' . $urlParts['host'];
Expand Down
4 changes: 4 additions & 0 deletions lib/Checkout/OAuthSdkCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ private function getAccessToken()
} catch (Exception $e) {
throw new CheckoutException($e->getMessage());
}
$statusCode = $response->getStatusCode();
if ($statusCode !== 200) {
throw CheckoutAuthorizationException::tokenRequestFailed($statusCode);
}
$body = json_decode((string)$response->getBody(), true);
if (!self::isValidTokenResponse($body)) {
throw CheckoutAuthorizationException::invalidAccessTokenResponse();
Expand Down
38 changes: 38 additions & 0 deletions test/Checkout/Tests/EnvironmentSubdomainTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Checkout\Tests;

use Checkout\Environment;
use Checkout\EnvironmentSubdomain;
use PHPUnit\Framework\TestCase;

class EnvironmentSubdomainTest extends TestCase
{
/**
* @test
*/
public function subdomainIsAddedToTheHosts()
{
$environmentSubdomain = new EnvironmentSubdomain(Environment::sandbox(), "abc");

$this->assertSame("https://abc.api.sandbox.checkout.com/", $environmentSubdomain->getBaseUri());
$this->assertSame(
"https://abc.access.sandbox.checkout.com/connect/token",
$environmentSubdomain->getAuthorizationUri()
);
}

/**
* @test
*/
public function subdomainWithTrailingNewlineIsNotUsed()
{
$environmentSubdomain = new EnvironmentSubdomain(Environment::sandbox(), "abc\n");

$this->assertSame("https://api.sandbox.checkout.com/", $environmentSubdomain->getBaseUri());
$this->assertSame(
"https://access.sandbox.checkout.com/connect/token",
$environmentSubdomain->getAuthorizationUri()
);
}
}
2 changes: 1 addition & 1 deletion test/Checkout/Tests/HttpClientOptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use Monolog\Logger;

/**
* The SDK must leave transport options to the HTTP client: requests use Guzzle's defaults
* The SDK must leave TLS options to the HTTP client: requests use Guzzle's TLS defaults
* unless the caller configures the client through a custom HttpClientBuilderInterface.
*/
class HttpClientOptionsTest extends MockeryTestCase
Expand Down
174 changes: 174 additions & 0 deletions test/Checkout/Tests/HttpClientTimeoutsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<?php

namespace Checkout\Tests;

use Checkout\AbstractCheckoutSdkBuilder;
use Checkout\ApiClient;
use Checkout\CheckoutApiException;
use Checkout\CheckoutConfiguration;
use Checkout\CheckoutException;
use Checkout\CheckoutSdk;
use Checkout\DefaultHttpClientBuilder;
use Checkout\Environment;
use Checkout\OAuthSdkCredentials;
use Checkout\PlatformType;
use Checkout\SdkAuthorization;
use Checkout\SdkCredentialsInterface;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use Monolog\Handler\NullHandler;
use Monolog\Logger;
use ReflectionProperty;

/**
* The HTTP client the SDK creates is bounded by default timeouts. A client the merchant
* provides through httpClientBuilder() is used as is.
*/
class HttpClientTimeoutsTest extends MockeryTestCase
{
/**
* Timeout, in seconds, of the client used against the server that never answers.
*/
const SHORT_TIMEOUT_SECONDS = 1;

/**
* Upper bound, in seconds, for a request against the server that never answers to fail.
*/
const MAX_ELAPSED_SECONDS = 10;

/**
* @param AbstractCheckoutSdkBuilder $sdkBuilder
* @return \GuzzleHttp\Client
*/
private static function clientOf(AbstractCheckoutSdkBuilder $sdkBuilder)
{
$property = new ReflectionProperty(AbstractCheckoutSdkBuilder::class, 'httpClientBuilder');
$property->setAccessible(true);
return $property->getValue($sdkBuilder)->getClient();
}

/**
* Opens a local TCP server that completes the connection and never sends a byte back.
*
* @return resource
*/
private static function openSilentServer()
{
$server = stream_socket_server('tcp://127.0.0.1:0', $errorNumber, $errorMessage);
if ($server === false) {
self::fail('Cannot open a local server: ' . $errorMessage);
}
return $server;
}

/**
* @param resource $server
* @return string
*/
private static function urlOf($server)
{
return 'http://' . stream_socket_get_name($server, false) . '/';
}

/**
* @return DefaultHttpClientBuilder
*/
private static function shortTimeoutBuilder()
{
return new DefaultHttpClientBuilder([
'connect_timeout' => self::SHORT_TIMEOUT_SECONDS,
'timeout' => self::SHORT_TIMEOUT_SECONDS,
]);
}

/**
* @test
*/
public function sdkCreatedClientHasDefaultTimeouts()
{
$this->assertSame(10, AbstractCheckoutSdkBuilder::DEFAULT_CONNECT_TIMEOUT_SECONDS);
$this->assertSame(60, AbstractCheckoutSdkBuilder::DEFAULT_TIMEOUT_SECONDS);

$sdkBuilders = [
CheckoutSdk::builder()->staticKeys(),
CheckoutSdk::builder()->oAuth(),
CheckoutSdk::builder()->previous()->staticKeys(),
];
foreach ($sdkBuilders as $sdkBuilder) {
$client = self::clientOf($sdkBuilder);
$this->assertSame(10, $client->getConfig('connect_timeout'));
$this->assertSame(60, $client->getConfig('timeout'));
}
}

/**
* @test
*/
public function customClientKeepsItsOwnOptions()
{
$withTimeout = new DefaultHttpClientBuilder(['timeout' => 5]);
$withoutTimeouts = new DefaultHttpClientBuilder([]);

$sdkBuilder = CheckoutSdk::builder()->staticKeys()->httpClientBuilder($withTimeout);
$client = self::clientOf($sdkBuilder);
$this->assertSame($withTimeout->getClient(), $client);
$this->assertSame(5, $client->getConfig('timeout'));
$this->assertNull($client->getConfig('connect_timeout'));

$sdkBuilder = CheckoutSdk::builder()->oAuth()->httpClientBuilder($withoutTimeouts);
$client = self::clientOf($sdkBuilder);
$this->assertSame($withoutTimeouts->getClient(), $client);
$this->assertNull($client->getConfig('timeout'));
$this->assertNull($client->getConfig('connect_timeout'));
}

/**
* @test
*/
public function apiRequestToServerThatNeverAnswersFailsWithApiException()
{
$server = self::openSilentServer();
$logger = new Logger('checkout-sdk-test-php');
$logger->pushHandler(new NullHandler());
$apiClient = new ApiClient(new CheckoutConfiguration(
$this->createMock(SdkCredentialsInterface::class),
Environment::sandbox(),
self::shortTimeoutBuilder(),
$logger
), self::urlOf($server));

$start = microtime(true);
try {
$apiClient->get('payments/pay_123', new SdkAuthorization(PlatformType::$default, 'sk_test_xxx'));
$this->fail('The request to a server that never answers did not fail');
} catch (CheckoutApiException $e) {
$this->assertLessThan(self::MAX_ELAPSED_SECONDS, microtime(true) - $start);
} finally {
fclose($server);
}
}

/**
* @test
*/
public function tokenRequestToServerThatNeverAnswersFailsWithCheckoutException()
{
$server = self::openSilentServer();

$start = microtime(true);
try {
OAuthSdkCredentials::init(
self::shortTimeoutBuilder(),
'client_id',
'secret_marker_5f2c',
self::urlOf($server) . 'connect/token',
['gateway']
);
$this->fail('The token request to a server that never answers did not fail');
} catch (CheckoutException $e) {
$this->assertLessThan(self::MAX_ELAPSED_SECONDS, microtime(true) - $start);
$this->assertFalse(strpos($e->getMessage(), 'secret_marker_5f2c') !== false);
} finally {
fclose($server);
}
}
}
Loading
Loading