forked from customerio/go-customerio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
customerio.go
391 lines (336 loc) · 10.7 KB
/
customerio.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
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
package customerio
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
)
const DefaultUserAgent = "Customer.io Go Client/" + Version
// CustomerIO wraps the customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction
type CustomerIO struct {
siteID string
apiKey string
URL string
UserAgent string
Client *http.Client
}
// CustomerIOError is returned by any method that fails at the API level
type CustomerIOError struct {
status int
url string
body []byte
}
func (e *CustomerIOError) Error() string {
return fmt.Sprintf("%v: %v %v", e.status, e.url, string(e.body))
}
// ParamError is an error returned if a parameter to the track API is invalid.
type ParamError struct {
Param string // Param is the name of the parameter.
}
func (e ParamError) Error() string { return e.Param + ": missing" }
// NewTrackClient prepares a client for use with the Customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction
// using a Tracking Site ID and API Key pair from https://fly.customer.io/settings/api_credentials
func NewTrackClient(siteID, apiKey string, opts ...option) *CustomerIO {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 100,
},
}
c := &CustomerIO{
siteID: siteID,
apiKey: apiKey,
URL: "https://track.customer.io",
UserAgent: DefaultUserAgent,
Client: client,
}
for _, opt := range opts {
opt.track(c)
}
return c
}
// NewCustomerIO prepares a client for use with the Customer.io track API, see: https://customer.io/docs/api/#apitrackintroduction
// deprecated in favour of NewTrackClient
func NewCustomerIO(siteID, apiKey string) *CustomerIO {
return NewTrackClient(siteID, apiKey)
}
// IdentifyCtx identifies a customer and sets their attributes
func (c *CustomerIO) IdentifyCtx(ctx context.Context, customerID string, attributes map[string]interface{}) error {
if customerID == "" {
return ParamError{Param: "customerID"}
}
_, err := c.request(ctx, "PUT",
fmt.Sprintf("%s/api/v1/customers/%s", c.URL, url.PathEscape(customerID)),
attributes)
return err
}
// Identify identifies a customer and sets their attributes
func (c *CustomerIO) Identify(customerID string, attributes map[string]interface{}) error {
return c.IdentifyCtx(context.Background(), customerID, attributes)
}
// TrackCtx sends a single event to Customer.io for the supplied user
func (c *CustomerIO) TrackCtx(ctx context.Context, customerID string, eventName string, data map[string]interface{}) error {
if customerID == "" {
return ParamError{Param: "customerID"}
}
if eventName == "" {
return ParamError{Param: "eventName"}
}
_, err := c.request(ctx, "POST",
fmt.Sprintf("%s/api/v1/customers/%s/events", c.URL, url.PathEscape(customerID)),
map[string]interface{}{
"name": eventName,
"data": data,
})
return err
}
// Track sends a single event to Customer.io for the supplied user
func (c *CustomerIO) Track(customerID string, eventName string, data map[string]interface{}) error {
return c.TrackCtx(context.Background(), customerID, eventName, data)
}
// TrackAnonymousCtx sends a single event to Customer.io for the anonymous user
func (c *CustomerIO) TrackAnonymousCtx(ctx context.Context, anonymousID, eventName string, data map[string]interface{}) error {
if eventName == "" {
return ParamError{Param: "eventName"}
}
payload := map[string]interface{}{
"name": eventName,
"data": data,
}
if anonymousID != "" {
payload["anonymous_id"] = anonymousID
}
_, err := c.request(ctx, "POST", fmt.Sprintf("%s/api/v1/events", c.URL), payload)
return err
}
// TrackAnonymous sends a single event to Customer.io for the anonymous user
func (c *CustomerIO) TrackAnonymous(anonymousID, eventName string, data map[string]interface{}) error {
return c.TrackAnonymousCtx(context.Background(), anonymousID, eventName, data)
}
// DeleteCtx deletes a customer
func (c *CustomerIO) DeleteCtx(ctx context.Context, customerID string) error {
if customerID == "" {
return ParamError{Param: "customerID"}
}
_, err := c.request(ctx, "DELETE",
fmt.Sprintf("%s/api/v1/customers/%s", c.URL, url.PathEscape(customerID)),
nil)
return err
}
// Delete deletes a customer
func (c *CustomerIO) Delete(customerID string) error {
return c.DeleteCtx(context.Background(), customerID)
}
// AddDeviceCtx adds a device for a customer
func (c *CustomerIO) AddDeviceCtx(ctx context.Context, customerID string, deviceID string, platform string, data map[string]interface{}) error {
if customerID == "" {
return ParamError{Param: "customerID"}
}
if deviceID == "" {
return ParamError{Param: "deviceID"}
}
if platform == "" {
return ParamError{Param: "platform"}
}
body := map[string]map[string]interface{}{
"device": {
"id": deviceID,
"platform": platform,
},
}
for k, v := range data {
body["device"][k] = v
}
_, err := c.request(ctx, "PUT",
fmt.Sprintf("%s/api/v1/customers/%s/devices", c.URL, url.PathEscape(customerID)),
body)
return err
}
// AddDevice adds a device for a customer
func (c *CustomerIO) AddDevice(customerID string, deviceID string, platform string, data map[string]interface{}) error {
return c.AddDeviceCtx(context.Background(), customerID, deviceID, platform, data)
}
// DeleteDeviceCtx deletes a device for a customer
func (c *CustomerIO) DeleteDeviceCtx(ctx context.Context, customerID string, deviceID string) error {
if customerID == "" {
return ParamError{Param: "customerID"}
}
if deviceID == "" {
return ParamError{Param: "deviceID"}
}
_, err := c.request(ctx, "DELETE",
fmt.Sprintf("%s/api/v1/customers/%s/devices/%s", c.URL, url.PathEscape(customerID), url.PathEscape(deviceID)),
nil)
return err
}
// DeleteDevice deletes a device for a customer
func (c *CustomerIO) DeleteDevice(customerID string, deviceID string) error {
return c.DeleteDeviceCtx(context.Background(), customerID, deviceID)
}
func (c *CustomerIO) auth() string {
return base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", c.siteID, c.apiKey)))
}
func (c *CustomerIO) request(ctx context.Context, method, url string, body interface{}) ([]byte, error) {
var req *http.Request
if body != nil {
j, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err = http.NewRequestWithContext(ctx, method, url, bytes.NewBuffer(j))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(j)))
} else {
var err error
req, err = http.NewRequestWithContext(ctx, method, url, nil)
if err != nil {
return nil, err
}
}
req.Header.Add("Authorization", fmt.Sprintf("Basic %v", c.auth()))
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, &CustomerIOError{
status: resp.StatusCode,
url: url,
body: responseBody,
}
}
return responseBody, nil
}
type IdentifierType string
const (
IdentifierTypeID IdentifierType = "id"
IdentifierTypeEmail IdentifierType = "email"
IdentifierTypeCioID IdentifierType = "cio_id"
IdentifierTypeName IdentifierType = "name"
IdentifierTypeCioObjectID IdentifierType = "cio_object_id"
IdentifierTypeObjectID IdentifierType = "object_id"
)
type Identifier struct {
Type IdentifierType
Value string
}
func (id Identifier) kv() map[string]string {
return map[string]string{
string(id.Type): id.Value,
}
}
func (id Identifier) validate() error {
if !(id.Type == IdentifierTypeID ||
id.Type == IdentifierTypeEmail ||
id.Type == IdentifierTypeCioID) {
return errors.New("invalid id type")
}
if strings.TrimSpace(id.Value) == "" {
return errors.New("invalid id")
}
return nil
}
// MergeCustomersCtx sends a request to Customer.io to merge two customer profiles together.
func (c *CustomerIO) MergeCustomersCtx(ctx context.Context, primary Identifier, secondary Identifier) error {
if primary.validate() != nil {
return ParamError{Param: "primary"}
}
if secondary.validate() != nil {
return ParamError{Param: "secondary"}
}
_, err := c.request(ctx, "POST",
fmt.Sprintf("%s/api/v1/merge_customers", c.URL),
map[string]interface{}{
"primary": primary.kv(),
"secondary": secondary.kv(),
})
return err
}
type RegionResponse struct {
Url string `json:"url"`
Region string `json:"region"`
EnvironmentId int `json:"environment_id"`
}
func (c *CustomerIO) Region(ctx context.Context) (RegionResponse, error) {
body, err := c.request(ctx, "GET",
fmt.Sprintf("%s/api/v1/accounts/region", c.URL),
nil,
)
if err != nil {
return RegionResponse{}, err
}
r := RegionResponse{}
err = json.Unmarshal(body, &r)
if err != nil {
return RegionResponse{}, err
}
return r, nil
}
// MergeCustomers sends a request to Customer.io to merge two customer profiles together.
func (c *CustomerIO) MergeCustomers(primary Identifier, secondary Identifier) error {
return c.MergeCustomersCtx(context.Background(), primary, secondary)
}
func (c *CustomerIO) AddOrUpdate(ctx context.Context, id string, req *Customer) error {
outgoingAtts := map[string]interface{}{}
for k, v := range req.Attributes {
outgoingAtts[k] = v
}
if req.CreatedAt != nil {
outgoingAtts["created_at"] = req.CreatedAt.UTC().Unix()
}
if req.Email != "" {
outgoingAtts["email"] = req.Email
}
if req.ID != "" {
outgoingAtts["id"] = req.ID
}
if req.Unsubscribed != nil {
outgoingAtts["unsubscribed"] = req.Unsubscribed
}
url := fmt.Sprintf("%s/api/v1/customers/%s", c.URL, id)
_, err := c.request(ctx, "PUT", url, outgoingAtts)
if err != nil {
return err
}
return nil
}
// AddCustomersToSegment adds customers to an existing manual segment. The
// customers will be identified by the specified identifier type. Customers
// without a value for that identifier will be skipped. The first return value
// is the number of identities that we attempted to add to the segment.
func (c *CustomerIO) AddCustomersToSegment(ctx context.Context, segmentID int, customers []Customer, identifier IdentifierType) (int, error) {
identifiers := make([]string, 0, len(customers))
for _, customer := range customers {
switch identifier {
case IdentifierTypeID:
identifiers = append(identifiers, customer.ID)
case IdentifierTypeEmail:
identifiers = append(identifiers, customer.Email)
case IdentifierTypeCioID:
identifiers = append(identifiers, customer.CioID)
}
}
_, err := c.request(ctx, http.MethodPost,
fmt.Sprintf("%s/api/v1/segments/%d/add_customers?id_type=%s", c.URL, segmentID, identifier),
map[string]interface{}{
"ids": identifiers,
},
)
return len(identifiers), err
}