-
Notifications
You must be signed in to change notification settings - Fork 6
/
CompanyStore.cs
executable file
·84 lines (69 loc) · 2.41 KB
/
CompanyStore.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
using System;
using System.Net;
using System.Text;
using System.Xml.Serialization;
namespace SyntaxTree.FastSpring.Api
{
public sealed class CompanyStore
{
private readonly StoreCredential _credential;
public CompanyStore(StoreCredential credential)
{
if (credential == null)
throw new ArgumentNullException("credential");
_credential = credential;
}
private static T ParseResponse<T>(WebResponse response)
{
if (response == null)
throw new InvalidOperationException("No response.");
var responseStream = response.GetResponseStream();
if (responseStream == null)
throw new InvalidOperationException("Unable to acquire response stream.");
return (T) new XmlSerializer(typeof (T)).Deserialize(responseStream);
}
public Coupon GenerateCoupon(string prefix)
{
if (prefix == null)
throw new ArgumentNullException("prefix");
if (prefix.Length == 0)
throw new ArgumentException("Prefix is empty.", "prefix");
var request = Request("POST", string.Concat("/coupon/", prefix, "/generate"));
return ParseResponse<Coupon>(request.GetResponse());
}
public Order Order(string reference)
{
if (reference == null)
throw new ArgumentNullException("reference");
if (reference.Length == 0)
throw new ArgumentException("Reference is empty.", "reference");
var request = Request("GET", "/order/" + reference);
return ParseResponse<Order>(request.GetResponse());
}
public OrderSearchResult Orders(string query)
{
if (query == null)
throw new ArgumentNullException("query");
if (query.Length == 0)
throw new ArgumentException("Query is empty.", "query");
var request = Request("GET", "/orders/search?query=" + Uri.EscapeDataString(query));
return ParseResponse<OrderSearchResult>(request.GetResponse());
}
private WebRequest Request(string method, string uri)
{
var request = WebRequest.Create(StoreUri(uri));
request.ContentType = "application/xml";
request.Method = method;
request.Headers["Authorization"] = AuthorizationHeader();
return request;
}
private string AuthorizationHeader()
{
return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(_credential.Username + ":" + _credential.Password));
}
private string StoreUri(string uri)
{
return "https://api.fastspring.com/company/" + _credential.Company + uri;
}
}
}