-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSageApiClient.php
275 lines (238 loc) · 9.72 KB
/
SageApiClient.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
<?php
namespace ThinkingLogic;
use GuzzleHttp\Psr7\Response;
use League\OAuth2\Client\Token\AccessTokenInterface;
use SageAccounting\ApiResponse;
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/AccessTokenStore.php';
require_once __DIR__ . '/Logger.php';
include 'sage/api_response.php';
/**
* Based on: https://raw.githubusercontent.com/Sage/sageone_api_php_sample/master/lib/api_client.php
* at commit: https://github.com/Sage/sageone_api_php_sample/tree/f04bd7dd910aacc7b60bfc0f81da90ccfcddadc4
* Class SageApiClient
* @package SageAccounting
*
*/
class SageApiClient {
private $clientId;
private $clientSecret;
private $callbackUrl;
private $oauthClient;
private $accessTokenStore;
private $generatedState;
const BASE_ENDPOINT = "https://api.accounting.sage.com/v3.1";
const AUTH_ENDPOINT = "https://www.sageone.com/oauth2/auth/central?filter=apiv3.1";
const TOKEN_ENDPOINT = "https://oauth.accounting.sage.com/token";
const SCOPE = "full_access";
/**
* Constructor
*
* @param string $client_id Your application's client_id
* @param string $client_secret Your application's client_secret
* @param string $callback_url Your application's callback_url
*/
public function __construct( $client_id, $client_secret, $callback_url ) {
$this->clientId = $client_id;
$this->clientSecret = $client_secret;
$this->callbackUrl = $callback_url;
$this->generateRandomState();
$this->oauthClient = new \League\OAuth2\Client\Provider\GenericProvider( [
'clientId' => $this->clientId,
'clientSecret' => $this->clientSecret,
'redirectUri' => $this->callbackUrl,
'urlAuthorize' => self::AUTH_ENDPOINT,
'urlAccessToken' => self::TOKEN_ENDPOINT,
'urlResourceOwnerDetails' => '',
'timeout' => 10
] );
}
/**
* Returns the authorization endpoint with all required query params for
* making the auth request
*/
public function authorizationEndpoint(): string {
return self::AUTH_ENDPOINT . "&response_type=code&client_id=" .
$this->clientId . "&redirect_uri=" . urlencode( $this->callbackUrl ) .
"&scope=" . self::SCOPE . "&state=" . $this->generatedState;
}
/* POST request to exchange the authorization code for an access_token */
public function getInitialAccessToken( $code, $receivedState ) {
$initialAccessToken = null;
try {
Logger::log( "About to getInitialAccessToken using clientId=" . $this->clientId . ", clientSecret=" . $this->clientSecret . ", callbackUrl=" . $this->callbackUrl );
$initialAccessToken = $this->oauthClient->getAccessToken( 'authorization_code', [ 'code' => $code ] );
return $this->storeAccessToken( $initialAccessToken );
} catch ( \League\OAuth2\Client\Grant\Exception\InvalidGrantException $e ) {
// authorization code was not found or is invalid
Logger::log( "Unable to getInitialAccessToken - InvalidGrantException: " . $e->getMessage() );
Logger::addAdminWarning( $e->getMessage() );
} catch ( \League\OAuth2\Client\Provider\Exception\IdentityProviderException $e ) {
// authorization code was not found or is invalid
Logger::log( "Unable to getInitialAccessToken - IdentityProviderException: " . $e );
Logger::addAdminWarning( $e->getMessage() );
} catch ( \GuzzleHttp\Exception\ConnectException $e ) {
// if no internet connection is available
Logger::log( "Unable to getInitialAccessToken - ConnectException: " . $e->getMessage() );
Logger::addAdminWarning( $e->getMessage() );
} catch ( \UnexpectedValueException $e ) {
// An OAuth server error was encountered that did not contain a JSON body
Logger::log( "Unable to getInitialAccessToken - UnexpectedValueException: " . $e->getMessage() );
Logger::addAdminWarning( $e->getMessage() );
} catch ( \Exception $e ) {
// general exception
Logger::log( "Unable to getInitialAccessToken - Exception: " . $e . ", message: " . $e->getMessage() );
Logger::addAdminWarning( $e->getMessage() );
}
return $initialAccessToken;
}
/* POST request to renew the access_token */
public function renewAccessToken() {
$newAccessToken = null;
try {
$newAccessToken = $this->oauthClient->getAccessToken( 'refresh_token', [ 'refresh_token' => $this->getRefreshToken() ] );
Logger::log( "renewAccessToken: token renewed" );
$this->storeAccessToken( $newAccessToken );
} catch ( \League\OAuth2\Client\Grant\Exception\InvalidGrantException $e ) {
// refresh token was not found or is invalid
Logger::log( "Unable to renewAccessToken - InvalidGrantException: " . $e->getMessage() );
$this->warnAccessTokenError( $e->getMessage() );
} catch ( \League\OAuth2\Client\Provider\Exception\IdentityProviderException $e ) {
// refresh token was not found or is invalid
Logger::log( "Unable to renewAccessToken - IdentityProviderException: " . $e->getMessage() );
$this->warnAccessTokenError( $e->getMessage() );
} catch ( \GuzzleHttp\Exception\ConnectException $e ) {
// if no internet connection is available
Logger::log( "Unable to renewAccessToken - ConnectException: " . $e->getMessage() );
$this->warnAccessTokenError( $e->getMessage() );
} catch ( \Exception $e ) {
// general exception
Logger::log( "Unable to getInitialAccessToken - message: " . $e->getMessage() );
$this->warnAccessTokenError( $e->getMessage() );
} finally {
return $newAccessToken;
}
}
public function refreshTokenIfNecessary() {
$expires = $this->getExpiresAt();
if ( $expires ) {
if ( time() >= $expires ) {
$this->renewAccessToken();
} else {
Logger::log( "token does not require refreshing" );
}
} else {
Logger::log( "Cannot renew token - no expires value found" );
}
}
/**
* @param $resource
* @param $httpMethod
* @param null $postData
*
* @return ApiResponse
*/
public function execApiRequest( $resource, $httpMethod, $postData = null ): ApiResponse {
$this->refreshTokenIfNecessary();
$method = strtoupper( $httpMethod );
$options['headers']['Content-Type'] = 'application/json';
$requestResponse = new Response( 500 );
if ( $postData && ( $method == 'POST' || $method == 'PUT' ) ) {
$options['body'] = $postData;
}
try {
$request = $this->oauthClient->getAuthenticatedRequest( $method, self::BASE_ENDPOINT . $resource, $this->getAccessToken(), $options );
$startTime = microtime( 1 );
$requestResponse = $this->oauthClient->getResponse( $request );
} catch ( \GuzzleHttp\Exception\ClientException|\GuzzleHttp\Exception\ServerException $e ) {
// catch all 4xx errors
Logger::log( "Caught " . get_class( $e ) . " making " . $httpMethod . " request to " . $resource . ": " . $e->getMessage() );
if (!is_null($postData)) {
Logger::log("Request body: " . json_encode($postData));
}
$requestResponse = $e->getResponse();
Logger::addAdminWarning( $e->getMessage() );
} catch ( \GuzzleHttp\Exception\ConnectException|Exception $e ) {
// general exception
Logger::log( "Caught " . get_class( $e ) . " making " . $httpMethod . " request to " . $resource . ": " . $e->getMessage() );
if (!is_null($postData)) {
Logger::log("Request body: " . json_encode($postData));
}
Logger::addAdminWarning( $e->getMessage() );
} finally {
$endTime = microtime( 1 );
$api_response = new ApiResponse( $requestResponse, $endTime - $startTime );
Logger::debug( 'Made ' . $httpMethod . ' request to ' . $resource . ' with request body=' . $postData . ', response: ' . $api_response->getBody() );
return $api_response;
}
}
/**
* Returns the access token
*/
public function getAccessToken() {
return $this->getAccessTokenStore()->getAccessToken();
}
/**
* Returns the UNIX timestamp when the access token expires
*/
public function getExpiresAt() {
return $this->getAccessTokenStore()->getExpiresAt();
}
/**
* Returns the refresh token
*/
public function getRefreshToken() {
return $this->getAccessTokenStore()->getRefreshToken();
}
/**
* Returns the UNIX timestamp when the refresh token expires
*/
public function getRefreshTokenExpiresAt() {
return $this->getAccessTokenStore()->getRefreshTokenExpiresAt();
}
/**
* @return true if the refresh token will expire within the next hour
*/
public function isRefreshTokenExpiringSoon(): bool {
$expires_at = $this->getRefreshTokenExpiresAt();
return empty( $expires_at ) || $expires_at < ( time() + ( 60 * 60 ) );
}
public function getAccessTokenStore(): ?AccessTokenStore {
if ( $this->accessTokenStore ) {
return $this->accessTokenStore;
}
$this->accessTokenStore = new AccessTokenStore();
if ( ! $this->accessTokenStore->load() ) {
$this->accessTokenStore = null;
}
return $this->accessTokenStore;
}
// Private area
private function storeAccessToken( AccessTokenInterface $response ): AccessTokenInterface {
if ( ! $this->accessTokenStore ) {
$this->accessTokenStore = new AccessTokenStore();
}
$this->accessTokenStore->save(
$response->getToken(),
$response->getExpires(),
$response->getRefreshToken(),
$response->getValues()["refresh_token_expires_in"]
);
Logger::log( "Stored access token as " . substr( $response->getToken(), 0, 5 ) . "..." );
return $response;
}
private function generateRandomState() {
$include_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$charLength = strlen( $include_chars );
$randomString = '';
// length of 30
for ( $i = 0; $i < 30; $i ++ ) {
$randomString .= $include_chars [ rand( 0, $charLength - 1 ) ];
}
$this->generatedState = $randomString;
}
private function warnAccessTokenError( $message ) {
Logger::addAdminWarning( $message );
Logger::addAdminNotice( '<a class="button" href="' . $this->authorizationEndpoint() . '">Refresh Authorisation</a>' );
}
}