forked from checkout/checkout-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckout.go
374 lines (319 loc) · 8.89 KB
/
checkout.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
package checkout
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os/exec"
"regexp"
"runtime"
"time"
"github.com/checkout/checkout-sdk-go/common"
)
// ClientVersion ...
const ClientVersion = "0.0.1"
const (
sandboxURI = "https://api.sandbox.checkout.com"
productionURI = "https://api.checkout.com"
)
const (
// UPAPI - Unified Payment API
UPAPI SupportedAPI = "api"
// Access - OAuth Authorization
Access SupportedAPI = "access"
)
var mbcLiveSecretKeyPattern = regexp.MustCompile(common.LiveSecretKeyRegex)
var fourKeyPattern = regexp.MustCompile(common.FourKeyRegex)
var fourOAuthJwtPattern = regexp.MustCompile(common.FourOAuthJwtPattern)
const (
// Sandbox - Sandbox
Sandbox SupportedEnvironment = "sandbox.checkout.com"
// Production - Production
Production SupportedEnvironment = "checkout.com"
// UnknownPlatform - Production
UnknownPlatform string = "unknown platform"
)
const (
// DefaultMaxNetworkRetries is the default maximum number of retries made
// by a Checkout.com client.
DefaultMaxNetworkRetries int64 = 2
)
const (
// CKORequestID ...
CKORequestID = "cko-request-id"
// CKOVersion ...
CKOVersion = "cko-version"
)
// SupportedAPI is an enumeration of supported Checkout.com endpoints.
// Currently supported values are "Unified Payment Gateway".
type SupportedAPI string
// SupportedEnvironment is an enumeration of supported Checkout.com environment.
// Currently supported values are "Sandbox" & "Production".
type SupportedEnvironment string
// Config ...
type Config struct {
PublicKey string
SecretKey string
URI *string
HTTPClient *http.Client
LeveledLogger LeveledLoggerInterface
MaxNetworkRetries *int64
BearerAuthentication bool
}
const (
defaultHTTPTimeout = 30 * time.Second
)
var httpClient = &http.Client{
Timeout: defaultHTTPTimeout,
Transport: &http.Transport{
TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper),
},
}
// Deprecated: Please use SdkConfig
func Create(secretKey string, publicKey *string) (*Config, error) {
var config, isSandbox = create(secretKey)
if config.HTTPClient == nil {
config.HTTPClient = httpClient
}
if config.LeveledLogger == nil {
config.LeveledLogger = DefaultLeveledLogger
}
if config.MaxNetworkRetries == nil {
config.MaxNetworkRetries = Int64(DefaultMaxNetworkRetries)
}
if publicKey == nil {
return &config, nil
}
if !isSandbox {
publicKeyMatch := regexp.MustCompile(common.LivePublicKeyRegex)
if publicKeyMatch.MatchString(StringValue(publicKey)) {
config.PublicKey = StringValue(publicKey)
return &config, nil
}
return nil, &common.Error{
Status: "Configuration Error - Please review your secret key and public key ",
}
}
publicKeyMatch := regexp.MustCompile(common.SandboxPublicKeyRegex)
if publicKeyMatch.MatchString(StringValue(publicKey)) {
config.PublicKey = StringValue(publicKey)
return &config, nil
}
return nil, &common.Error{
Status: "Configuration Error - Please review your secret key and public key ",
}
}
func SdkConfig(secretKey *string, publicKey *string, env SupportedEnvironment) (*Config, error) {
var config Config
config.SecretKey = StringValue(secretKey)
config.PublicKey = StringValue(publicKey)
config.BearerAuthentication = shouldApplyBearer(config)
if env == Sandbox {
config.URI = String(sandboxURI)
} else if env == Production {
config.URI = String(productionURI)
}
if config.HTTPClient == nil {
config.HTTPClient = httpClient
}
if config.LeveledLogger == nil {
config.LeveledLogger = DefaultLeveledLogger
}
if config.MaxNetworkRetries == nil {
config.MaxNetworkRetries = Int64(DefaultMaxNetworkRetries)
}
return &config, nil
}
func shouldApplyBearer(config Config) bool {
// SecretKey or PublicKey matches a Four pattern
if fourKeyPattern.MatchString(config.SecretKey) || fourKeyPattern.MatchString(config.PublicKey) {
return true
}
// SecretKey or PublicKey matches a JWT
if fourOAuthJwtPattern.MatchString(config.SecretKey) || fourOAuthJwtPattern.MatchString(config.PublicKey) {
return true
}
return false
}
func create(secretKey string) (Config, bool) {
if mbcLiveSecretKeyPattern.MatchString(secretKey) {
return Config{
URI: String(productionURI),
SecretKey: secretKey,
}, false
}
return Config{
URI: String(sandboxURI),
SecretKey: secretKey,
}, true
}
var appInfo *AppInfo
var encodedCheckoutUserAgent string
var encodedUserAgent string
// AppInfo ...
type AppInfo struct {
Name string `json:"name"`
URL string `json:"url"`
Version string `json:"version"`
}
// SetAppInfo sets app information. See AppInfo.
func SetAppInfo(info *AppInfo) {
if info != nil && info.Name == "" {
panic(fmt.Errorf("App info name cannot be empty"))
}
appInfo = info
// This is run in init, but we need to reinitialize it now that we have
// some app info.
initUserAgent()
}
func (a *AppInfo) formatUserAgent() string {
str := a.Name
if a.Version != "" {
str += "/" + a.Version
}
if a.URL != "" {
str += " (" + a.URL + ")"
}
return str
}
type checkoutClientUserAgent struct {
Application *AppInfo `json:"application"`
BindingsVersion string `json:"bindings_version"`
Language string `json:"lang"`
LanguageVersion string `json:"lang_version"`
Publisher string `json:"publisher"`
Uname string `json:"uname"`
}
func initUserAgent() {
encodedUserAgent = "Checkout/v1 GoBindings/" + ClientVersion
if appInfo != nil {
encodedUserAgent += " " + appInfo.formatUserAgent()
}
checkoutUserAgent := &checkoutClientUserAgent{
Application: appInfo,
BindingsVersion: ClientVersion,
Language: "go",
LanguageVersion: runtime.Version(),
Publisher: "checkout.com",
Uname: getUname(),
}
marshaled, err := json.Marshal(checkoutUserAgent)
// Encoding this struct should never be a problem, so we're okay to panic
// in case it is for some reason.
if err != nil {
panic(err)
}
encodedCheckoutUserAgent = string(marshaled)
}
func getUname() string {
path, err := exec.LookPath("uname")
if err != nil {
return UnknownPlatform
}
cmd := exec.Command(path, "-a")
var out bytes.Buffer
cmd.Stderr = nil // goes to os.DevNull
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
return UnknownPlatform
}
return out.String()
}
// StatusResponse ...
type StatusResponse struct {
Status string `json:"status,omitempty"`
StatusCode int `json:"status_code,omitempty"`
ResponseBody []byte `json:"response_body,omitempty"`
ResponseCSV [][]string `json:"response_csv,omitempty"`
Headers *Headers `json:"headers,omitempty"`
}
// Headers ...
type Headers struct {
Header http.Header
CKORequestID *string `json:"cko-request-id,omitempty"`
CKOVersion *string `json:"cko-version,omitempty"`
}
// HTTPClient ...
type HTTPClient interface {
Get(path string) (*StatusResponse, error)
Post(path string, request interface{}, params *Params) (*StatusResponse, error)
Put(path string, request interface{}) (*StatusResponse, error)
Patch(path string, request interface{}) (*StatusResponse, error)
Delete(path string) (*StatusResponse, error)
Upload(path, boundary string, body *bytes.Buffer) (*StatusResponse, error)
Download(path string) (*StatusResponse, error)
}
// Int64 returns a pointer to the int64 value passed in.
func Int64(v int64) *int64 {
return &v
}
// Int64Value returns the value of the int64 pointer passed in or
// 0 if the pointer is nil.
func Int64Value(v *int64) int64 {
if v != nil {
return *v
}
return 0
}
// String returns a pointer to the string value passed in.
func String(v string) *string {
return &v
}
// StringValue returns the value of the string pointer passed in or
// "" if the pointer is nil.
func StringValue(v *string) string {
if v != nil {
return *v
}
return ""
}
// StringSlice returns a slice of string pointers given a slice of strings.
func StringSlice(v []string) []*string {
out := make([]*string, len(v))
for i := range v {
out[i] = &v[i]
}
return out
}
// Bool returns a pointer to the bool value passed in.
func Bool(v bool) *bool {
return &v
}
// BoolValue returns the value of the bool pointer passed in or
// false if the pointer is nil.
func BoolValue(v *bool) bool {
if v != nil {
return *v
}
return false
}
// BoolSlice returns a slice of bool pointers given a slice of bools.
func BoolSlice(v []bool) []*bool {
out := make([]*bool, len(v))
for i := range v {
out[i] = &v[i]
}
return out
}
// Float64 returns a pointer to the float64 value passed in.
func Float64(v float64) *float64 {
return &v
}
// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.
func Float64Value(v *float64) float64 {
if v != nil {
return *v
}
return 0
}
// Float64Slice returns a slice of float64 pointers given a slice of float64s.
func Float64Slice(v []float64) []*float64 {
out := make([]*float64, len(v))
for i := range v {
out[i] = &v[i]
}
return out
}