-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathBasicShopifyAPI.php
More file actions
executable file
·479 lines (421 loc) · 12.7 KB
/
BasicShopifyAPI.php
File metadata and controls
executable file
·479 lines (421 loc) · 12.7 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
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
<?php
declare(strict_types=1);
namespace Gnikyt\BasicShopifyAPI;
use Closure;
use Exception;
use Gnikyt\BasicShopifyAPI\Clients\Graph;
use Gnikyt\BasicShopifyAPI\Clients\Rest;
use Gnikyt\BasicShopifyAPI\Contracts\ClientAware;
use Gnikyt\BasicShopifyAPI\Contracts\GraphRequester;
use Gnikyt\BasicShopifyAPI\Contracts\RestRequester;
use Gnikyt\BasicShopifyAPI\Contracts\SessionAware;
use Gnikyt\BasicShopifyAPI\Contracts\StateStorage;
use Gnikyt\BasicShopifyAPI\Contracts\TimeDeferrer;
use Gnikyt\BasicShopifyAPI\Deferrers\Sleep;
use Gnikyt\BasicShopifyAPI\Middleware\AuthRequest;
use Gnikyt\BasicShopifyAPI\Middleware\RateLimiting;
use Gnikyt\BasicShopifyAPI\Middleware\UpdateApiLimits;
use Gnikyt\BasicShopifyAPI\Middleware\UpdateRequestTime;
use Gnikyt\BasicShopifyAPI\Store\Memory;
use Gnikyt\BasicShopifyAPI\Traits\ResponseTransform;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\Promise;
use GuzzleRetry\GuzzleRetryMiddleware;
/**
* Basic Shopify API for REST & GraphQL.
*/
class BasicShopifyAPI implements SessionAware, ClientAware
{
use ResponseTransform;
/**
* Header for per-shop API call limits (recieve).
*
* @var string
*/
public const HEADER_REST_API_LIMITS = 'http_x_shopify_shop_api_call_limit';
/**
* Header for access token (send).
*
* @var string
*/
public const HEADER_ACCESS_TOKEN = 'x-shopify-access-token';
/**
* The Guzzle client.
*
* @var ClientInterface
*/
protected $client;
/**
* The handler stack.
*
* @var HandlerStack
*/
protected $stack;
/**
* The GraphQL client.
*
* @var GraphRequester
*/
protected $graphClient;
/**
* The REST client.
*
* @var RestRequester
*/
protected $restClient;
/**
* The library options.
*
* @var Options
*/
protected $options;
/**
* The API session.
*
* @var Session|null
*/
protected $session;
/**
* Request timestamp for every new call.
* Used for rate limiting.
*
* @var int
*/
protected $requestTimestamp;
/**
* Constructor.
*
* @param Options $options The options for the library setup.
* @param StateStorage|null $tstore The time storer implementation to use for rate limiting.
* @param StateStorage|null $lstore The limits storer implementation to use for rate limiting.
* @param TimeDeferrer|null $tdeferrer The time deferrer implementation to use for rate limiting.
*
* @return self
*/
public function __construct(
Options $options,
?StateStorage $tstore = null,
?StateStorage $lstore = null,
?TimeDeferrer $tdeferrer = null
) {
// Setup REST and GraphQL clients
$this->setupClients($tstore, $lstore, $tdeferrer);
// Set the options
$this->setOptions($options);
// Create the stack and assign the middleware which attempts to fix redirects
$this->stack = HandlerStack::create($this->getOptions()->getGuzzleHandler());
$this
->addMiddleware(new AuthRequest($this), 'request:auth')
->addMiddleware(new UpdateApiLimits($this), 'rate:update')
->addMiddleware(new UpdateRequestTime($this), 'time:update')
->addMiddleware(GuzzleRetryMiddleware::factory(), 'request:retry');
if ($this->getOptions()->isRateLimitingEnabled()) {
$this->addMiddleware(new RateLimiting($this), 'rate:limiting');
}
// Create a default Guzzle client with our stack
$this->setClient(
new Client(array_merge(
['handler' => $this->stack],
$this->getOptions()->getGuzzleOptions()
))
);
}
/**
* {@inheritdoc}
*/
public function setClient(ClientInterface $client): void
{
$this->client = $client;
$this->getGraphClient()->setClient($this->client);
$this->getRestClient()->setClient($this->client);
}
/**
* {@inheritdoc}
*/
public function getClient(): ClientInterface
{
return $this->client;
}
/**
* {@inheritdoc}
*/
public function setOptions(Options $options): void
{
$this->options = $options;
$this->getGraphClient()->setOptions($this->options);
$this->getRestClient()->setOptions($this->options);
}
/**
* {@inheritdoc}
*/
public function getOptions(): Options
{
return $this->options;
}
/**
* Sets the GraphQL request client.
*
* @param GraphRequester $client The client for GraphQL.
*
* @return self
*/
public function setGraphClient(GraphRequester $client): self
{
$this->graphClient = $client;
return $this;
}
/**
* Get the GraphQL client.
*
* @return GraphRequester
*/
public function getGraphClient(): GraphRequester
{
return $this->graphClient;
}
/**
* Sets the REST request client.
*
* @param RestRequester $client The client for REST.
*
* @return self
*/
public function setRestClient(RestRequester $client): self
{
$this->restClient = $client;
return $this;
}
/**
* Get the REST client.
*
* @return RestRequester
*/
public function getRestClient(): RestRequester
{
return $this->restClient;
}
/**
* {@inheritdoc}
*/
public function setSession(Session $session): void
{
$this->session = $session;
$this->getGraphClient()->setSession($this->session);
$this->getRestClient()->setSession($this->session);
}
/**
* {@inheritdoc}
*/
public function getSession(): ?Session
{
return $this->session;
}
/**
* Accepts a closure to do isolated API calls for a shop.
*
* @param Session $session The shop/user session.
*
* @throws Exception When closure is missing or not callable.
*
* @return mixed
*/
public function withSession(Session $session, Closure $closure)
{
// Clone the API class and bind it to the closure
$clonedApi = clone $this;
$clonedApi->setSession($session);
return $closure->call($clonedApi);
}
/**
* Add middleware to the handler stack.
*
* @param callable $callable Middleware function.
* @param string $name Name to register for this middleware.
*
* @return self
*/
public function addMiddleware(callable $callable, string $name = ''): self
{
$this->stack->push($callable, $name);
return $this;
}
/**
* Remove middleware to the handler stack.
*
* @param string $name Name to register for this middleware.
*
* @return self
*/
public function removeMiddleware(string $name = ''): self
{
$this->stack->remove($name);
return $this;
}
/**
* @see Rest::getAuthUrl
*/
public function getAuthUrl($scopes, string $redirectUri, string $mode = 'offline'): string
{
return $this->getRestClient()->getAuthUrl($scopes, $redirectUri, $mode);
}
/**
* @see Rest::requestAccess
*/
public function requestAccess(string $code): ResponseAccess
{
return $this->getRestClient()->requestAccess($code);
}
/**
* Gets the access token from a "code" supplied by Shopify request after successfull auth (for public apps).
*
* @param string $code The code from Shopify.
*
* @return string
*/
public function requestAccessToken(string $code): string
{
return $this->requestAccess($code)['access_token'];
}
/**
* Gets the access object from a "code" and sets it to the instance (for public apps).
*
* @param string $code The code from Shopify.
*
* @return void
*/
public function requestAndSetAccess(string $code): void
{
// Get the access response data
$access = $this->requestAccess($code);
// Setup the additional user data (if available)
$user = [];
if (isset($access['associated_user'])) {
$keys = ['associated_user', 'associated_user_scope', 'expires_in', 'session', 'account_number'];
foreach ($keys as $key) {
$user[$key] = $access[$key] ?? null;
}
}
$session = new Session(
$this->session->getShop(),
$access['access_token'],
new ResponseAccess($user)
);
// Update the session
$this->setSession($session);
}
/**
* Verify the request is from Shopify using the HMAC signature (for public apps).
*
* @param array $params The request parameters (ex. $_GET).
*
* @throws Exception For missing API secret.
*
* @return bool If the HMAC is validated.
*/
public function verifyRequest(array $params): bool
{
if ($this->getOptions()->getApiSecret() === null) {
// Secret is required
throw new Exception('API secret is missing');
}
// Ensure shop, timestamp, and HMAC are in the params
if (array_key_exists('shop', $params)
&& array_key_exists('timestamp', $params)
&& array_key_exists('hmac', $params)
) {
// Grab the HMAC, remove it from the params, then sort the params for hashing
$hmac = $params['hmac'];
unset($params['hmac']);
// Convert array values in the params to a string
foreach ($params as &$value) {
if (is_array($value)) {
$value = '["'.implode('", "', $value).'"]';
}
}
ksort($params);
// Encode and hash the params (without HMAC), add the API secret, and compare to the HMAC from params
return $hmac === hash_hmac(
'sha256',
urldecode(http_build_query($params)),
$this->options->getApiSecret()
);
}
// Not valid
return false;
}
/**
* Alias for REST method for backwards compatibility.
*
* @see rest
*/
public function request()
{
return call_user_func_array(
[$this, 'rest'],
func_get_args()
);
}
/**
* @see Graph::request
*/
public function graph(string $query, array $variables = [], bool $sync = true)
{
return $this->getGraphClient()->request($query, $variables, $sync);
}
/**
* Runs a request to the Shopify API (async).
*
* @see graph
*/
public function graphAsync(string $query, array $variables = []): Promise
{
return $this->graph($query, $variables, false);
}
/**
* @see Rest::request
*/
public function rest(string $type, string $path, ?array $params = null, array $headers = [], bool $sync = true)
{
return $this->getRestClient()->request($type, $path, $params, $headers, $sync);
}
/**
* Runs a request to the Shopify API (async).
* Alias for `rest` with `sync` param set to `false`.
*
* @see rest
*/
public function restAsync(string $type, string $path, ?array $params = null, array $headers = []): Promise
{
return $this->rest($type, $path, $params, $headers, false);
}
/**
* Setup the REST and GraphQL clients.
*
* @param StateStorage|null $tstore The time storer implementation to use for rate limiting.
* @param StateStorage|null $lstore The limits storer implementation to use for rate limiting.
* @param TimeDeferrer|null $tdeferrer The time deferrer implementation to use for rate limiting.
*
* @return void
*/
protected function setupClients(
?StateStorage $tstore = null,
?StateStorage $lstore = null,
?TimeDeferrer $tdeferrer = null
): void {
// Base/default storage class if none provided
$baseStorage = Memory::class;
// Setup timestamp storage
$graphTstore = $tstore === null ? new $baseStorage() : clone $tstore;
$restTstore = $tstore === null ? new $baseStorage() : clone $tstore;
// Setup limits storage
$graphLstore = $lstore === null ? new $baseStorage() : clone $lstore;
$restLstore = $lstore === null ? new $baseStorage() : clone $lstore;
// Setup time deferrer
$tdeferrer = $tdeferrer ?? new Sleep();
// Setup REST and Graph clients
$this->setRestClient(new Rest($restTstore, $restLstore, $tdeferrer));
$this->setGraphClient(new Graph($graphTstore, $graphLstore, $tdeferrer));
}
}