forked from braintree-go/braintree-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbraintree.go
More file actions
375 lines (307 loc) · 9.51 KB
/
braintree.go
File metadata and controls
375 lines (307 loc) · 9.51 KB
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
package braintree
import (
"bytes"
"context"
"crypto/tls"
"encoding/xml"
"errors"
"fmt"
"log"
"net"
"net/http"
"time"
)
type apiVersion int
const (
apiVersion3 apiVersion = 3
apiVersion4 apiVersion = 4
apiVersion6 apiVersion = 6
)
const defaultTimeout = time.Second * 60
var (
// defaultTransport uses the same configuration as http.DefaultTransport
// with the addition of the minimum requirement for TLS 1.2
defaultTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
}
defaultClient = &http.Client{
Timeout: defaultTimeout,
Transport: defaultTransport,
}
)
// New creates a Braintree client with API Keys.
func New(env, graphqlEnv Environment, merchId, pubKey, privKey string) *Braintree {
return NewWithHttpClient(env, graphqlEnv, merchId, pubKey, privKey, defaultClient)
}
// NewWithHttpClient creates a Braintree client with API Keys and a HTTP Client.
func NewWithHttpClient(env, graphqlEnv Environment, merchantId, publicKey, privateKey string, client *http.Client) *Braintree {
return &Braintree{credentials: newAPIKey(env, graphqlEnv, merchantId, publicKey, privateKey), HttpClient: client}
}
// NewWithCredentials creates a Braintree client with API Keys and client credentials.
// some endpoints require client credentials to be passed in the header.
func NewWithCredentials(env, graphqlEnv Environment, merchId, pubKey, privKey, clientId, clientSecrets string) *Braintree {
return NewHttpClientWithCredentials(env, graphqlEnv, merchId, pubKey, privKey, clientId, clientSecrets, defaultClient)
}
// NewWithHttpClient creates a Braintree client with API Keys and a HTTP Client.
func NewHttpClientWithCredentials(env, graphqlEnv Environment, merchantId, publicKey, privateKey, clientId, clientSecret string, client *http.Client) *Braintree {
return &Braintree{credentials: newAPIKeyWithCredentials(env, graphqlEnv, merchantId, publicKey, privateKey, clientId, clientSecret), HttpClient: client}
}
// NewWithAccessToken creates a Braintree client with an Access Token.
// Note: When using an access token, webhooks are unsupported and the
// WebhookNotification() function will panic.
func NewWithAccessToken(accessToken string) (*Braintree, error) {
c, err := newAccessToken(accessToken)
if err != nil {
return nil, err
}
return &Braintree{credentials: c, HttpClient: defaultClient}, nil
}
// Braintree interacts with the Braintree API.
type Braintree struct {
credentials credentials
Logger *log.Logger
HttpClient *http.Client
}
// Environment returns the current environment.
func (g *Braintree) Environment() Environment {
return g.credentials.Environment()
}
// GraphQLEnvironment returns the current environment.
func (g *Braintree) GraphQLEnvironment() Environment {
return g.credentials.GraphQLEnvironment()
}
// MerchantID returns the current merchant id.
func (g *Braintree) MerchantID() string {
return g.credentials.MerchantID()
}
// MerchantURL returns the configured merchant's base URL for outgoing requests.
func (g *Braintree) MerchantURL() string {
return g.Environment().BaseURL() + "/merchants/" + g.MerchantID()
}
func (g *Braintree) execute(ctx context.Context, method, path string, xmlObj interface{}) (*Response, error) {
return g.executeVersion(ctx, method, path, xmlObj, apiVersion3)
}
func (g *Braintree) graphqlExecute(ctx context.Context, buf *bytes.Buffer) (*Response, error) {
httpClient := g.HttpClient
if httpClient == nil {
httpClient = defaultClient
}
url := g.GraphQLEnvironment().BaseURL() + "/graphql"
if g.Logger != nil && buf != nil {
g.Logger.Printf("> %s %s\n%s", http.MethodPost, url, buf.String())
}
req, err := http.NewRequest(http.MethodPost, url, buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
// date of first using the recommendation from the official doc
req.Header.Set("Braintree-Version", "2025-02-26")
req.Header.Set("User-Agent", fmt.Sprintf("Braintree Go %s", LibraryVersion))
req.Header.Set("Authorization", g.credentials.AuthorizationHeader())
req = req.WithContext(ctx)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
btr := &Response{
Response: resp,
}
err = btr.unpackBody()
if err != nil {
return nil, err
}
if g.Logger != nil {
g.Logger.Printf("<\n%s", string(btr.Body))
}
err = btr.apiError()
if err != nil {
return nil, err
}
return btr, nil
}
func (g *Braintree) executeVersion(ctx context.Context, method, path string, xmlObj interface{}, v apiVersion) (*Response, error) {
var buf bytes.Buffer
if xmlObj != nil {
xmlBody, err := xml.Marshal(xmlObj)
if err != nil {
return nil, err
}
_, err = buf.Write(xmlBody)
if err != nil {
return nil, err
}
}
url := g.MerchantURL() + "/" + path
if g.Logger != nil {
g.Logger.Printf("> %s %s\n%s", method, url, buf.String())
}
req, err := http.NewRequest(method, url, &buf)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/xml")
req.Header.Set("Accept", "application/xml")
req.Header.Set("Accept-Encoding", "gzip")
req.Header.Set("User-Agent", fmt.Sprintf("Braintree Go %s", LibraryVersion))
req.Header.Set("X-ApiVersion", fmt.Sprintf("%d", v))
req.Header.Set("Authorization", g.credentials.AuthorizationHeader())
httpClient := g.HttpClient
if httpClient == nil {
httpClient = defaultClient
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
btr := &Response{
Response: resp,
}
err = btr.unpackBody()
if err != nil {
return nil, err
}
if g.Logger != nil {
g.Logger.Printf("<\n%s", string(btr.Body))
}
err = btr.apiError()
if err != nil {
return nil, err
}
return btr, nil
}
func (g *Braintree) executeBaseVersion(ctx context.Context, method, path string, xmlObj interface{}, v apiVersion) (*Response, error) {
var buf bytes.Buffer
if xmlObj != nil {
xmlBody, err := xml.Marshal(xmlObj)
if err != nil {
return nil, err
}
_, err = buf.Write(xmlBody)
if err != nil {
return nil, err
}
}
url := g.Environment().BaseURL() + "/" + path
if g.Logger != nil {
g.Logger.Printf("> %s %s\n%s", method, url, buf.String())
}
req, err := http.NewRequest(method, url, &buf)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/xml")
req.Header.Set("Accept", "application/xml")
req.Header.Set("Accept-Encoding", "gzip")
req.Header.Set("User-Agent", fmt.Sprintf("Braintree Go %s", LibraryVersion))
req.Header.Set("X-ApiVersion", fmt.Sprintf("%d", v))
req.Header.Set("Authorization", g.credentials.AuthorizationHeaderWithClientCreds())
httpClient := g.HttpClient
if httpClient == nil {
httpClient = defaultClient
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
btr := &Response{
Response: resp,
}
err = btr.unpackBody()
if err != nil {
return nil, err
}
if g.Logger != nil {
g.Logger.Printf("<\n%s", string(btr.Body))
}
err = btr.apiError()
if err != nil {
return nil, err
}
return btr, nil
}
func (g *Braintree) ClientToken() *ClientTokenGateway {
return &ClientTokenGateway{g}
}
func (g *Braintree) MerchantAccount() *MerchantAccountGateway {
return &MerchantAccountGateway{g}
}
func (g *Braintree) Transaction() *TransactionGateway {
return &TransactionGateway{g}
}
func (g *Braintree) TransactionLineItem() *TransactionLineItemGateway {
return &TransactionLineItemGateway{g}
}
func (g *Braintree) Testing() *TestingGateway {
return &TestingGateway{g}
}
func (g *Braintree) WebhookTesting() *WebhookTestingGateway {
if apiKey, ok := g.credentials.(apiKey); !ok {
panic(errors.New("WebhookTesting can only be used with Braintree Credentials that are API Keys."))
} else {
return &WebhookTestingGateway{Braintree: g, apiKey: apiKey}
}
}
func (g *Braintree) PaymentMethod() *PaymentMethodGateway {
return &PaymentMethodGateway{g}
}
func (g *Braintree) Oauth() *OAuthGateway {
return &OAuthGateway{g}
}
func (g *Braintree) PaymentMethodNonce() *PaymentMethodNonceGateway {
return &PaymentMethodNonceGateway{g}
}
func (g *Braintree) CreditCard() *CreditCardGateway {
return &CreditCardGateway{g}
}
func (g *Braintree) PayPalAccount() *PayPalAccountGateway {
return &PayPalAccountGateway{g}
}
func (g *Braintree) Customer() *CustomerGateway {
return &CustomerGateway{g}
}
func (g *Braintree) Subscription() *SubscriptionGateway {
return &SubscriptionGateway{g}
}
func (g *Braintree) Plan() *PlanGateway {
return &PlanGateway{g}
}
func (g *Braintree) Address() *AddressGateway {
return &AddressGateway{g}
}
func (g *Braintree) AddOn() *AddOnGateway {
return &AddOnGateway{g}
}
func (g *Braintree) Discount() *DiscountGateway {
return &DiscountGateway{g}
}
func (g *Braintree) Dispute() *DisputeGateway {
return &DisputeGateway{g}
}
func (g *Braintree) WebhookNotification() *WebhookNotificationGateway {
if apiKey, ok := g.credentials.(apiKey); !ok {
panic(errors.New("WebhookNotifications can only be used with Braintree Credentials that are API Keys."))
} else {
return &WebhookNotificationGateway{Braintree: g, apiKey: apiKey}
}
}
func (g *Braintree) Settlement() *SettlementGateway {
return &SettlementGateway{g}
}