-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathincognia.go
467 lines (394 loc) · 11.7 KB
/
incognia.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
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
package incognia
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"runtime/debug"
"strings"
"time"
)
const (
defaultNetClientTimeout = 5 * time.Second
)
var (
ErrMissingPayment = errors.New("missing payment parameters")
ErrMissingLogin = errors.New("missing login parameters")
ErrMissingSignup = errors.New("missing signup parameters")
ErrMissingInstallationID = errors.New("missing installation id")
ErrMissingInstallationIDOrSessionToken = errors.New("missing installation id or session token")
ErrMissingIdentifier = errors.New("missing installation id, request token or session token")
ErrMissingAccountID = errors.New("missing account id")
ErrMissingSignupID = errors.New("missing signup id")
ErrMissingClientIDOrClientSecret = errors.New("client id and client secret are required")
ErrConfigIsNil = errors.New("incognia client config is required")
)
type Client struct {
clientID string
clientSecret string
tokenProvider TokenProvider
netClient *http.Client
endpoints *endpoints
UserAgent string
}
type IncogniaClientConfig struct {
ClientID string
ClientSecret string
TokenProvider TokenProvider
Timeout time.Duration
TokenRouteTimeout time.Duration
HTTPClient *http.Client
}
type Payment struct {
InstallationID *string
SessionToken *string
RequestToken string
AppVersion string
DeviceOs string
AccountID string
ExternalID string
PolicyID string
Coupon *CouponType
Addresses []*TransactionAddress
Value *PaymentValue
Methods []*PaymentMethod
Eval *bool
CustomProperties map[string]interface{}
}
type Login struct {
InstallationID *string
SessionToken *string
RequestToken string
AccountID string
ExternalID string
PolicyID string
PaymentMethodIdentifier string
Eval *bool
AppVersion string
DeviceOs string
CustomProperties map[string]interface{}
}
type FeedbackIdentifiers struct {
InstallationID string
SessionToken string
RequestToken string
LoginID string
PaymentID string
SignupID string
AccountID string
ExternalID string
}
type Address struct {
Coordinates *Coordinates
StructuredAddress *StructuredAddress
AddressLine string
}
type Signup struct {
InstallationID string
RequestToken string
SessionToken string
AppVersion string
DeviceOs string
Address *Address
AccountID string
PolicyID string
ExternalID string
}
func New(config *IncogniaClientConfig) (*Client, error) {
if config == nil {
return nil, ErrConfigIsNil
}
if config.ClientID == "" || config.ClientSecret == "" {
return nil, ErrMissingClientIDOrClientSecret
}
timeout := config.Timeout
if timeout == 0 {
timeout = defaultNetClientTimeout
}
netClient := config.HTTPClient
if netClient == nil {
netClient = &http.Client{
Timeout: timeout,
}
}
tokenRouteTimeout := config.TokenRouteTimeout
if tokenRouteTimeout == 0 {
tokenRouteTimeout = defaultNetClientTimeout
}
tokenClient := NewTokenClient(&TokenClientConfig{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Timeout: tokenRouteTimeout,
})
libVersion := "unknown"
if buildInfo, ok := debug.ReadBuildInfo(); ok {
for _, dep := range buildInfo.Deps {
if dep.Path == "repo.incognia.com/go/incognia" {
libVersion = dep.Version
}
}
}
userAgent := fmt.Sprintf(
"incognia-api-go/%s (%s %s) Go/%s",
libVersion,
runtime.GOOS,
runtime.GOARCH,
runtime.Version(),
)
tokenProvider := config.TokenProvider
if tokenProvider == nil {
tokenProvider = NewAutoRefreshTokenProvider(tokenClient)
}
endpoints := getEndpoints()
return &Client{clientID: config.ClientID, clientSecret: config.ClientSecret, tokenProvider: tokenProvider, netClient: netClient, endpoints: &endpoints, UserAgent: userAgent}, nil
}
func (c *Client) RegisterSignup(installationID string, address *Address) (ret *SignupAssessment, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
ret = nil
}
}()
return c.registerSignup(&Signup{
InstallationID: installationID,
Address: address,
})
}
func (c *Client) RegisterSignupWithParams(params *Signup) (ret *SignupAssessment, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
ret = nil
}
}()
return c.registerSignup(params)
}
func (c *Client) registerSignup(params *Signup) (ret *SignupAssessment, err error) {
if params == nil {
return nil, ErrMissingSignup
}
if params.InstallationID == "" && params.RequestToken == "" && params.SessionToken == "" {
return nil, ErrMissingIdentifier
}
requestBody := postAssessmentRequestBody{
InstallationID: params.InstallationID,
RequestToken: params.RequestToken,
SessionToken: params.SessionToken,
AccountID: params.AccountID,
PolicyID: params.PolicyID,
ExternalID: params.ExternalID,
AppVersion: params.AppVersion,
DeviceOs: strings.ToLower(params.DeviceOs),
}
if params.Address != nil {
requestBody.AddressLine = params.Address.AddressLine
requestBody.StructuredAddress = params.Address.StructuredAddress
requestBody.Coordinates = params.Address.Coordinates
}
requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoints.Signups, bytes.NewBuffer(requestBodyBytes))
if err != nil {
return nil, err
}
var signupAssessment SignupAssessment
err = c.doRequest(req, &signupAssessment)
if err != nil {
return nil, err
}
return &signupAssessment, nil
}
func (c *Client) RegisterFeedback(feedbackEvent FeedbackType, occurredAt *time.Time, feedbackIdentifiers *FeedbackIdentifiers) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
return c.registerFeedback(feedbackEvent, occurredAt, nil, feedbackIdentifiers)
}
func (c *Client) RegisterFeedbackWithExpiration(feedbackEvent FeedbackType, occurredAt *time.Time, expiresAt *time.Time, feedbackIdentifiers *FeedbackIdentifiers) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
return c.registerFeedback(feedbackEvent, occurredAt, expiresAt, feedbackIdentifiers)
}
func (c *Client) registerFeedback(feedbackEvent FeedbackType, occurredAt *time.Time, expiresAt *time.Time, feedbackIdentifiers *FeedbackIdentifiers) (err error) {
requestBody := postFeedbackRequestBody{
Event: feedbackEvent,
OccurredAt: occurredAt,
ExpiresAt: expiresAt,
}
if feedbackIdentifiers != nil {
requestBody.InstallationID = feedbackIdentifiers.InstallationID
requestBody.SessionToken = feedbackIdentifiers.SessionToken
requestBody.RequestToken = feedbackIdentifiers.RequestToken
requestBody.LoginID = feedbackIdentifiers.LoginID
requestBody.PaymentID = feedbackIdentifiers.PaymentID
requestBody.SignupID = feedbackIdentifiers.SignupID
requestBody.AccountID = feedbackIdentifiers.AccountID
requestBody.ExternalID = feedbackIdentifiers.ExternalID
}
requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return err
}
req, err := http.NewRequest("POST", c.endpoints.Feedback, bytes.NewBuffer(requestBodyBytes))
if err != nil {
return err
}
err = c.doRequest(req, nil)
if err != nil {
return err
}
return nil
}
func (c *Client) RegisterPayment(payment *Payment) (ret *TransactionAssessment, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
ret = nil
}
}()
return c.registerPayment(payment)
}
func (c *Client) registerPayment(payment *Payment) (ret *TransactionAssessment, err error) {
if payment == nil {
return nil, ErrMissingPayment
}
if payment.InstallationID == nil && payment.SessionToken == nil && payment.RequestToken == "" {
return nil, ErrMissingIdentifier
}
if payment.AccountID == "" {
return nil, ErrMissingAccountID
}
requestBody, err := json.Marshal(postTransactionRequestBody{
InstallationID: payment.InstallationID,
RequestToken: payment.RequestToken,
SessionToken: payment.SessionToken,
Type: paymentType,
AccountID: payment.AccountID,
PolicyID: payment.PolicyID,
Coupon: payment.Coupon,
ExternalID: payment.ExternalID,
Addresses: payment.Addresses,
PaymentValue: payment.Value,
PaymentMethods: payment.Methods,
AppVersion: payment.AppVersion,
DeviceOs: strings.ToLower(payment.DeviceOs),
CustomProperties: payment.CustomProperties,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoints.Transactions, bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
if payment.Eval != nil {
q := req.URL.Query()
q.Add("eval", fmt.Sprintf("%t", *payment.Eval))
req.URL.RawQuery = q.Encode()
}
var paymentAssesment TransactionAssessment
err = c.doRequest(req, &paymentAssesment)
if err != nil {
return nil, err
}
return &paymentAssesment, nil
}
func (c *Client) RegisterLogin(login *Login) (ret *TransactionAssessment, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
ret = nil
}
}()
return c.registerLogin(login)
}
func (c *Client) registerLogin(login *Login) (*TransactionAssessment, error) {
if login == nil {
return nil, ErrMissingLogin
}
if login.InstallationID == nil && login.SessionToken == nil && login.RequestToken == "" {
return nil, ErrMissingIdentifier
}
if login.AccountID == "" {
return nil, ErrMissingAccountID
}
requestBody, err := json.Marshal(postTransactionRequestBody{
InstallationID: login.InstallationID,
Type: loginType,
AccountID: login.AccountID,
PolicyID: login.PolicyID,
ExternalID: login.ExternalID,
PaymentMethodIdentifier: login.PaymentMethodIdentifier,
SessionToken: login.SessionToken,
RequestToken: login.RequestToken,
AppVersion: login.AppVersion,
DeviceOs: strings.ToLower(login.DeviceOs),
CustomProperties: login.CustomProperties,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoints.Transactions, bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
if login.Eval != nil {
q := req.URL.Query()
q.Add("eval", fmt.Sprintf("%t", *login.Eval))
req.URL.RawQuery = q.Encode()
}
var loginAssessment TransactionAssessment
err = c.doRequest(req, &loginAssessment)
if err != nil {
return nil, err
}
return &loginAssessment, nil
}
func (c *Client) doRequest(request *http.Request, response interface{}) error {
request.Header.Add("Content-Type", "application/json")
request.Header.Add("User-Agent", c.UserAgent)
err := c.authorizeRequest(request)
if err != nil {
return err
}
res, err := c.netClient.Do(request)
if err != nil {
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
if len(body) > 0 {
return fmt.Errorf("%s %s", res.Status, string(body))
}
return errors.New(res.Status)
}
if len(body) > 0 {
err = json.Unmarshal(body, &response)
if err != nil {
return err
}
}
return nil
}
func (c *Client) authorizeRequest(request *http.Request) error {
token, err := c.tokenProvider.GetToken()
if err != nil {
return err
}
token.SetAuthHeader(request)
return nil
}