-
Notifications
You must be signed in to change notification settings - Fork 3
/
craftgate.go
375 lines (319 loc) · 9.28 KB
/
craftgate.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
package adapter
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/schema"
"io"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
var schemaEncoder = schema.NewEncoder()
const (
timeEncodeLayout = "2006-01-02T15:04:05"
timeDecodeLayout = "\"2006-01-02T15:04:05\""
)
type TimeResponse struct {
time.Time
}
type Date struct {
Year int // Year (e.g., 2014).
Month time.Month // Month of the year (January = 1, ...).
Day int // Day of the month, starting at 1.
}
func DateOf(t time.Time) Date {
var d Date
d.Year, d.Month, d.Day = t.Date()
return d
}
func init() {
timeConverter := func(value reflect.Value) string {
return value.Interface().(time.Time).Format(timeEncodeLayout)
}
dateConverter := func(value reflect.Value) string {
date := value.Interface().(Date)
month := strconv.Itoa(int(date.Month))
if date.Month < 10 {
month = "0" + month
}
day := strconv.Itoa(date.Day)
if date.Day < 10 {
day = "0" + day
}
d := fmt.Sprintf("%d-%s-%s", date.Year, month, day)
return d
}
schemaEncoder.RegisterEncoder(time.Time{}, timeConverter)
schemaEncoder.RegisterEncoder(Date{}, dateConverter)
}
type ClientOption func(*Client) error
func WithLocalization(lang string) ClientOption {
return func(client *Client) error {
if len(lang) > 0 {
client.headers["lang"] = strings.ToLower(lang)
} else {
client.headers["lang"] = "tr"
}
return nil
}
}
func WithCustomHTTPClient(httpClient *http.Client) ClientOption {
return func(client *Client) error {
if httpClient != nil {
client.httpClient = httpClient
} else {
client.httpClient = http.DefaultClient
}
return nil
}
}
type Client struct {
httpClient *http.Client
baseURL *url.URL
apiKey string
secretKey string
headers map[string]string
Installment *Installment
Payment *Payment
PaymentReporting *PaymentReporting
Wallet *Wallet
Onboarding *Onboarding
PayByLink *PayByLink
Settlement *Settlement
SettlementReporting *SettlementReporting
FileReporting *FileReporting
Fraud *Fraud
Hook *Hook
Masterpass *Masterpass
BankAccountTracking *BankAccountTracking
Merchant *Merchant
Juzdan *Juzdan
}
func New(apiKey, apiSecret, baseURL string, opts ...ClientOption) (*Client, error) {
client := newClient(apiKey, apiSecret)
client.headers = make(map[string]string)
for _, option := range opts {
if err := option(client); err != nil {
return nil, err
}
}
if client.httpClient == nil {
client.httpClient = http.DefaultClient
client.httpClient.Timeout = time.Minute * 120
}
if client.baseURL == nil {
client.baseURL, _ = url.Parse(baseURL)
}
return client, nil
}
func newClient(apiKey, secretKey string) *Client {
client := &Client{apiKey: apiKey, secretKey: secretKey}
client.Installment = &Installment{Client: client}
client.Payment = &Payment{Client: client}
client.PaymentReporting = &PaymentReporting{Client: client}
client.Onboarding = &Onboarding{Client: client}
client.PayByLink = &PayByLink{Client: client}
client.Wallet = &Wallet{Client: client}
client.Settlement = &Settlement{Client: client}
client.SettlementReporting = &SettlementReporting{Client: client}
client.FileReporting = &FileReporting{Client: client}
client.Fraud = &Fraud{Client: client}
client.Hook = &Hook{Client: client}
client.Masterpass = &Masterpass{Client: client}
client.BankAccountTracking = &BankAccountTracking{Client: client}
client.Merchant = &Merchant{Client: client}
return client
}
func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var req *http.Request
switch method {
case http.MethodGet, http.MethodDelete, http.MethodHead, http.MethodOptions:
req, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
if err != nil {
return nil, err
}
if body != nil {
req.URL.RawQuery, _ = QueryParams(body)
}
default:
buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err = http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
}
for k, v := range c.headers {
req.Header.Add(k, v)
}
authorizationRequestBody := c.extractRequestBodyForAuthorization(body, method, req)
randomStr := GenerateRandomString()
hashStr := GenerateHash(req.URL.String(), c.apiKey, c.secretKey, randomStr, authorizationRequestBody)
req.Header.Set(ApiKeyHeaderName, c.apiKey)
req.Header.Set(RandomHeaderName, randomStr)
req.Header.Set(AuthVersionHeaderName, AuthVersion)
req.Header.Set(ClientVersionHeaderName, ClientVersion)
req.Header.Set(SignatureHeaderName, hashStr)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
return req, nil
}
func (c *Client) NewRequestForByteResponse(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var req *http.Request
switch method {
case http.MethodGet, http.MethodDelete, http.MethodHead, http.MethodOptions:
req, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
if err != nil {
return nil, err
}
if body != nil {
req.URL.RawQuery, _ = QueryParams(body)
}
default:
buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err = http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
}
for k, v := range c.headers {
req.Header.Add(k, v)
}
authorizationRequestBody := c.extractRequestBodyForAuthorization(body, method, req)
randomStr := GenerateRandomString()
hashStr := GenerateHash(req.URL.String(), c.apiKey, c.secretKey, randomStr, authorizationRequestBody)
req.Header.Set(ApiKeyHeaderName, c.apiKey)
req.Header.Set(RandomHeaderName, randomStr)
req.Header.Set(AuthVersionHeaderName, AuthVersion)
req.Header.Set(ClientVersionHeaderName, ClientVersion)
req.Header.Set(SignatureHeaderName, hashStr)
req.Header.Set("Content-Type", "application/octet-stream; charset=utf-8")
req.Header.Set("Accept", "application/octet-stream; charset=utf-8")
return req, nil
}
func (c *Client) extractRequestBodyForAuthorization(body interface{}, method string, req *http.Request) string {
authorizationRequestBody := ""
if body != nil && method != http.MethodGet && method != http.MethodDelete {
var buf bytes.Buffer
tee := io.TeeReader(req.Body, &buf)
req.Body = io.NopCloser(&buf)
bodyBytes, bodyErr := io.ReadAll(tee)
if bodyErr == nil {
authorizationRequestBody = string(bodyBytes)
}
}
return authorizationRequestBody
}
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) error {
resp, err := DoRequestWithClient(ctx, c.httpClient, req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
}(resp.Body)
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
errRes := &Response[ErrorResponse]{}
if err = json.NewDecoder(resp.Body).Decode(errRes); nil == errRes {
return errors.New(*errRes.Errors.ErrorDescription)
}
return errRes
}
switch v.(type) {
case *Void:
default:
if err = json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
}
return nil
}
func (c *Client) DoForByteResponse(ctx context.Context, req *http.Request) ([]byte, error) {
resp, err := DoRequestWithClient(ctx, c.httpClient, req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
}(resp.Body)
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
errRes := &Response[ErrorResponse]{}
if err = json.NewDecoder(resp.Body).Decode(errRes); nil == errRes {
return nil, errors.New(*errRes.Errors.ErrorDescription)
}
return nil, errRes
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v %v", r.ErrorGroup, r.ErrorCode, r.ErrorDescription)
}
func DoRequestWithClient(
ctx context.Context,
client *http.Client,
req *http.Request) (*http.Response, error) {
req = req.WithContext(ctx)
return client.Do(req)
}
func GenerateHash(url, apiKey, secretKey, randomString, body string) string {
hashStr := strings.Join([]string{url, apiKey, secretKey, randomString, body}, "")
hash := sha256.New()
hash.Write([]byte(hashStr))
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}
func GenerateRandomString() string {
s := strconv.FormatInt(time.Now().UnixNano(), 16)
return s[8:]
}
func (v *TimeResponse) UnmarshalJSON(b []byte) error {
parse, err := time.Parse(timeDecodeLayout, string(b))
if err != nil {
return err
}
v.Time = parse
return nil
}
func QueryParams(req interface{}) (string, error) {
queryParams := url.Values{}
err := schemaEncoder.Encode(req, queryParams)
if err != nil {
return "", err
}
encoded := queryParams.Encode()
encoded = strings.Replace(encoded, "%3A", ":", -1)
return encoded, nil
}
func (c *Client) Info() string {
return "Craftgate Go Client. Api Key: " + c.apiKey
}