forked from picqer/exact-php-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.php
768 lines (655 loc) · 18.4 KB
/
Connection.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
<?php
namespace Picqer\Financials\Exact;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
/**
* Class Connection.
*/
class Connection
{
/**
* @var string
*/
private $baseUrl = 'https://start.exactonline.nl';
/**
* @var string
*/
private $apiUrl = '/api/v1';
/**
* @var string
*/
private $authUrl = '/api/oauth2/auth';
/**
* @var string
*/
private $tokenUrl = '/api/oauth2/token';
/**
* @var mixed
*/
private $exactClientId;
/**
* @var mixed
*/
private $exactClientSecret;
/**
* @var mixed
*/
private $authorizationCode;
/**
* @var mixed
*/
private $accessToken;
/**
* @var int the Unix timestamp at which the access token expires
*/
private $tokenExpires;
/**
* @var mixed
*/
private $refreshToken;
/**
* @var mixed
*/
private $redirectUrl;
/**
* @var mixed
*/
private $division;
/**
* @var Client|null
*/
private $client;
/**
* @var callable(Connection)
*/
private $tokenUpdateCallback;
/**
* @var callable(Connection)
*/
private $acquireAccessTokenLockCallback;
/**
* @var callable(Connection)
*/
private $acquireAccessTokenUnlockCallback;
/**
* @var callable[]
*/
protected $middleWares = [];
/**
* @var string|null
*/
public $nextUrl = null;
/**
* @var int|null
*/
protected $dailyLimit;
/**
* @var int|null
*/
protected $dailyLimitRemaining;
/**
* @var int|null
*/
protected $dailyLimitReset;
/**
* @var int|null
*/
protected $minutelyLimit;
/**
* @var int|null
*/
protected $minutelyLimitRemaining;
/**
* @return Client
*/
private function client()
{
if ($this->client) {
return $this->client;
}
$handlerStack = HandlerStack::create();
foreach ($this->middleWares as $middleWare) {
$handlerStack->push($middleWare);
}
$this->client = new Client([
'http_errors' => true,
'handler' => $handlerStack,
'expect' => false,
]);
return $this->client;
}
/**
* Insert a custom Guzzle client.
*
* @param Client $client
*/
public function setClient($client)
{
$this->client = $client;
}
/**
* Insert a Middleware for the Guzzle Client.
*
* @param $middleWare
*/
public function insertMiddleWare($middleWare)
{
$this->middleWares[] = $middleWare;
}
/**
* @throws ApiException
*
* @return Client
*/
public function connect()
{
// Redirect for authorization if needed (no access token or refresh token given)
if ($this->needsAuthentication()) {
$this->redirectForAuthorization();
}
// If access token is not set or token has expired, acquire new token
if (empty($this->accessToken) || $this->tokenHasExpired()) {
$this->acquireAccessToken();
}
$client = $this->client();
return $client;
}
/**
* @param string $method
* @param string $endpoint
* @param mixed $body
* @param array $params
* @param array $headers
*
* @return Request
*/
private function createRequest($method, $endpoint, $body = null, array $params = [], array $headers = [])
{
// Add default json headers to the request
$headers = array_merge($headers, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Prefer' => 'return=representation',
]);
// If access token is not set or token has expired, acquire new token
if (empty($this->accessToken) || $this->tokenHasExpired()) {
$this->acquireAccessToken();
}
// If we have a token, sign the request
if (! $this->needsAuthentication() && ! empty($this->accessToken)) {
$headers['Authorization'] = 'Bearer ' . $this->accessToken;
}
// Create param string
if (! empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
// Create the request
$request = new Request($method, $endpoint, $headers, $body);
return $request;
}
/**
* @param string $url
* @param array $params
* @param array $headers
*
* @throws ApiException
*
* @return mixed
*/
public function get($url, array $params = [], array $headers = [])
{
$url = $this->formatUrl($url, $url !== 'current/Me', $url == $this->nextUrl);
try {
$request = $this->createRequest('GET', $url, null, $params, $headers);
$response = $this->client()->send($request);
return $this->parseResponse($response, $url != $this->nextUrl);
} catch (Exception $e) {
$this->parseExceptionForErrorMessages($e);
}
}
/**
* @param string $url
* @param mixed $body
*
* @throws ApiException
*
* @return mixed
*/
public function post($url, $body)
{
$url = $this->formatUrl($url);
try {
$request = $this->createRequest('POST', $url, $body);
$response = $this->client()->send($request);
return $this->parseResponse($response);
} catch (Exception $e) {
$this->parseExceptionForErrorMessages($e);
}
}
/**
* @param string $url
* @param mixed $body
*
* @throws ApiException
*
* @return mixed
*/
public function put($url, $body)
{
$url = $this->formatUrl($url);
try {
$request = $this->createRequest('PUT', $url, $body);
$response = $this->client()->send($request);
return $this->parseResponse($response);
} catch (Exception $e) {
$this->parseExceptionForErrorMessages($e);
}
}
/**
* @param string $url
*
* @throws ApiException
*
* @return mixed
*/
public function delete($url)
{
$url = $this->formatUrl($url);
try {
$request = $this->createRequest('DELETE', $url);
$response = $this->client()->send($request);
return $this->parseResponse($response);
} catch (Exception $e) {
$this->parseExceptionForErrorMessages($e);
}
}
/**
* @return string
*/
public function getAuthUrl()
{
return $this->baseUrl . $this->authUrl . '?' . http_build_query([
'client_id' => $this->exactClientId,
'redirect_uri' => $this->redirectUrl,
'response_type' => 'code',
]);
}
/**
* @param mixed $exactClientId
*/
public function setExactClientId($exactClientId)
{
$this->exactClientId = $exactClientId;
}
/**
* @param mixed $exactClientSecret
*/
public function setExactClientSecret($exactClientSecret)
{
$this->exactClientSecret = $exactClientSecret;
}
/**
* @param mixed $authorizationCode
*/
public function setAuthorizationCode($authorizationCode)
{
$this->authorizationCode = $authorizationCode;
}
/**
* @param mixed $accessToken
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
}
/**
* @param mixed $refreshToken
*/
public function setRefreshToken($refreshToken)
{
$this->refreshToken = $refreshToken;
}
public function redirectForAuthorization()
{
$authUrl = $this->getAuthUrl();
header('Location: ' . $authUrl);
exit;
}
/**
* @param mixed $redirectUrl
*/
public function setRedirectUrl($redirectUrl)
{
$this->redirectUrl = $redirectUrl;
}
/**
* @return bool
*/
public function needsAuthentication()
{
return empty($this->refreshToken) && empty($this->authorizationCode);
}
/**
* @param Response $response
* @param bool $returnSingleIfPossible
*
* @throws ApiException
*
* @return mixed
*/
private function parseResponse(Response $response, $returnSingleIfPossible = true)
{
try {
if ($response->getStatusCode() === 204) {
return [];
}
$this->extractRateLimits($response);
Psr7\rewind_body($response);
$json = json_decode($response->getBody()->getContents(), true);
if (false === is_array($json)) {
throw new ApiException('Json decode failed. Got response: ' . $response->getBody()->getContents());
}
if (array_key_exists('d', $json)) {
if (array_key_exists('__next', $json['d'])) {
$this->nextUrl = $json['d']['__next'];
} else {
$this->nextUrl = null;
}
if (array_key_exists('results', $json['d'])) {
if ($returnSingleIfPossible && count($json['d']['results']) == 1) {
return $json['d']['results'][0];
}
return $json['d']['results'];
}
return $json['d'];
}
return $json;
} catch (\RuntimeException $e) {
throw new ApiException($e->getMessage());
}
}
/**
* @return mixed
*/
private function getCurrentDivisionNumber()
{
if (empty($this->division)) {
$me = new Me($this);
$this->division = $me->find()->CurrentDivision;
}
return $this->division;
}
/**
* @return mixed
*/
public function getRefreshToken()
{
return $this->refreshToken;
}
/**
* @return mixed
*/
public function getAccessToken()
{
return $this->accessToken;
}
private function acquireAccessToken()
{
try {
if (is_callable($this->acquireAccessTokenLockCallback)) {
call_user_func($this->acquireAccessTokenLockCallback, $this);
}
// If refresh token not yet acquired, do token request
if (empty($this->refreshToken)) {
$body = [
'form_params' => [
'redirect_uri' => $this->redirectUrl,
'grant_type' => 'authorization_code',
'client_id' => $this->exactClientId,
'client_secret' => $this->exactClientSecret,
'code' => $this->authorizationCode,
],
];
} else { // else do refresh token request
$body = [
'form_params' => [
'refresh_token' => $this->refreshToken,
'grant_type' => 'refresh_token',
'client_id' => $this->exactClientId,
'client_secret' => $this->exactClientSecret,
],
];
}
$response = $this->client()->post($this->getTokenUrl(), $body);
Psr7\rewind_body($response);
$body = json_decode($response->getBody()->getContents(), true);
if (json_last_error() === JSON_ERROR_NONE) {
$this->accessToken = $body['access_token'];
$this->refreshToken = $body['refresh_token'];
$this->tokenExpires = $this->getTimestampFromExpiresIn($body['expires_in']);
if (is_callable($this->tokenUpdateCallback)) {
call_user_func($this->tokenUpdateCallback, $this);
}
} else {
throw new ApiException('Could not acquire tokens, json decode failed. Got response: ' . $response->getBody()->getContents());
}
} catch (BadResponseException $ex) {
throw new ApiException('Could not acquire or refresh tokens [http ' . $ex->getResponse()->getStatusCode() . ']', 0, $ex);
} finally {
if (is_callable($this->acquireAccessTokenUnlockCallback)) {
call_user_func($this->acquireAccessTokenUnlockCallback, $this);
}
}
}
/**
* Translates expires_in to a Unix timestamp.
*
* @param string $expiresIn number of seconds until the token expires
*
* @return int
*/
private function getTimestampFromExpiresIn($expiresIn)
{
if (! ctype_digit($expiresIn)) {
throw new \InvalidArgumentException('Function requires a numeric expires value');
}
return time() + $expiresIn;
}
/**
* @return int the Unix timestamp at which the access token expires
*/
public function getTokenExpires()
{
return $this->tokenExpires;
}
/**
* @param int $tokenExpires the Unix timestamp at which the access token expires
*/
public function setTokenExpires($tokenExpires)
{
$this->tokenExpires = $tokenExpires;
}
private function tokenHasExpired()
{
if (empty($this->tokenExpires)) {
return true;
}
return ($this->tokenExpires - 60) < time();
}
private function formatUrl($endPoint, $includeDivision = true, $formatNextUrl = false)
{
if ($formatNextUrl) {
return $endPoint;
}
if ($includeDivision) {
return implode('/', [
$this->getApiUrl(),
$this->getCurrentDivisionNumber(),
$endPoint,
]);
}
return implode('/', [
$this->getApiUrl(),
$endPoint,
]);
}
/**
* @return mixed
*/
public function getDivision()
{
return $this->division;
}
/**
* @param mixed $division
*/
public function setDivision($division)
{
$this->division = $division;
}
/**
* @param callable $callback
*/
public function setAcquireAccessTokenLockCallback($callback)
{
$this->acquireAccessTokenLockCallback = $callback;
}
/**
* @param callable $callback
*/
public function setAcquireAccessTokenUnlockCallback($callback)
{
$this->acquireAccessTokenUnlockCallback = $callback;
}
/**
* @param callable $callback
*/
public function setTokenUpdateCallback($callback)
{
$this->tokenUpdateCallback = $callback;
}
/**
* Parse the reponse in the Exception to return the Exact error messages.
*
* @param Exception $e
*
* @throws ApiException
*/
private function parseExceptionForErrorMessages(Exception $e)
{
if (! $e instanceof BadResponseException) {
throw new ApiException($e->getMessage(), 0, $e);
}
$response = $e->getResponse();
$this->extractRateLimits($response);
Psr7\rewind_body($response);
$responseBody = $response->getBody()->getContents();
$decodedResponseBody = json_decode($responseBody, true);
if (! is_null($decodedResponseBody) && isset($decodedResponseBody['error']['message']['value'])) {
$errorMessage = $decodedResponseBody['error']['message']['value'];
} else {
$errorMessage = $responseBody;
}
throw new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $e);
}
/**
* @return int|null The maximum number of API calls that your app is permitted to make per company, per day
*/
public function getDailyLimit()
{
return $this->dailyLimit;
}
/**
* @return int|null The remaining number of API calls that your app is permitted to make for a company, per day
*/
public function getDailyLimitRemaining()
{
return $this->dailyLimitRemaining;
}
/**
* @return int|null The time at which the rate limit window resets in UTC epoch milliseconds
*/
public function getDailyLimitReset()
{
return $this->dailyLimitReset;
}
/**
* @return int|null The maximum number of API calls that your app is permitted to make per company, per minute
*/
public function getMinutelyLimit()
{
return $this->minutelyLimit;
}
/**
* @return int|null The remaining number of API calls that your app is permitted to make for a company, per minute
*/
public function getMinutelyLimitRemaining()
{
return $this->minutelyLimitRemaining;
}
/**
* @return string
*/
protected function getBaseUrl()
{
return $this->baseUrl;
}
/**
* @return string
*/
private function getApiUrl()
{
return $this->baseUrl . $this->apiUrl;
}
/**
* @return string
*/
private function getTokenUrl()
{
return $this->baseUrl . $this->tokenUrl;
}
/**
* Set base URL for different countries according to
* https://developers.exactonline.com/#Exact%20Online%20sites.html.
*
* @param string $baseUrl
*/
public function setBaseUrl($baseUrl)
{
$this->baseUrl = $baseUrl;
}
/**
* @param string $apiUrl
*/
public function setApiUrl($apiUrl)
{
$this->apiUrl = $apiUrl;
}
/**
* @param string $authUrl
*/
public function setAuthUrl($authUrl)
{
$this->authUrl = $authUrl;
}
/**
* @param string $tokenUrl
*/
public function setTokenUrl($tokenUrl)
{
$this->tokenUrl = $tokenUrl;
}
private function extractRateLimits(Response $response)
{
$this->dailyLimit = (int) $response->getHeaderLine('X-RateLimit-Limit');
$this->dailyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Remaining');
$this->dailyLimitReset = (int) $response->getHeaderLine('X-RateLimit-Reset');
$this->minutelyLimit = (int) $response->getHeaderLine('X-RateLimit-Minutely-Limit');
$this->minutelyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Minutely-Remaining');
}
}