-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
616 lines (491 loc) · 14.3 KB
/
client.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package dwolla
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"strings"
"time"
)
// Environment is a supported dwolla environment
type Environment string
const (
// Version is the version of the client
Version string = "0.1.0"
// Production is the production environment
Production Environment = "production"
// Sandbox is the sanbox environment
Sandbox Environment = "sandbox"
// ProductionAPIURL is the production api url
ProductionAPIURL = "https://api.dwolla.com"
// ProductionAuthURL is the production auth url
ProductionAuthURL = "https://www.dwolla.com/oauth/v2/authenticate"
// ProductionTokenURL is the production token url
// Deprecated - use https://api.dwolla.com/token moving forward
ProductionTokenURL = "https://accounts.dwolla.com/token"
// SandboxAPIURL is the sandbox api url
SandboxAPIURL = "https://api-sandbox.dwolla.com"
// SandboxAuthURL is the sandbox auth url
SandboxAuthURL = "https://sandbox.dwolla.com/oauth/v2/authenticate"
// SandboxTokenURL is the sandbox token url
// Deprecated - use https://api-sandbox.dwolla.com moving forward
SandboxTokenURL = "https://accounts-sandbox.dwolla.com/token"
)
// Token is a dwolla auth token
type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
startTime time.Time
}
// Expired returns true if token has expired
func (t *Token) Expired() bool {
return time.Since(t.startTime) > time.Duration(t.ExpiresIn)*time.Second
}
// HTTPClient is the http client interface
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Client is the dwolla client
type Client struct {
Key string
Secret string
Environment Environment
HTTPClient HTTPClient
Token *Token
root *Resource
Account AccountService
BeneficialOwner BeneficialOwnerService
BusinessClassification BusinessClassificationService
Customer CustomerService
Document DocumentService
Event EventService
FundingSource FundingSourceService
KBA KBAService
MassPayment MassPaymentService
OnDemandAuthorization OnDemandAuthorizationService
Transfer TransferService
TransferFailure *TransferFailureServiceOp
Webhook WebhookService
WebhookSubscription WebhookSubscriptionService
}
// ClientTokenRequest is a client token request
type ClientTokenRequest struct {
Resource
Action string `json:"action"`
}
// ClientToken is a general use client token
type ClientToken struct {
Token string `json:"token"`
}
// New initializes a new dwolla client
func New(key, secret string, environment Environment) *Client {
return NewWithHTTPClient(key, secret, environment, nil)
}
// NewWithHTTPClient initializes the client with specified http client
func NewWithHTTPClient(key, secret string, environment Environment, httpClient HTTPClient) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
c := &Client{
Key: key,
Secret: secret,
Environment: environment,
HTTPClient: httpClient,
}
c.Account = &AccountServiceOp{c}
c.BeneficialOwner = &BeneficialOwnerServiceOp{c}
c.BusinessClassification = &BusinessClassificationServiceOp{c}
c.Customer = &CustomerServiceOp{c}
c.Document = &DocumentServiceOp{c}
c.Event = &EventServiceOp{c}
c.FundingSource = &FundingSourceServiceOp{c}
c.KBA = &KBAServiceOp{c}
c.MassPayment = &MassPaymentServiceOp{c}
c.OnDemandAuthorization = &OnDemandAuthorizationServiceOp{c}
c.Transfer = &TransferServiceOp{c}
c.TransferFailure = &TransferFailureServiceOp{client: c}
c.Webhook = &WebhookServiceOp{c}
c.WebhookSubscription = &WebhookSubscriptionServiceOp{c}
return c
}
// APIURL returns the api url for the environment
func (c Client) APIURL() string {
var url string
switch c.Environment {
case Production:
url = ProductionAPIURL
case Sandbox:
url = SandboxAPIURL
}
return url
}
// BuildAPIURL builds an api url with a given path
func (c Client) BuildAPIURL(path string) string {
apiURL := c.APIURL()
if strings.HasPrefix(path, apiURL) {
return path
}
if !strings.HasPrefix(path, "/") {
path = fmt.Sprintf("/%s", path)
}
return fmt.Sprintf("%s%s", apiURL, path)
}
// AuthURL returns the auth url for the environment
func (c Client) AuthURL() string {
var url string
switch c.Environment {
case Production:
url = ProductionAuthURL
case Sandbox:
url = SandboxAuthURL
}
return url
}
// TokenURL returns the token url for the environment
func (c Client) TokenURL() string {
var url string
switch c.Environment {
case Production:
url = ProductionTokenURL
case Sandbox:
url = SandboxTokenURL
}
return url
}
// RequestToken requests a new auth token using client credentials
func (c *Client) RequestToken(ctx context.Context) error {
var (
err error
token Token
)
buf := bytes.NewBuffer([]byte("grant_type=client_credentials"))
req, err := http.NewRequestWithContext(ctx, "POST", c.BuildAPIURL("token"), buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", fmt.Sprintf("dwolla-v2-go/%s", Version))
req.SetBasicAuth(c.Key, c.Secret)
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = json.Unmarshal(resBody, &token)
if err != nil {
return err
}
if token.Error != "" {
return fmt.Errorf("[%s] %s", token.Error, token.ErrorDescription)
}
c.Token = &token
c.Token.startTime = time.Now()
return nil
}
// EnsureToken ensures that a token exists for a request
func (c *Client) EnsureToken(ctx context.Context) error {
if c.Token == nil {
if err := c.RequestToken(ctx); err != nil {
return err
}
}
if c.Token.Expired() {
if err := c.RequestToken(ctx); err != nil {
return err
}
}
return nil
}
// Get performs a GET against the api
func (c *Client) Get(ctx context.Context, path string, params *url.Values, headers *http.Header, container interface{}) error {
var (
err error
halError HALError
)
if err = c.EnsureToken(ctx); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "GET", c.BuildAPIURL(path), nil)
if err != nil {
return err
}
if headers != nil {
req.Header = *headers
}
req.Header.Set("Accept", "application/vnd.dwolla.v1.hal+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
req.Header.Set("User-Agent", fmt.Sprintf("dwolla-v2-go/%s", Version))
if params != nil {
req.URL.RawQuery = params.Encode()
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode > 299 {
if err := json.Unmarshal(resBody, &halError); err != nil {
return err
}
// If token is expired, we'll attempt to get a newone and reattempt
// the request. This should probably be moved to a method to handle
// all error scenarios.
if halError.Code == "ExpiredAccessToken" {
if err := c.RequestToken(ctx); err != nil {
return err
}
return c.Get(ctx, path, params, headers, container)
}
return halError
}
if container != nil {
return json.Unmarshal(resBody, container)
}
return nil
}
// Post performs a POST against the api
func (c *Client) Post(ctx context.Context, path string, body interface{}, headers *http.Header, container interface{}) error {
var (
err error
halError HALError
validationError ValidationError
bodyReader io.Reader
)
if err = c.EnsureToken(ctx); err != nil {
return err
}
if body != nil {
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
bodyReader = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.BuildAPIURL(path), bodyReader)
if err != nil {
return err
}
if headers != nil {
req.Header = *headers
}
req.Header.Set("Accept", "application/vnd.dwolla.v1.hal+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
req.Header.Set("Content-Type", "application/vnd.dwolla.v1.hal+json")
req.Header.Set("User-Agent", "dwolla-v2-go")
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// When creating a resource, Dwolla will return a 201 and a "Location"
// header. This just cuts to the chase and retrieves the resource.
if res.Header.Get("Location") != "" {
return c.Get(ctx, res.Header.Get("Location"), nil, nil, container)
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode > 299 {
if err := json.Unmarshal(resBody, &halError); err != nil {
return err
}
// If token is expired, we'll attempt to get a newone and reattempt
// the request. This should probably be moved to a method to handle
// all error scenarios.
if halError.Code == "ExpiredAccessToken" {
if err := c.RequestToken(ctx); err != nil {
return err
}
return c.Post(ctx, path, body, headers, container)
}
if halError.Code == "ValidationError" {
if err := json.Unmarshal(resBody, &validationError); err != nil {
return err
}
return validationError
}
return halError
}
if container != nil {
return json.Unmarshal(resBody, container)
}
return nil
}
// Upload performs a multipart file upload to the Dwolla API
func (c *Client) Upload(ctx context.Context, path string, documentType DocumentType, fileName string, file io.Reader, container interface{}) error {
var (
err error
halError HALError
validationError ValidationError
)
if err = c.EnsureToken(ctx); err != nil {
return err
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", fileName)
if err != nil {
return err
}
_, err = io.Copy(part, file)
if err != nil {
return err
}
err = writer.WriteField("documentType", string(documentType))
if err != nil {
return err
}
err = writer.Close()
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "POST", c.BuildAPIURL(path), body)
if err != nil {
return err
}
req.Header.Set("Accept", "application/vnd.dwolla.v1.hal+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("User-Agent", "dwolla-v2-go")
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// When creating a resource, Dwolla will return a 201 and a "Location"
// header. This just cuts to the chase and retrieves the resource.
if res.Header.Get("Location") != "" {
return c.Get(ctx, res.Header.Get("Location"), nil, nil, container)
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode > 299 {
if err := json.Unmarshal(resBody, &halError); err != nil {
return err
}
// If token is expired, we'll attempt to get a newone and reattempt
// the request. This should probably be moved to a method to handle
// all error scenarios.
if halError.Code == "ExpiredAccessToken" {
if err := c.RequestToken(ctx); err != nil {
return err
}
return c.Upload(ctx, path, documentType, fileName, file, container)
}
if halError.Code == "ValidationError" {
if err := json.Unmarshal(resBody, &validationError); err != nil {
return err
}
return validationError
}
return halError
}
if container != nil {
return json.Unmarshal(resBody, container)
}
return nil
}
// Delete performs a DELETE against the api
func (c *Client) Delete(ctx context.Context, path string, params *url.Values, headers *http.Header) error {
var (
err error
halError HALError
)
if err = c.EnsureToken(ctx); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "DELETE", c.BuildAPIURL(path), nil)
if err != nil {
return err
}
if headers != nil {
req.Header = *headers
}
req.Header.Set("Accept", "application/vnd.dwolla.v1.hal+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
req.Header.Set("User-Agent", fmt.Sprintf("dwolla-v2-go/%s", Version))
if params != nil {
req.URL.RawQuery = params.Encode()
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode > 299 {
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if err := json.Unmarshal(resBody, &halError); err != nil {
return err
}
// If token is expired, we'll attempt to get a newone and reattempt
// the request. This should probably be moved to a method to handle
// all error scenarios.
if halError.Code == "ExpiredAccessToken" {
if err := c.RequestToken(ctx); err != nil {
return err
}
return c.Delete(ctx, path, params, headers)
}
return halError
}
return nil
}
// Root returns the dwolla root response
func (c *Client) Root(ctx context.Context) (*Resource, error) {
if c.root != nil {
return c.root, nil
}
var resource Resource
if err := c.Get(ctx, "", nil, nil, &resource); err != nil {
return nil, err
}
c.root = &resource
return &resource, nil
}
// SandboxSimulations simulates events within the sandbox environment
//
// see: https://developers.dwolla.com/resources/testing.html#simulate-bank-transfer-processing
func (c *Client) SandboxSimulations(ctx context.Context) error {
return c.Post(ctx, "sandbox-simulations", nil, nil, nil)
}
// CreateClientToken creates a general use client token
//
// see: https://docsv2.dwolla.com/#create-a-client-token
func (c *Client) CreateClientToken(ctx context.Context, action string, customer *Customer) (*ClientToken, error) {
body := ClientTokenRequest{Action: action}
if customer != nil {
if _, ok := customer.Links["self"]; !ok {
return nil, errors.New("No self resource link")
}
body.Resource = *NewResource(Links{"customer": Link{Href: customer.Links["self"].Href}}, nil)
}
var token ClientToken
if err := c.Post(ctx, "client-tokens", body, nil, &token); err != nil {
return nil, err
}
return &token, nil
}