-
Notifications
You must be signed in to change notification settings - Fork 54
/
ApiClient.php
505 lines (444 loc) · 14.4 KB
/
ApiClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<?php
namespace bunq\Http;
use bunq\Context\ApiContext;
use bunq\Context\BunqContext;
use bunq\Exception\BunqException;
use bunq\Http\Handler\HandlerUtil;
use bunq\Http\Handler\RequestHandlerAuthentication;
use bunq\Http\Handler\RequestHandlerEncryption;
use bunq\Http\Handler\RequestHandlerSignature;
use bunq\Http\Handler\ResponseHandlerError;
use bunq\Http\Handler\ResponseHandlerSignature;
use bunq\Util\BunqEnumApiEnvironmentType;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;
/**
*/
class ApiClient
{
/**
* Error constants.
*/
const ERROR_ENVIRONMENT_TYPE_UNKNOWN = 'Unknown environmentType "%s"';
const ERROR_MAC_OS_CURL_VERSION = 'Your PHP seems to be linked to the MacOS provided curl binary. ' .
'This is incompatible with our SDK, please reinstall by running: "brew reinstall %s --with-homebrew-curl".%s';
const ERROR_CURL_DOES_NOT_SUPPORT_ROOT_CERTIFICATE_PINNING =
//@codingStandardsIgnoreLine
'Curl does not support root certificate pinning. See https://curl.haxx.se/docs/todo.html#Support_intermediate_root_pinn';
/**
* Endpoints not requiring active session for the request to succeed.
*/
const URIS_NOT_REQUIRING_ACTIVE_SESSION = [
self::SANDBOX_USER_URL => true,
self::DEVICE_SERVER_URL => true,
self::INSTALLATION_URL => true,
self::SESSION_SERVER_URL => true,
];
const SANDBOX_USER_URL = 'sandbox-user';
const DEVICE_SERVER_URL = 'device-server';
const INSTALLATION_URL = 'installation';
const SESSION_SERVER_URL = 'session-server';
/**
* Public key locations.
*/
const FILE_PUBLIC_KEY_ENVIRONMENT_PRODUCTION = '/Certificate/api.bunq.com.pubkey.pem';
/**
* String format constants.
*/
const FORMAT_CURL_INSTALLATION_INSTRUCTIONS =
'This is incompatible with our SDK, please reinstall by running: "brew reinstall %s --with-homebrew-curl".%s';
const FORMAT_ERROR_MESSAGE_MAC_CURL = '%s%s%s';
/**
* Body constants.
*/
const BODY_EMPTY = '{}';
/**
* Header name.
*/
const HEADER_CLIENT_REQUEST_ID = 'X-Bunq-Client-Request-Id';
const HEADER_ATTACHMENT_DESCRIPTION = 'X-Bunq-Attachment-Description';
const HEADER_GEOLOCATION = 'X-Bunq-Geolocation';
const HEADER_LANGUAGE = 'X-Bunq-Language';
const HEADER_REGION = 'X-Bunq-Region';
const HEADER_CACHE_CONTROL = 'Cache-Control';
const HEADER_CONTENT_TYPE = 'Content-Type';
const HEADER_USER_AGENT = 'User-Agent';
/**
* Header value constants.
*/
const HEADER_CACHE_CONTROL_DEFAULT = 'no-cache';
const HEADER_CUSTOM_GEOLOCATION_DEFAULT = '0 0 0 0 NL';
const HEADER_CUSTOM_LANGUAGE_DEFAULT = 'en_US';
const HEADER_CUSTOM_REGION_DEFAULT = 'en_US';
/**
* User agent constants.
*/
const HEADER_USER_AGENT_BUNQ_SDK_DEFAULT = 'bunq-sdk-php/1.2.2';
/**
* Binary request constants.
*/
const FIELD_BODY = 'body';
const FIELD_CONTENT_TYPE = 'content_type';
const FIELD_DESCRIPTION = 'description';
/**
* Guzzle client configuration options.
*/
const OPTION_ALLOW_REDIRECTS = 'allow_redirects';
const OPTION_DEFAULTS = 'defaults';
const OPTION_EXCEPTIONS = 'exceptions';
const OPTION_HEADERS = 'headers';
const OPTION_HTTP_ERRORS = 'http_errors';
const OPTION_BODY = 'body';
const OPTION_CONFIG = 'config';
const OPTION_CURL = 'curl';
const OPTION_DEBUG = 'debug';
const OPTION_HANDLER = 'handler';
const OPTION_PROXY = 'proxy';
const OPTION_VERIFY = 'verify';
/**
* HTTP methods to make calls.
*/
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
/**
* Glue to connect multiple header values into one string.
*/
const GLUE_HEADER_VALUE = ',';
/**
* MacOS curl bug error code constant.
*/
const ERROR_CODE_MAC_OS_CURL_BUG = 0;
/**
* uname constants.
*/
const INDEX_UNAME_SYSNAME = 'sysname';
const SYSNAME_MAC_OS = 'Darwin';
/**
* PHP version check command constant.
*/
const COMMAND_DETERMINE_BREW_PHP_VERSION = 'brew list | egrep -e "^php[0-9]{2}$"';
/**
* Curl error regex constants.
*/
const REGEX_CURL_ERROR_CODE = '/(cURL error )(?P<errorCode>\d+)/';
const REGEX_NAMED_GOUP_ERROR_CODE = 'errorCode';
/**
* @var Client
*/
protected $httpClient;
/**
* @var ApiContext
*/
protected $apiContext;
/**
* @var bool
*/
protected $isBinary;
/**
* @var bool
*/
protected $isEncrypted;
/**
* @param ApiContext $apiContext
*/
public function __construct(ApiContext $apiContext)
{
$this->apiContext = $apiContext;
}
/**
*/
public function enableBinary()
{
$this->isBinary = true;
}
/**
*/
public function enableEncryption()
{
$this->isEncrypted = true;
}
/**
* @param string $uri
* @param string[] $params
* @param string[] $customHeaders
*
* @return BunqResponseRaw
*/
public function get(string $uri, array $params, array $customHeaders): BunqResponseRaw
{
return $this->request(self::METHOD_GET, $uri, [], $params, $customHeaders);
}
/**
* @param string $method
* @param string $uri
* @param mixed[][]|string $body
* @param string[] $params
* @param string[] $customHeaders
*
* @return BunqResponseRaw
* @throws BunqException
*/
private function request(
string $method,
string $uri,
$body,
array $params,
array $customHeaders
): BunqResponseRaw {
$this->initialize($uri);
try {
$response = $this->httpClient->request(
$method,
$this->determineUriFull($uri, $params),
$this->determineRequestOptions($body, $customHeaders)
);
} catch (RequestException $exception) {
if ($this->isCurlErrorCodeZero($exception) && $this->isMacOs()) {
throw new BunqException($this->determineErrorMessageCurlZero());
} else {
throw $exception;
}
}
return $this->createBunqResponseRaw($response);
}
/**
*/
private function initialize(string $uri)
{
if (!isset(self::URIS_NOT_REQUIRING_ACTIVE_SESSION[$uri])) {
if ($this->apiContext->ensureSessionActive()) {
BunqContext::updateApiContext($this->apiContext);
}
}
$this->initializeHttpClient();
}
/**
*/
private function initializeHttpClient()
{
if (is_null($this->httpClient)) {
$middleware = $this->determineMiddleware();
$this->httpClient = new Client(
array_merge(
[
self::OPTION_DEFAULTS => [
self::OPTION_ALLOW_REDIRECTS => false,
self::OPTION_EXCEPTIONS => false,
],
self::OPTION_HANDLER => $middleware,
self::OPTION_VERIFY => true,
self::OPTION_PROXY => $this->apiContext->getProxy(),
],
$this->determinePinnedKeySetting()
)
);
}
}
/**
* @return HandlerStack
*/
private function determineMiddleware(): HandlerStack
{
$handlerStack = HandlerStack::create();
if (is_null($this->apiContext->getInstallationContext())) {
// Disable verification middleware.
} else {
$sessionToken = $this->apiContext->getSessionToken();
$handlerStack->push(HandlerUtil::applyRequestHandler(new RequestHandlerAuthentication($sessionToken)));
if ($this->isEncrypted) {
$publicKey = $this->apiContext->getInstallationContext()->getPublicKeyServer();
$handlerStack->push(HandlerUtil::applyRequestHandler(new RequestHandlerEncryption($publicKey)));
}
$privateKey = $this->apiContext->getInstallationContext()->getKeyPairClient()->getPrivateKey();
$handlerStack->push(HandlerUtil::applyRequestHandler(new RequestHandlerSignature($privateKey)));
$serverPublicKey = $this->apiContext->getInstallationContext()->getPublicKeyServer();
$handlerStack->push(HandlerUtil::applyResponseHandler(new ResponseHandlerSignature($serverPublicKey)));
}
$handlerStack->push(HandlerUtil::applyResponseHandler(new ResponseHandlerError()));
return $handlerStack;
}
/**
* @return string[]
*/
private function determinePinnedKeySetting(): array
{
if ($this->apiContext->getEnvironmentType()->equals(BunqEnumApiEnvironmentType::SANDBOX())) {
return [];
} else {
return [
self::OPTION_CURL => [
CURLOPT_PINNEDPUBLICKEY => $this->determinePinnedServerPublicKey(),
],
];
}
}
/**
* @return string
* @throws BunqException when the environment type is unknown.
*/
private function determinePinnedServerPublicKey(): string
{
$environmentType = $this->apiContext->getEnvironmentType();
if ($environmentType->equals(BunqEnumApiEnvironmentType::SANDBOX())) {
throw new BunqException(self::ERROR_CURL_DOES_NOT_SUPPORT_ROOT_CERTIFICATE_PINNING);
} elseif ($environmentType->equals(BunqEnumApiEnvironmentType::PRODUCTION())) {
return __DIR__ . self::FILE_PUBLIC_KEY_ENVIRONMENT_PRODUCTION;
} else {
throw new BunqException(
self::ERROR_ENVIRONMENT_TYPE_UNKNOWN,
[
$environmentType->getChoiceString(),
]
);
}
}
/**
* @param string $uri
* @param string[] $params
*
* @return Uri
*/
private function determineUriFull(string $uri, array $params): Uri
{
$basePath = $this->apiContext->determineBaseUri()->getPath();
return $this->apiContext
->determineBaseUri()
->withPath($basePath . $uri)
->withQuery(http_build_query($params));
}
/**
* @param mixed[][]|string $body
* @param string[] $customHeaders
*
* @return mixed[]
*/
private function determineRequestOptions($body, array $customHeaders): array
{
$headers = array_merge($this->determineDefaultHeaders(), $customHeaders);
return [
self::OPTION_HEADERS => $headers,
self::OPTION_BODY => $this->determineBodyString($body),
self::OPTION_DEBUG => false,
self::OPTION_HTTP_ERRORS => false,
];
}
/**
* @return string[][]
*/
protected function determineDefaultHeaders(): array
{
return [
self::HEADER_CACHE_CONTROL => [self::HEADER_CACHE_CONTROL_DEFAULT],
self::HEADER_USER_AGENT => [self::HEADER_USER_AGENT_BUNQ_SDK_DEFAULT],
self::HEADER_GEOLOCATION => [self::HEADER_CUSTOM_GEOLOCATION_DEFAULT],
self::HEADER_LANGUAGE => [self::HEADER_CUSTOM_LANGUAGE_DEFAULT],
self::HEADER_REGION => [self::HEADER_CUSTOM_REGION_DEFAULT],
self::HEADER_CLIENT_REQUEST_ID => [uniqid()],
];
}
/**
* @param mixed[][]|string $body
*
* @return string
*/
protected function determineBodyString($body): string
{
if ($this->isBinary) {
return $body;
} elseif (empty($body)) {
return self::BODY_EMPTY;
} else {
$bodyString = json_encode($body);
}
return $bodyString;
}
/**
* @param RequestException $exception
*
* @return bool
*/
private function isCurlErrorCodeZero(RequestException $exception): bool
{
$allMatch = [];
preg_match(self::REGEX_CURL_ERROR_CODE, $exception->getMessage(), $allMatch);
return isset($allMatch[self::REGEX_NAMED_GOUP_ERROR_CODE])
&& $allMatch[self::REGEX_NAMED_GOUP_ERROR_CODE] === self::ERROR_CODE_MAC_OS_CURL_BUG;
}
/**
* @return bool
*/
private function isMacOs(): bool
{
return posix_uname()[self::INDEX_UNAME_SYSNAME] === self::SYSNAME_MAC_OS;
}
/**
* @return string
*/
private function determineErrorMessageCurlZero(): string
{
return vsprintf(
vsprintf(
self::FORMAT_ERROR_MESSAGE_MAC_CURL,
[self::ERROR_MAC_OS_CURL_VERSION, PHP_EOL, self::FORMAT_CURL_INSTALLATION_INSTRUCTIONS]
),
[$this->determineVersionPhpMacOs(), PHP_EOL]
);
}
/**
* @return string
*/
private function determineVersionPhpMacOs(): string
{
return exec(self::COMMAND_DETERMINE_BREW_PHP_VERSION);
}
/**
* @param ResponseInterface $response
*
* @return BunqResponseRaw
*/
private function createBunqResponseRaw(ResponseInterface $response): BunqResponseRaw
{
$headers = [];
foreach ($response->getHeaders() as $headerKey => $headerValues) {
$headers[$headerKey] = implode(self::GLUE_HEADER_VALUE, $headerValues);
}
return new BunqResponseRaw($response->getBody(), $headers);
}
/**
* @param string $uri
* @param mixed[][]|string $body
* @param string[] $customHeaders
*
* @return BunqResponseRaw
*/
public function post(string $uri, $body, array $customHeaders): BunqResponseRaw
{
return $this->request(self::METHOD_POST, $uri, $body, [], $customHeaders);
}
/**
* @param string $uri
* @param mixed[][]|string $body
* @param string[] $customHeaders
*
* @return BunqResponseRaw
*/
public function put(string $uri, $body, array $customHeaders): BunqResponseRaw
{
return $this->request(self::METHOD_PUT, $uri, $body, [], $customHeaders);
}
/**
* @param string $uri
* @param string[] $customHeaders
*
* @return BunqResponseRaw
*/
public function delete($uri, array $customHeaders)
{
return $this->request(self::METHOD_DELETE, $uri, [], [], $customHeaders);
}
}