-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathquickbooks.go
110 lines (88 loc) · 2.37 KB
/
quickbooks.go
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
package quickbooks
import (
"bytes"
"encoding/json"
"net/http"
"github.com/jinmatt/go-quickbooks.v2/sdk"
"github.com/jinmatt/go-quickbooks.v2/sdk/consts"
)
// Quickbooks client type
type Quickbooks struct {
RealmID string
AccessToken string
baseURL string
}
// NewClient creates a new client to work with Quickbooks
func NewClient(realmID string, accessToken string, isSandbox bool) *Quickbooks {
q := Quickbooks{}
q.RealmID = realmID
q.AccessToken = accessToken
if isSandbox {
q.baseURL = sdk.SandboxURL
} else {
q.baseURL = sdk.ProductionURL
}
return &q
}
// makeGetRequest makes a GET request to Quickbooks API.
// endpoint should start with a leading '/'
func (q *Quickbooks) makeGetRequest(endpoint string) (*http.Response, error) {
urlStr := q.baseURL + endpoint
httpClient := &http.Client{}
request, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, err
}
// headers
request.Header.Set("accept", "application/json")
request.Header.Set("Authorization", "Bearer "+q.AccessToken)
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, handleError(response)
}
return response, nil
}
// PostRequest makes a POST request to Quickbooks API.
// endpoint should start with a leading '/'
func (q *Quickbooks) makePostRequest(endpoint string, body interface{}) (*http.Response, error) {
urlStr := q.baseURL + endpoint
httpClient := &http.Client{}
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
request, err := http.NewRequest("POST", urlStr, bytes.NewReader(b))
if err != nil {
return nil, err
}
// headers
request.Header.Set("accept", "application/json")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "Bearer "+q.AccessToken)
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, handleError(response)
}
return response, nil
}
func handleError(response *http.Response) error {
switch response.StatusCode {
case 400:
qbError := ErrorObject{}
err := json.NewDecoder(response.Body).Decode(&qbError)
if err != nil {
return err
}
return qbError
case 401:
sdkError := SDKError{}
return sdkError.New(consts.QBAuthorizationFault, consts.QBAuthenticationFaultCode, consts.QBAuthorizationFaultMessage)
}
return nil
}