-
Notifications
You must be signed in to change notification settings - Fork 0
/
ShopifyClient.php
281 lines (229 loc) · 9.82 KB
/
ShopifyClient.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
<?php
class ShopifyClient {
public $shop_domain;
private $token;
private $api_key;
private $secret;
private $last_response_headers = null;
public function __construct($shop_domain, $token, $api_key, $secret) {
$this->name = "ShopifyClient";
$this->shop_domain = $shop_domain;
$this->token = $token;
$this->api_key = $api_key;
$this->secret = $secret;
}
// Get the URL required to request authorization
public function getAuthorizeUrl($scope, $redirect_url='') {
$url = "https://{$this->shop_domain}/admin/oauth/authorize?client_id={$this->api_key}&scope=" . urlencode($scope);
if ($redirect_url != '')
{
$url .= "&redirect_uri=" . urlencode($redirect_url);
}
return $url;
}
// Once the User has authorized the app, call this with the code to get the access token
public function getAccessToken($code) {
// POST to POST https://SHOP_NAME.myshopify.com/admin/oauth/access_token
$url = "https://{$this->shop_domain}/admin/oauth/access_token";
$payload = "client_id={$this->api_key}&client_secret={$this->secret}&code=$code";
$response = $this->curlHttpApiRequest('POST', $url, '', $payload, array());
$response = json_decode($response, true);
if (isset($response['access_token']))
return $response['access_token'];
return '';
}
public function getHeaders(){
return $this->last_response_headers;
}
public function getPageInfo($header){
$next_page_info = '';
$prev_page_info = '';
$splittingPrevNex=preg_split("/,/",$header);
$makingCondition=preg_split("/rel=/",$splittingPrevNex[0]);
$makingCondition=preg_replace('/"/',"",$makingCondition[1]);
if($makingCondition=="previous" && sizeof($splittingPrevNex) > 1) {
// it means we have both next and previous links
$splittingPrevLinks=preg_split("/;/",$splittingPrevNex[0]);
$prev_page_data=preg_split('/\&/',$splittingPrevLinks[0]);
$pattern='/page_info=/';
$replacement='';
$prev_page_info=preg_replace($pattern, $replacement, $prev_page_data);
$pattern='/>/';
$replacement='';
$prev_page_info=preg_replace($pattern, $replacement, $prev_page_info[1]);
$splittingNextLinks=preg_split("/;/",$splittingPrevNex[1]);
$next_page_data=preg_split('/\&/',$splittingNextLinks[0]);
$pattern='/page_info=/';
$replacement='';
$next_page_info=preg_replace($pattern, $replacement, $next_page_data);
$pattern='/>/';
$replacement='';
$next_page_info=preg_replace($pattern, $replacement, $next_page_info[1]);
}
elseif($makingCondition=="previous" && !(sizeof($splittingPrevNex)>1)){
// we have only previous links
$splittingPrevLinks=preg_split("/;/",$splittingPrevNex[0]);
$prev_page_data=preg_split('/\&/',$splittingPrevLinks[0]);
$pattern='/page_info=/';
$replacement='';
$prev_page_info=preg_replace($pattern, $replacement, $prev_page_data);
$pattern='/>/';
$replacement='';
$prev_page_info=preg_replace($pattern, $replacement, $prev_page_info[1]);
}else{
// we have only next links
$splittingNextLinks=preg_split("/;/",$splittingPrevNex[0]);
$next_page_data=preg_split('/\&/',$splittingNextLinks[0]);
$pattern='/page_info=/';
$replacement='';
$next_page_info=preg_replace($pattern, $replacement, $next_page_data);
$pattern='/>/';
$replacement='';
$next_page_info=preg_replace($pattern, $replacement, $next_page_info[1]);
}
//$responseData = json_decode($response, TRUE);
$responseData['next_page']=$next_page_info;
$responseData['prev_page']=$prev_page_info;
return $responseData;
}
public function callsMade()
{
return $this->shopApiCallLimitParam(0);
}
public function callLimit()
{
return $this->shopApiCallLimitParam(1);
}
public function callsLeft($response_headers)
{
return $this->callLimit() - $this->callsMade();
}
public function call($method, $path, $params=array(),$debug = 0)
{
$baseurl = "https://{$this->shop_domain}/";
// if(strpos($path, "/oauth/") === False)
// {
// $updated_path= str_replace("admin/","admin/api/".SHOPIFY_API_CONSTANT,$path);
// $path = $updated_path;
// }
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? json_encode($params) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
// add auth headers
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->token;
$response = $this->curlHttpApiRequest($method, $url, $query, $payload, $request_headers,$debug);
$response = json_decode($response, true);
if($debug){
echo '<pre>';
print_r($response);
echo '</pre>';
}
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
public function validateSignature($query)
{
if(!is_array($query) || empty($query['signature']) || !is_string($query['signature']))
return false;
foreach($query as $k => $v) {
if($k != 'shop' && $k != 'code' && $k != 'timestamp') continue;
$signature[] = $k . '=' . $v;
}
sort($signature);
$signature = md5($this->secret . implode('', $signature));
return $query['signature'] == $signature;
}
private function curlHttpApiRequest($method, $url, $query='', $payload='', $request_headers=array(),$debug = 0)
{
$url = $this->curlAppendQuery($url, $query);
$ch = curl_init($url);
$this->curlSetopts($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$this->last_response_headers = $this->curlParseHeaders($message_headers);
if($debug){
echo '<pre>';
print_r($response);
echo '</pre>';
echo $message_headers;
}
return $message_body;
}
private function curlAppendQuery($url, $query)
{
if (empty($query)) return $url;
if (is_array($query)) return "$url?".http_build_query($query);
else return "$url?$query";
}
private function curlSetopts($ch, $method, $payload, $request_headers)
{
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'ohShopify-php-api-client');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($request_headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && !empty($payload))
{
if (is_array($payload)) $payload = http_build_query($payload);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
}
}
private function curlParseHeaders($message_headers)
{
$header_lines = preg_split("/\r\n|\n|\r/", $message_headers);
$headers = array();
list(, $headers['http_status_code'], $headers['http_status_message']) = explode(' ', trim(array_shift($header_lines)), 3);
foreach ($header_lines as $header_line)
{
list($name, $value) = explode(':', $header_line, 2);
$name = strtolower($name);
$headers[$name] = trim($value);
}
return $headers;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
throw new Exception('Cannot be called before an API call.');
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
}
class ShopifyCurlException extends Exception { }
class ShopifyApiException extends Exception
{
protected $method;
protected $path;
protected $params;
protected $response_headers;
protected $response;
function __construct($method, $path, $params, $response_headers, $response)
{
$this->method = $method;
$this->path = $path;
$this->params = $params;
$this->response_headers = $response_headers;
$this->response = $response;
parent::__construct($response_headers['http_status_message'], $response_headers['http_status_code']);
}
function getMethod() { return $this->method; }
function getPath() { return $this->path; }
function getParams() { return $this->params; }
function getResponseHeaders() { return $this->response_headers; }
function getResponse() { return $this->response; }
}
?>