-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathShopifySDK.php
478 lines (443 loc) · 15.1 KB
/
ShopifySDK.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
<?php
/**
* Created by PhpStorm.
* @author Tareq Mahmood <tareqtms@yahoo.com>
* Created at 8/16/16 10:42 AM UTC+06:00
*
* @see https://help.shopify.com/api/reference/ Shopify API Reference
*/
namespace PHPShopify;
/*
|--------------------------------------------------------------------------
| Shopify API SDK Client Class
|--------------------------------------------------------------------------
|
| This class initializes the resource objects
|
| Usage:
| //For private app
| $config = array(
| 'ShopUrl' => 'yourshop.myshopify.com',
| 'ApiKey' => '***YOUR-PRIVATE-API-KEY***',
| 'Password' => '***YOUR-PRIVATE-API-PASSWORD***',
| );
| //For third party app
| $config = array(
| 'ShopUrl' => 'yourshop.myshopify.com',
| 'AccessToken' => '***ACCESS-TOKEN-FOR-THIRD-PARTY-APP***',
| );
| //Create the shopify client object
| $shopify = new ShopifySDK($config);
|
| //Get shop details
| $products = $shopify->Shop->get();
|
| //Get list of all products
| $products = $shopify->Product->get();
|
| //Get a specific product by product ID
| $products = $shopify->Product($productID)->get();
|
| //Update a product
| $updateInfo = array('title' => 'New Product Title');
| $products = $shopify->Product($productID)->put($updateInfo);
|
| //Delete a product
| $products = $shopify->Product($productID)->delete();
|
| //Create a new product
| $productInfo = array(
| "title" => "Burton Custom Freestlye 151",
| "body_html" => "<strong>Good snowboard!<\/strong>",
| "vendor" => "Burton",
| "product_type" => "Snowboard",
| );
| $products = $shopify->Product->post($productInfo);
|
| //Get variants of a product (using Child resource)
| $products = $shopify->Product($productID)->Variant->get();
|
| //GraphQL
| $data = $shopify->GraphQL->post($graphQL);
|
*/
use PHPShopify\Exception\SdkException;
/**
* @property-read AbandonedCheckout $AbandonedCheckout
* @property-read AccessScope $AccessScope
* @property-read ApiDeprecations $ApiDeprecations
* @property-read ApplicationCharge $ApplicationCharge
* @property-read AssignedFulfillmentOrder $AssignedFulfillmentOrder
* @property-read Blog $Blog
* @property-read CarrierService $CarrierService
* @property-read Cart $Cart
* @property-read Collect $Collect
* @property-read Collection $Collection
* @property-read Comment $Comment
* @property-read Country $Country
* @property-read Currency $Currency
* @property-read CustomCollection $CustomCollection
* @property-read Customer $Customer
* @property-read CustomerSavedSearch $CustomerSavedSearch
* @property-read Discount $Discount
* @property-read DiscountCode $DiscountCode
* @property-read DraftOrder $DraftOrder
* @property-read Event $Event
* @property-read Fulfillment $Fulfillment
* @property-read FulfillmentOrder $FulfillmentOrder
* @property-read FulfillmentService $FulfillmentService
* @property-read GiftCard $GiftCard
* @property-read GiftCardAdjustment $GiftCardAdjustment
* @property-read InventoryItem $InventoryItem
* @property-read InventoryLevel $InventoryLevel
* @property-read Location $Location
* @property-read Metafield $Metafield
* @property-read Multipass $Multipass
* @property-read Order $Order
* @property-read Page $Page
* @property-read Policy $Policy
* @property-read PriceRule $PriceRule
* @property-read Product $Product
* @property-read ProductListing $ProductListing
* @property-read ProductVariant $ProductVariant
* @property-read RecurringApplicationCharge $RecurringApplicationCharge
* @property-read Redirect $Redirect
* @property-read Report $Report
* @property-read ScriptTag $ScriptTag
* @property-read ShippingZone $ShippingZone
* @property-read Shop $Shop
* @property-read ShopifyPayment $ShopifyPayment
* @property-read SmartCollection $SmartCollection
* @property-read TenderTransaction $TenderTransaction
* @property-read Theme $Theme
* @property-read User $User
* @property-read Webhook $Webhook
* @property-read GraphQL $GraphQL
*
* @method AbandonedCheckout AbandonedCheckout(integer $id = null)
* @method AssignedFulfillmentOrder AssignedFulfillmentOrder(string $assignment_status = null, array $location_ids = null)
* @method AccessScope AccessScope()
* @method ApiDeprecations ApiDeprecations()
* @method ApplicationCharge ApplicationCharge(integer $id = null)
* @method Blog Blog(integer $id = null)
* @method CarrierService CarrierService(integer $id = null)
* @method Cart Cart(string $cart_token = null)
* @method Collect Collect(integer $id = null)
* @method Collection Collection(integer $id = null)
* @method Comment Comment(integer $id = null)
* @method Country Country(integer $id = null)
* @method Currency Currency(integer $id = null)
* @method CustomCollection CustomCollection(integer $id = null)
* @method Customer Customer(integer $id = null)
* @method CustomerSavedSearch CustomerSavedSearch(integer $id = null)
* @method Discount Discount(integer $id = null)
* @method DraftOrder DraftOrder(integer $id = null)
* @method DiscountCode DiscountCode(integer $id = null)
* @method Event Event(integer $id = null)
* @method Fulfillment Fulfillment(integer $id = null)
* @method FulfillmentService FulfillmentService(integer $id = null)
* @method FulfillmentOrder FulfillmentOrder(integer $id = null)
* @method GiftCard GiftCard(integer $id = null)
* @method GiftCardAdjustment GiftCardAdjustment(integer $id = null)
* @method InventoryItem InventoryItem(integer $id = null)
* @method InventoryLevel InventoryLevel(integer $id = null)
* @method Location Location(integer $id = null)
* @method Metafield Metafield(integer $id = null)
* @method Multipass Multipass(integer $id = null)
* @method Order Order(integer $id = null)
* @method Page Page(integer $id = null)
* @method Policy Policy(integer $id = null)
* @method Product Product(integer $id = null)
* @method ProductListing ProductListing(integer $id = null)
* @method ProductVariant ProductVariant(integer $id = null)
* @method PriceRule PriceRule(integer $id = null)
* @method RecurringApplicationCharge RecurringApplicationCharge(integer $id = null)
* @method Redirect Redirect(integer $id = null)
* @method Report Report(integer $id = null)
* @method ScriptTag ScriptTag(integer $id = null)
* @method ShippingZone ShippingZone(integer $id = null)
* @method Shop Shop(integer $id = null)
* @method ShopifyPayment ShopifyPayment()
* @method SmartCollection SmartCollection(integer $id = null)
* @method TenderTransaction TenderTransaction()
* @method Theme Theme(int $id = null)
* @method User User(integer $id = null)
* @method Webhook Webhook(integer $id = null)
* @method GraphQL GraphQL()
*/
class ShopifySDK
{
/**
* List of available resources which can be called from this client
*
* @var string[]
*/
protected $resources = array(
'AbandonedCheckout',
'AssignedFulfillmentOrder',
'AccessScope',
'ApiDeprecations',
'ApplicationCharge',
'Blog',
'CarrierService',
'Cart',
'Collect',
'Collection',
'Comment',
'Country',
'Currency',
'CustomCollection',
'Customer',
'CustomerSavedSearch',
'Discount',
'DiscountCode',
'DraftOrder',
'Event',
'Fulfillment',
'FulfillmentService',
'FulfillmentOrder',
'GiftCard',
'InventoryItem',
'InventoryLevel',
'Location',
'Metafield',
'Multipass',
'Order',
'Page',
'Policy',
'Product',
'ProductListing',
'ProductVariant',
'PriceRule',
'RecurringApplicationCharge',
'Redirect',
'Report',
'ScriptTag',
'ShippingZone',
'Shop',
'SmartCollection',
'ShopifyPayment',
'TenderTransaction',
'Theme',
'User',
'Webhook',
'GraphQL'
);
/**
* @var float microtime of last api call
*/
public static $microtimeOfLastApiCall;
/**
* @var float Minimum gap in seconds to maintain between 2 api calls
*/
public static $timeAllowedForEachApiCall = .5;
/**
* @var string Default Shopify API version
*/
public static $defaultApiVersion = '2025-01';
/**
* Shop / API configurations
*
* @var array
*/
public static $config = array(
);
/**
* List of resources which are only available through a parent resource
*
* @var array Array key is the child resource name and array value is the parent resource name
*/
protected $childResources = array(
'Article' => 'Blog',
'Asset' => 'Theme',
'Balance' => 'ShopifyPayment',
'CustomerAddress' => 'Customer',
'Dispute' => 'ShopifyPayment',
'Fulfillment' => 'Order',
'FulfillmentEvent' => 'Fulfillment',
'GiftCardAdjustment'=> 'GiftCard',
'OrderRisk' => 'Order',
'Payouts' => 'ShopifyPayment',
'ProductImage' => 'Product',
'ProductVariant' => 'Product',
'DiscountCode' => 'PriceRule',
'Province' => 'Country',
'Refund' => 'Order',
'Transaction' => 'Order',
'Transactions' => 'Balance',
'UsageCharge' => 'RecurringApplicationCharge',
);
/*
* ShopifySDK constructor
*
* @param array $config
*
* @return void
*/
public function __construct($config = array())
{
if(!empty($config)) {
ShopifySDK::config($config);
}
}
/**
* Return ShopifyResource instance for a resource.
* @example $shopify->Product->get(); //Returns all available Products
* Called like an object properties (without parenthesis)
*
* @param string $resourceName
*
* @return ShopifyResource
*/
public function __get($resourceName)
{
return $this->$resourceName();
}
/**
* Return ShopifyResource instance for a resource.
* Called like an object method (with parenthesis) optionally with the resource ID as the first argument
* @example $shopify->Product($productID); //Return a specific product defined by $productID
*
* @param string $resourceName
* @param array $arguments
*
* @throws SdkException if the $name is not a valid ShopifyResource resource.
*
* @return ShopifyResource
*/
public function __call($resourceName, $arguments)
{
if (!in_array($resourceName, $this->resources)) {
if (isset($this->childResources[$resourceName])) {
$message = "$resourceName is a child resource of " . $this->childResources[$resourceName] . ". Cannot be accessed directly.";
} else {
$message = "Invalid resource name $resourceName. Pls check the API Reference to get the appropriate resource name.";
}
throw new SdkException($message);
}
$resourceClassName = __NAMESPACE__ . "\\$resourceName";
//If first argument is provided, it will be considered as the ID of the resource.
$resourceID = !empty($arguments) ? $arguments[0] : null;
//Initiate the resource object
$resource = new $resourceClassName($resourceID);
return $resource;
}
/**
* Configure the SDK client
*
* @param array $config
*
* @return ShopifySDK
*/
public static function config($config)
{
/**
* Reset config to it's initial values
*/
self::$config = array(
'ApiVersion' => self::$defaultApiVersion
);
foreach ($config as $key => $value) {
self::$config[$key] = $value;
}
//Re-set the admin url if shop url is changed
if(isset($config['ShopUrl'])) {
self::setAdminUrl();
}
//If want to keep more wait time than .5 seconds for each call
if (isset($config['AllowedTimePerCall'])) {
static::$timeAllowedForEachApiCall = $config['AllowedTimePerCall'];
}
if (isset($config['Curl']) && is_array($config['Curl'])) {
CurlRequest::config($config['Curl']);
}
return new ShopifySDK;
}
/**
* Set the admin url, based on the configured shop url
*
* @return string
*/
public static function setAdminUrl()
{
$shopUrl = self::$config['ShopUrl'];
//Remove https:// and trailing slash (if provided)
$shopUrl = preg_replace('#^https?://|/$#', '', $shopUrl);
$apiVersion = self::$config['ApiVersion'];
if(isset(self::$config['ApiKey']) && isset(self::$config['Password'])) {
$apiKey = self::$config['ApiKey'];
$apiPassword = self::$config['Password'];
$adminUrl = "https://$apiKey:$apiPassword@$shopUrl/admin/";
} else {
$adminUrl = "https://$shopUrl/admin/";
}
self::$config['AdminUrl'] = $adminUrl;
self::$config['ApiUrl'] = $adminUrl . "api/$apiVersion/";
return $adminUrl;
}
/**
* Get the admin url of the configured shop
*
* @return string
*/
public static function getAdminUrl() {
return self::$config['AdminUrl'];
}
/**
* Get the api url of the configured shop
*
* @return string
*/
public static function getApiUrl() {
return self::$config['ApiUrl'];
}
/**
* Returns the appropriate URL for the host that should load the embedded app.
*
* @param string $host The host value received from Shopify
*
* @return string
*/
public static function getEmbeddedAppUrl($host)
{
if (empty($host)) {
throw new SdkException("Host value cannot be empty");
}
$decodedHost = base64_decode($host, true);
if (!$decodedHost) {
throw new SdkException("Host was not a valid base64 string");
}
$apiKey = self::$config['ApiKey'];
return "https://$decodedHost/apps/$apiKey";
}
/**
* Maintain maximum 2 calls per second to the API
*
* @see https://help.shopify.com/api/guides/api-call-limit
*
* @param bool $firstCallWait Whether to maintain the wait time even if it is the first API call
*/
public static function checkApiCallLimit($firstCallWait = false)
{
$timeToWait = 0;
if (static::$microtimeOfLastApiCall == null) {
if ($firstCallWait) {
$timeToWait = static::$timeAllowedForEachApiCall;
}
} else {
$now = microtime(true);
$timeSinceLastCall = $now - static::$microtimeOfLastApiCall;
//Ensure 2 API calls per second
if($timeSinceLastCall < static::$timeAllowedForEachApiCall) {
$timeToWait = static::$timeAllowedForEachApiCall - $timeSinceLastCall;
}
}
if ($timeToWait) {
//convert time to microseconds
$microSecondsToWait = $timeToWait * 1000000;
//Wait to maintain the API call difference of .5 seconds
usleep($microSecondsToWait);
}
static::$microtimeOfLastApiCall = microtime(true);
}
}