-
Notifications
You must be signed in to change notification settings - Fork 11
/
customers.go
334 lines (320 loc) · 10.4 KB
/
customers.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
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
package bigcommerce
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
)
// Customer is a struct for the BigCommerce Customer API
type Customer struct {
ID int64 `json:"id"`
Company string `json:"company"`
Firstname string `json:"first_name"`
Lastname string `json:"last_name"`
Email string `json:"email"`
Phone string `json:"phone"`
FormFields interface{} `json:"form_fields"`
DateCreated string `json:"date_created"`
DateModified string `json:"date_modified"`
StoreCredit string `json:"store_credit"`
RegistrationIP string `json:"registration_ip_address"`
CustomerGroup int64 `json:"customer_group_id"`
Notes string `json:"notes"`
TaxExempt string `json:"tax_exempt_category"`
ResetPassword bool `json:"reset_pass_on_login"`
AcceptsMarketing bool `json:"accepts_marketing"`
Addresses []Address `json:"addresses"`
}
type SaveAccountPayload struct {
ID int64 `json:"id"`
Company string `json:"company,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
Notes string `json:"notes,omitempty"`
TaxExemptCategory string `json:"tax_exempt_category,omitempty"`
CustomerGroupID int64 `json:"customer_group_id,omitempty"`
Addresses []Address `json:"addresses,omitempty"`
Authentication struct {
ForcePasswordReset bool `json:"force_password_reset,omitempty"`
NewPassword string `json:"new_password,omitempty"`
} `json:"authentication,omitempty"`
AcceptsProductReviewAbandonedCartEmails bool `json:"accepts_product_review_abandoned_cart_emails,omitempty"`
StoreCreditAmounts []struct {
Amount float64 `json:"amount,omitempty"`
} `json:"store_credit_amounts,omitempty"`
OriginChannelID int `json:"origin_channel_id,omitempty"`
ChannelIDs []int `json:"channel_ids,omitempty"`
FormFields []struct {
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"form_fields,omitempty"`
}
type CreateAccountPayload struct {
Company string `json:"company,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
Notes string `json:"notes,omitempty"`
TaxExemptCategory string `json:"tax_exempt_category,omitempty"`
CustomerGroupID int64 `json:"customer_group_id,omitempty"`
Addresses []Address `json:"addresses,omitempty"`
Authentication Authentication `json:"authentication,omitempty"`
AcceptsProductReviewAbandonedCartEmails bool `json:"accepts_product_review_abandoned_cart_emails,omitempty"`
StoreCreditAmounts []StoreCredit `json:"store_credit_amounts,omitempty"`
OriginChannelID int `json:"origin_channel_id,omitempty"`
ChannelIDs []int `json:"channel_ids,omitempty"`
}
// StoreCredit is for CreateAccountPayload's store_credit_ammounts field
type StoreCredit struct {
Amount float64 `json:"amount"`
}
// AccountAuthentication is for CreateAccountPayload's authentication field
type Authentication struct {
ForcePasswordReset bool `json:"force_password_reset"`
Password string `json:"new_password"`
}
// FormField is a struct for the BigCommerce Customer API Form Fiel values
type FormField struct {
CustomerID int64 `json:"customer_id"`
Name string `json:"name"`
Value string `json:"value"`
}
// ValidateCredentials returns customer ID or error (i.e. ErrNotfound) if the provided credentials are valid in BigCommerce
func (bc *Client) ValidateCredentials(email, password string) (int64, error) {
var credReq struct {
Email string `json:"email"`
Password string `json:"password"`
ChannelID int `json:"channel_id"`
}
credReq.Email = email
credReq.Password = password
credReq.ChannelID = bc.ChannelID
var b []byte
b, _ = json.Marshal(credReq)
req := bc.getAPIRequest(http.MethodPost, "/v3/customers/validate-credentials", bytes.NewBuffer(b))
res, err := bc.HTTPClient.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
return 0, err
}
var credResptype struct {
IsValid bool `json:"is_valid"`
CustomerID int64 `json:"customer_id"`
}
err = json.Unmarshal(body, &credResptype)
if err != nil {
return 0, err
}
if !credResptype.IsValid {
return 0, ErrNotFound
}
return credResptype.CustomerID, nil
}
// CreateAccount creates a new customer account in BigCommerce and returns the customer or error
func (bc *Client) CreateAccount(payload *CreateAccountPayload) (*Customer, error) {
if payload.OriginChannelID == 0 {
payload.OriginChannelID = bc.ChannelID
}
if payload.ChannelIDs == nil {
payload.ChannelIDs = []int{bc.ChannelID}
}
var b []byte
b, _ = json.Marshal([]CreateAccountPayload{*payload})
req := bc.getAPIRequest(http.MethodPost, "/v3/customers", bytes.NewBuffer(b))
res, err := bc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
if res.StatusCode == http.StatusUnprocessableEntity {
var errResp ErrorResult
err = json.Unmarshal(body, &errResp)
if err != nil {
log.Printf("Error: %s\nResult: %s", err, string(body))
return nil, err
}
if len(errResp.Errors) > 0 {
errors := []string{}
for _, e := range errResp.Errors {
errors = append(errors, e)
}
return nil, fmt.Errorf("%s", strings.Join(errors, ", "))
}
return nil, errors.New("unknown error")
}
log.Printf("Error: %s\nResult: %s", err, string(body))
return nil, err
}
var ret struct {
Customers []Customer `json:"data"`
}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
return &ret.Customers[0], nil
}
// SaveAccount saves an exising customer account in BigCommerce and returns the customer or error
func (bc *Client) SaveAccount(payload *SaveAccountPayload) (*Customer, error) {
if payload.OriginChannelID == 0 {
payload.OriginChannelID = bc.ChannelID
}
if payload.ChannelIDs == nil {
payload.ChannelIDs = []int{bc.ChannelID}
}
var b []byte
b, _ = json.Marshal([]SaveAccountPayload{*payload})
req := bc.getAPIRequest(http.MethodPut, "/v3/customers", bytes.NewBuffer(b))
res, err := bc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
if res.StatusCode == http.StatusUnprocessableEntity {
var errResp ErrorResult
err = json.Unmarshal(body, &errResp)
if err != nil {
log.Printf("Error: %s\nResult: %s", err, string(body))
return nil, err
}
if len(errResp.Errors) > 0 {
errors := []string{}
for _, e := range errResp.Errors {
errors = append(errors, e)
}
return nil, fmt.Errorf("%s", strings.Join(errors, ", "))
}
return nil, errors.New("unknown error")
}
log.Printf("Error: %s\nResult: %s", err, string(body))
return nil, err
}
var ret struct {
Customers []Customer `json:"data"`
}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
return &ret.Customers[0], nil
}
// CustomerSetFormFields sets the form fields for a customer
func (bc *Client) CustomerSetFormFields(customerID int64, formFields []FormField) error {
if customerID == 0 {
return errors.New("customerID cannot be 0")
}
for i := range formFields {
formFields[i].CustomerID = customerID
}
var b []byte
b, _ = json.Marshal(formFields)
log.Printf("Fields: %s", string(b))
req := bc.getAPIRequest(http.MethodPut, "/v3/customers/form-field-values", bytes.NewBuffer(b))
res, err := bc.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
if res.StatusCode == http.StatusUnprocessableEntity {
var errResp ErrorResult
err = json.Unmarshal(body, &errResp)
if err != nil {
log.Printf("Error: %s\nResult: %s", err, string(body))
return err
}
if len(errResp.Errors) > 0 {
errors := []string{}
for _, e := range errResp.Errors {
errors = append(errors, e)
}
return fmt.Errorf("%s", strings.Join(errors, ", "))
}
return errors.New("unknown error")
}
return err
}
return nil
}
func (bc *Client) CustomerGetFormFields(customerID int64) ([]FormField, error) {
req := bc.getAPIRequest(http.MethodGet, fmt.Sprintf("/v3/customers/form-field-values?customer_id=%d", customerID), nil)
res, err := bc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
return nil, err
}
var ret struct {
Data []FormField `json:"data"`
}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
log.Printf("Form fields: %s", string(body))
return ret.Data, nil
}
func (bc *Client) GetCustomerByID(customerID int64) (*Customer, error) {
req := bc.getAPIRequest(http.MethodGet, fmt.Sprintf("/v3/customers?id:in=%d", customerID), nil)
res, err := bc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
return nil, err
}
var ret struct {
Data []Customer `json:"data"`
}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
if len(ret.Data) == 0 {
return nil, ErrNotFound
}
return &ret.Data[0], nil
}
func (bc *Client) GetCustomerByEmail(email string) (*Customer, error) {
req := bc.getAPIRequest(http.MethodGet, fmt.Sprintf("/v3/customers?email:in=%s", email), nil)
res, err := bc.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := processBody(res)
if err != nil {
return nil, err
}
var ret struct {
Data []Customer `json:"data"`
}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, err
}
if len(ret.Data) == 0 {
return nil, ErrNotFound
}
return &ret.Data[0], nil // return the first customer
}