@@ -68,7 +68,12 @@ class ShopifySDK
68
68
/**
69
69
* @var float microtime of last api call
70
70
*/
71
- public static $ microtimeOfLastAPICall ;
71
+ public static $ microtimeOfLastApiCall ;
72
+
73
+ /**
74
+ * @var float Minimum gap in seconds to maintain between 2 api calls
75
+ */
76
+ public static $ timeAllowedForEachApiCall = .5 ;
72
77
73
78
/**
74
79
* Shop / API configurations
@@ -216,6 +221,10 @@ public static function config($config)
216
221
self ::setAdminUrl ();
217
222
}
218
223
224
+ if (isset ($ config ['AllowedTimePerCall ' ])) {
225
+ static ::$ timeAllowedForEachApiCall = $ config ['AllowedTimePerCall ' ];
226
+ }
227
+
219
228
return new ShopifySDK ;
220
229
}
221
230
@@ -256,26 +265,33 @@ public static function getAdminUrl() {
256
265
/**
257
266
* Maintain maximum 2 calls per second to the API
258
267
*
268
+ * @see https://help.shopify.com/api/guides/api-call-limit
269
+ *
259
270
* @param bool $firstCallWait Whether to maintain the wait time even if it is the first API call
260
271
*/
261
272
public static function checkApiCallLimit ($ firstCallWait = false )
262
273
{
263
- if (static ::$ microtimeOfLastAPICall == null ) {
274
+ $ timeToWait = 0 ;
275
+ if (static ::$ microtimeOfLastApiCall == null ) {
264
276
if ($ firstCallWait ) {
265
- usleep ( 500000 ) ;
277
+ $ timeToWait = static :: $ timeAllowedForEachApiCall ;
266
278
}
267
279
} else {
268
280
$ now = microtime (true );
269
- $ timeSinceLastCall = $ now - static ::$ microtimeOfLastAPICall ;
281
+ $ timeSinceLastCall = $ now - static ::$ microtimeOfLastApiCall ;
270
282
//Ensure 2 API calls per second
271
- if ($ timeSinceLastCall < .5 ) {
272
- $ timeToWait = .5 - $ timeSinceLastCall ;
273
- //convert time to microseconds
274
- $ microSecondsToWait = $ timeToWait * 1000000 ;
275
- //Wait to maintain the API call difference of .5 seconds
276
- usleep ($ microSecondsToWait );
283
+ if ($ timeSinceLastCall < static ::$ timeAllowedForEachApiCall ) {
284
+ $ timeToWait = static ::$ timeAllowedForEachApiCall - $ timeSinceLastCall ;
277
285
}
278
286
}
279
- static ::$ microtimeOfLastAPICall = microtime (true );
287
+
288
+ if ($ timeToWait ) {
289
+ //convert time to microseconds
290
+ $ microSecondsToWait = $ timeToWait * 1000000 ;
291
+ //Wait to maintain the API call difference of .5 seconds
292
+ usleep ($ microSecondsToWait );
293
+ }
294
+
295
+ static ::$ microtimeOfLastApiCall = microtime (true );
280
296
}
281
297
}
0 commit comments