forked from XiaoFaye/WooCommerce.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestAPI.cs
499 lines (420 loc) · 21.8 KB
/
RestAPI.cs
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using WooCommerceNET.Base;
namespace WooCommerceNET
{
public class RestAPI
{
protected string wc_url = string.Empty;
protected string wc_key = "";
protected string wc_secret = "";
//private bool wc_Proxy = false;
protected bool AuthorizedHeader { get; set; }
protected Func<string, string> jsonSeFilter;
protected Func<string, string> jsonDeseFilter;
protected Action<HttpWebRequest> webRequestFilter;
protected Action<HttpWebResponse> webResponseFilter;
/// <summary>
/// For Wordpress REST API with OAuth 1.0 ONLY
/// </summary>
public string oauth_token { get; set; }
/// <summary>
/// For Wordpress REST API with OAuth 1.0 ONLY
/// </summary>
public string oauth_token_secret { get; set; }
public WP_JWT_Object JWT_Object { get; set; }
/// <summary>
/// Authenticate Woocommerce API with JWT when set to True
/// </summary>
public bool WCAuthWithJWT { get; set; }
/// <summary>
/// Provide a function to modify the json string before deserilizing, this is for JWT Token ONLY!
/// </summary>
public Func<string, string> JWTDeserializeFilter { get; set; }
/// <summary>
/// Provide a function to modify the HttpWebRequest object, this is for JWT Token ONLY!
/// </summary>
public Action<HttpWebRequest> JWTRequestFilter { get; set; }
/// <summary>
/// If running in Debug mode, default is False.
/// NOTE: Beware when setting Debug to True, as exceptions might contain sensetive information.
/// </summary>
public bool Debug { get; set; }
/// <summary>
/// Initialize the RestAPI object
/// </summary>
/// <param name="url">
/// WooCommerce REST API URL, e.g.: http://yourstore/wp-json/wc/v1/
/// WordPress REST API URL, e.g.: http://yourstore/wp-json/
/// </param>
/// <param name="key">WooCommerce REST API Key Or WordPress consumerKey</param>
/// <param name="secret">WooCommerce REST API Secret Or WordPress consumerSecret</param>
/// <param name="authorizedHeader">WHEN using HTTPS, do you prefer to send the Credentials in HTTP HEADER?</param>
/// <param name="jsonSerializeFilter">Provide a function to modify the json string after serilizing.</param>
/// <param name="jsonDeserializeFilter">Provide a function to modify the json string before deserilizing.</param>
/// <param name="requestFilter">Provide a function to modify the HttpWebRequest object.</param>
/// <param name="responseFilter">Provide a function to grab information from the HttpWebResponse object.</param>
public RestAPI(string url, string key, string secret, bool authorizedHeader = true,
Func<string, string> jsonSerializeFilter = null,
Func<string, string> jsonDeserializeFilter = null,
Action<HttpWebRequest> requestFilter = null,
Action<HttpWebResponse> responseFilter = null)//, bool useProxy = false)
{
if (string.IsNullOrEmpty(url))
throw new Exception("Please use a valid WooCommerce Restful API url.");
string urlLower = url.Trim().ToLower().TrimEnd('/');
if (urlLower.EndsWith("wc-api/v1") || urlLower.EndsWith("wc-api/v2") || urlLower.EndsWith("wc-api/v3"))
Version = APIVersion.Legacy;
else if (urlLower.EndsWith("wp-json/wc/v1"))
Version = APIVersion.Version1;
else if (urlLower.EndsWith("wp-json/wc/v2"))
Version = APIVersion.Version2;
else if (urlLower.EndsWith("wp-json/wc/v3"))
Version = APIVersion.Version3;
else if (urlLower.Contains("wp-json/wc-"))
Version = APIVersion.ThirdPartyPlugins;
else if (urlLower.EndsWith("wp-json/wp/v2") || urlLower.EndsWith("wp-json"))
Version = APIVersion.WordPressAPI;
else if (urlLower.EndsWith("jwt-auth/v1/token"))
{
Version = APIVersion.WordPressAPIJWT;
url = urlLower.Replace("jwt-auth/v1/token", "wp/v2");
}
else
{
Version = APIVersion.Unknown;
throw new Exception("Unknown WooCommerce Restful API version.");
}
wc_url = url + (url.EndsWith("/") ? "" : "/");
wc_key = key;
AuthorizedHeader = authorizedHeader;
//Why extra '&'? look here: https://wordpress.org/support/topic/woocommerce-rest-api-v3-problem-woocommerce_api_authentication_error/
if ((url.ToLower().Contains("wc-api/v3") || !IsLegacy) && !wc_url.StartsWith("https", StringComparison.OrdinalIgnoreCase) && !(Version == APIVersion.WordPressAPI || Version == APIVersion.WordPressAPIJWT))
wc_secret = secret + "&";
else
wc_secret = secret;
jsonSeFilter = jsonSerializeFilter;
jsonDeseFilter = jsonDeserializeFilter;
webRequestFilter = requestFilter;
webResponseFilter = responseFilter;
//wc_Proxy = useProxy;
}
public bool IsLegacy
{
get
{
return Version == APIVersion.Legacy;
}
}
public APIVersion Version { get; private set; }
public string Url { get { return wc_url; } }
/// <summary>
/// Make Restful calls
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="method">HEAD, GET, POST, PUT, PATCH, DELETE</param>
/// <param name="requestBody">If your call doesn't have a body, please pass string.Empty, not null.</param>
/// <param name="parms"></param>
/// <returns>json string</returns>
public virtual async Task<string> SendHttpClientRequest<T>(string endpoint, RequestMethod method, T requestBody, Dictionary<string, string> parms = null)
{
HttpWebRequest httpWebRequest = null;
try
{
if (Version == APIVersion.WordPressAPI)
{
if (string.IsNullOrEmpty(oauth_token) || string.IsNullOrEmpty(oauth_token_secret))
throw new Exception($"oauth_token and oauth_token_secret parameters are required when using WordPress REST API.");
}
if ((Version == APIVersion.WordPressAPIJWT || WCAuthWithJWT) && JWT_Object == null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(wc_url.Replace("wp/v2", "jwt-auth/v1/token")
.Replace("wc/v1", "jwt-auth/v1/token")
.Replace("wc/v2", "jwt-auth/v1/token")
.Replace("wc/v3", "jwt-auth/v1/token"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
if (JWTRequestFilter != null)
JWTRequestFilter.Invoke(request);
var buffer = Encoding.UTF8.GetBytes($"username={wc_key}&password={wc_secret}");
Stream dataStream = await request.GetRequestStreamAsync().ConfigureAwait(false);
dataStream.Write(buffer, 0, buffer.Length);
WebResponse response = await request.GetResponseAsync().ConfigureAwait(false);
Stream resStream = response.GetResponseStream();
string result = await GetStreamContent(resStream, "UTF-8").ConfigureAwait(false);
if (JWTDeserializeFilter != null)
result = JWTDeserializeFilter.Invoke(result);
JWT_Object = DeserializeJSon<WP_JWT_Object>(result);
}
if (wc_url.StartsWith("https", StringComparison.OrdinalIgnoreCase) && Version != APIVersion.WordPressAPI && Version != APIVersion.WordPressAPIJWT)
{
if (AuthorizedHeader == true)
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url + GetOAuthEndPoint(method.ToString(), endpoint, parms));
if (WCAuthWithJWT && JWT_Object != null)
httpWebRequest.Headers["Authorization"] = "Bearer " + JWT_Object.token;
else
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(wc_key + ":" + wc_secret));
}
else
{
if (parms == null)
parms = new Dictionary<string, string>();
if (!parms.ContainsKey("consumer_key"))
parms.Add("consumer_key", wc_key);
if (!parms.ContainsKey("consumer_secret"))
parms.Add("consumer_secret", wc_secret);
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url + GetOAuthEndPoint(method.ToString(), endpoint, parms));
}
}
else
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url + GetOAuthEndPoint(method.ToString(), endpoint, parms));
if (Version == APIVersion.WordPressAPIJWT)
httpWebRequest.Headers["Authorization"] = "Bearer " + JWT_Object.token;
}
// start the stream immediately
httpWebRequest.Method = method.ToString();
httpWebRequest.AllowReadStreamBuffering = false;
if (webRequestFilter != null)
webRequestFilter.Invoke(httpWebRequest);
//if (wc_Proxy)
// httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
//else
// httpWebRequest.Proxy = null;
if (requestBody != null && requestBody.GetType() != typeof(string))
{
httpWebRequest.ContentType = "application/json";
var buffer = Encoding.UTF8.GetBytes(SerializeJSon(requestBody));
Stream dataStream = await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false);
dataStream.Write(buffer, 0, buffer.Length);
}
else
{
if (requestBody != null && requestBody.ToString() != string.Empty)
{
if (requestBody.ToString() == "fileupload")
{
httpWebRequest.Headers["Content-Disposition"] = $"form-data; filename=\"{parms["name"]}\"";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false);
FileStream fileStream = new FileStream(parms["path"], FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
dataStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
else
{
httpWebRequest.ContentType = "application/json";
var buffer = Encoding.UTF8.GetBytes(requestBody.ToString());
Stream dataStream = await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false);
dataStream.Write(buffer, 0, buffer.Length);
}
}
}
// asynchronously get a response
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);
if (webResponseFilter != null)
webResponseFilter.Invoke((HttpWebResponse)wr);
return await GetStreamContent(wr.GetResponseStream(), wr.ContentType.Contains("=") ? wr.ContentType.Split('=')[1] : "UTF-8").ConfigureAwait(false);
}
catch (WebException we)
{
if (httpWebRequest != null && httpWebRequest.HaveResponse)
if (we.Response != null)
throw new WebException(await GetStreamContent(we.Response.GetResponseStream(), we.Response.ContentType.Contains("=") ? we.Response.ContentType.Split('=')[1] : "UTF-8").ConfigureAwait(false), we.InnerException, we.Status, we.Response);
else
throw we;
else
throw we;
}
catch (Exception e)
{
return e.Message;
}
}
public async Task<string> GetRestful(string endpoint, Dictionary<string, string> parms = null)
{
return await SendHttpClientRequest(endpoint, RequestMethod.GET, string.Empty, parms).ConfigureAwait(false);
}
public async Task<string> PostRestful(string endpoint, object jsonObject, Dictionary<string, string> parms = null)
{
return await SendHttpClientRequest(endpoint, RequestMethod.POST, jsonObject, parms).ConfigureAwait(false);
}
public async Task<string> PutRestful(string endpoint, object jsonObject, Dictionary<string, string> parms = null)
{
return await SendHttpClientRequest(endpoint, RequestMethod.PUT, jsonObject, parms).ConfigureAwait(false);
}
public async Task<string> DeleteRestful(string endpoint, Dictionary<string, string> parms = null)
{
return await SendHttpClientRequest(endpoint, RequestMethod.DELETE, string.Empty, parms).ConfigureAwait(false);
}
public async Task<string> DeleteRestful(string endpoint, object jsonObject, Dictionary<string, string> parms = null)
{
return await SendHttpClientRequest(endpoint, RequestMethod.DELETE, jsonObject, parms).ConfigureAwait(false);
}
protected string GetOAuthEndPoint(string method, string endpoint, Dictionary<string, string> parms = null)
{
if (Version == APIVersion.WordPressAPIJWT || (wc_url.StartsWith("https", StringComparison.OrdinalIgnoreCase) && Version != APIVersion.WordPressAPI))
{
if (parms == null)
return endpoint;
else
{
string requestParms = string.Empty;
foreach (var parm in parms)
requestParms += parm.Key + "=" + parm.Value + "&";
return endpoint + "?" + requestParms.TrimEnd('&');
}
}
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("oauth_consumer_key", wc_key);
if (Version == APIVersion.WordPressAPI)
dic.Add("oauth_token", oauth_token);
dic.Add("oauth_nonce", Guid.NewGuid().ToString("N"));
dic.Add("oauth_signature_method", "HMAC-SHA256");
dic.Add("oauth_timestamp", Common.GetUnixTime(false));
dic.Add("oauth_version", "1.0");
if (parms != null)
foreach (var p in parms)
dic.Add(p.Key, p.Value);
string base_request_uri = method.ToUpper() + "&" + Uri.EscapeDataString(wc_url + endpoint) + "&";
string stringToSign = string.Empty;
foreach (var parm in dic.OrderBy(x => x.Key))
stringToSign += Uri.EscapeDataString(parm.Key) + "=" + Uri.EscapeDataString(parm.Value) + "&";
base_request_uri = base_request_uri + Uri.EscapeDataString(stringToSign.TrimEnd('&'));
if (Version == APIVersion.WordPressAPI)
dic.Add("oauth_signature", Common.GetSHA256(wc_secret + "&" + oauth_token_secret, base_request_uri));
else
dic.Add("oauth_signature", Common.GetSHA256(wc_secret, base_request_uri));
string parmstr = string.Empty;
foreach (var parm in dic)
parmstr += parm.Key + "=" + Uri.EscapeDataString(parm.Value) + "&";
return endpoint + "?" + parmstr.TrimEnd('&');
}
protected async Task<string> GetStreamContent(Stream s, string charset)
{
StringBuilder sb = new StringBuilder();
byte[] Buffer = new byte[512];
int count = 0;
count = await s.ReadAsync(Buffer, 0, Buffer.Length).ConfigureAwait(false);
while (count > 0)
{
sb.Append(Encoding.GetEncoding(charset).GetString(Buffer, 0, count));
count = await s.ReadAsync(Buffer, 0, Buffer.Length).ConfigureAwait(false);
}
return sb.ToString();
}
public virtual string SerializeJSon<T>(T t)
{
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings()
{
DateTimeFormat = new DateTimeFormat(DateTimeFormat),
UseSimpleDictionaryFormat = true
};
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ds = new DataContractJsonSerializer(t.GetType(), settings);
ds.WriteObject(stream, t);
byte[] data = stream.ToArray();
string jsonString = Encoding.UTF8.GetString(data, 0, data.Length);
if (t.GetType().GetMethod("FormatJsonS") != null)
{
jsonString = t.GetType().GetMethod("FormatJsonS").Invoke(null, new object[] { jsonString }).ToString();
}
if (IsLegacy)
if (typeof(T).IsArray)
jsonString = "{\"" + typeof(T).Name.ToLower().Replace("[]", "s") + "\":" + jsonString + "}";
else
jsonString = "{\"" + typeof(T).Name.ToLower() + "\":" + jsonString + "}";
stream.Dispose();
if (jsonSeFilter != null)
jsonString = jsonSeFilter.Invoke(jsonString);
return jsonString;
}
public virtual T DeserializeJSon<T>(string jsonString)
{
if (jsonDeseFilter != null)
jsonString = jsonDeseFilter.Invoke(jsonString);
Type dT = typeof(T);
try
{
if (dT.Name.EndsWith("List"))
dT = dT.GetTypeInfo().DeclaredProperties.First().PropertyType.GenericTypeArguments[0];
if (dT.FullName.StartsWith("System.Collections.Generic.List"))
{
dT = dT.GetProperty("Item").PropertyType;
}
if (dT.GetMethod("FormatJsonD") != null)
{
jsonString = dT.GetMethod("FormatJsonD").Invoke(null, new object[] { jsonString }).ToString();
}
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings()
{
DateTimeFormat = new DateTimeFormat(DateTimeFormat),
UseSimpleDictionaryFormat = true
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T), settings);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(stream);
stream.Dispose();
return obj;
}
catch (Exception ex)
{
if (Debug)
throw new Exception(ex.Message + Environment.NewLine + Environment.NewLine + jsonString);
else
throw ex;
}
}
public string DateTimeFormat
{
get
{
return IsLegacy ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:ssK";
}
}
}
public class WP_JWT_Object
{
public string token { get; set; }
public string user_email { get; set; }
public string user_nicename { get; set; }
public string user_display_name { get; set; }
}
public enum RequestMethod
{
HEAD = 1,
GET = 2,
POST = 3,
PUT = 4,
PATCH = 5,
DELETE = 6
}
public enum APIVersion
{
Unknown = 0,
Legacy = 1,
Version1 = 2,
Version2 = 3,
Version3 = 4,
WordPressAPI = 90,
WordPressAPIJWT = 91,
ThirdPartyPlugins = 99
}
}