This repository was archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathapi_client.php
More file actions
223 lines (200 loc) · 7.24 KB
/
api_client.php
File metadata and controls
223 lines (200 loc) · 7.24 KB
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
<?php
namespace SageAccounting;
require '/var/php/vendor/autoload.php';
include 'client_configuration.php';
include 'access_token_store.php';
include 'api_response.php';
include 'exception_handler.php';
class ApiClient
{
private $clientId;
private $clientSecret;
private $callbackUrl;
private $oauthClient;
private $scope;
private $accessToken;
private $refreshToken;
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
*/
public function __construct()
{
$this->generateRandomState();
$this->loadClientConfiguration();
$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()
{
return self::AUTH_ENDPOINT . "&response_type=code&client_id=" .
$this->clientId . "&redirect_uri=" . $this->callbackUrl .
"&scope=" . self::SCOPE . "&state=" . $this->generatedState;
}
/* POST request to exchange the authorization code for an access_token */
public function getInitialAccessToken($code, $receivedState)
{
try {
$initialAccessToken = $this->oauthClient->getAccessToken('authorization_code', ['code' => $code]);
}
catch (\League\OAuth2\Client\Grant\Exception\InvalidGrantException $e) {
// authorization code was not found or is invalid
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch (\GuzzleHttp\Exception\ConnectException $e) {
// if no internet connection is available
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch (UnexpectedValueException $e) {
// An OAuth server error was encountered that did not contain a JSON body
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch(Exception $e) {
// general exception
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
finally {
return $this->storeAccessToken($initialAccessToken);
}
}
/* POST request to renew the access_token */
public function renewAccessToken()
{
try {
$newAccessToken = $this->oauthClient->getAccessToken('refresh_token', ['refresh_token' => $this->getRefreshToken()]);
}
catch (\League\OAuth2\Client\Grant\Exception\InvalidGrantException $e) {
// refresh token was not found or is invalid
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch (\GuzzleHttp\Exception\ConnectException $e) {
// if no internet connection is available
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch(Exception $e) {
// general exception
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
finally {
return $this->storeAccessToken($newAccessToken);
}
}
/* GET request */
public function execApiRequest($resource, $httpMethod, $postData = null)
{
$method = strtoupper($httpMethod);
$options['headers']['Content-Type'] = 'application/json';
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(\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch (\GuzzleHttp\Exception\ClientException $e) {
// catch all 4xx errors
$requestResponse = $e->getResponse();
}
catch (\GuzzleHttp\Exception\ServerException $e) {
// catch all 5xx errors
$requestResponse = $e->getResponse();
}
catch (\GuzzleHttp\Exception\ConnectException $e) {
// if no internet connection is available
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
catch(Exception $e) {
// general exception
ExceptionHandler::raiseError(get_class($e), $e->getMessage());
}
finally {
$endTime = microtime(1);
return new \SageAccounting\ApiResponse($requestResponse, $endTime - $startTime);
}
}
/**
* Returns the previously loaded access token
*/
public function getAccessToken()
{
return $this->getAccessTokenStore()->getAccessToken();
}
/**
* Returns the previously loaded UNIX timestamp when the access token expires
*/
public function getExpiresAt()
{
return $this->getAccessTokenStore()->getExpiresAt();
}
/**
* Returns the previously loaded refresh token
*/
public function getRefreshToken()
{
return $this->getAccessTokenStore()->getRefreshToken();
}
public function getAccessTokenStore()
{
if ($this->accessTokenStore) {
return $this->accessTokenStore;
}
$this->accessTokenStore = new \SageAccounting\AccessTokenStore();
if (!$this->accessTokenStore->load()) {
$this->accessTokenStore = null;
}
return $this->accessTokenStore;
}
// Private area
private function loadClientConfiguration()
{
$clientConfig = new \SageAccounting\ClientConfiguration;
if ($clientConfig->load()) {
$this->clientId = $clientConfig->getClientId();
$this->clientSecret = $clientConfig->getClientSecret();
$this->callbackUrl = $clientConfig->getCallbackUrl();
}
}
private function storeAccessToken($response)
{
if (!$this->accessTokenStore) {
$this->accessTokenStore = new \SageAccounting\AccessTokenStore();
}
$this->accessTokenStore->save(
$response->getToken(),
$response->getExpires(),
$response->getRefreshToken(),
$response->getValues()["refresh_token_expires_in"]
);
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;
}
}