/
utils_api_v2.go
118 lines (91 loc) · 2.54 KB
/
utils_api_v2.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
package iyzipay
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/google/uuid"
)
func connectV2(method, uri, apiKey, secretKey string, req interface{}) (string, error) {
authHeader, err := prepareAuthorizationStringV2(uri, apiKey, secretKey, uuid.New().String(), req)
if err != nil {
return "", err
}
request, err := http.NewRequest(method, uri, nil)
if err != nil {
return "", err
}
if req != nil {
marshaled, err := json.Marshal(req)
if err != nil {
return "", err
}
request, err = http.NewRequest(method, uri, bytes.NewBuffer(marshaled))
if err != nil {
return "", err
}
}
request.Header.Set("Accept", "application/json")
request.Header.Set("Content-type", "application/json")
request.Header.Set("Authorization", authHeader)
client := http.Client{}
rawResponse, err := client.Do(request)
if err != nil {
return "", err
}
defer rawResponse.Body.Close()
bodyByte, err := io.ReadAll(rawResponse.Body)
if err != nil {
return "", err
}
return string(bodyByte), nil
}
func prepareAuthorizationStringV2(uri, apiKey, secretKey, randomString string, request interface{}) (string, error) {
authContent, err := generateAuthContent(uri, apiKey, secretKey, randomString, request)
if err != nil {
return "", err
}
return "IYZWSv2 " + authContent, nil
}
func generateAuthContent(uri, apiKey, secretKey, randomString string, request interface{}) (string, error) {
hmac256, err := getHmacSHA256Signature(uri, secretKey, randomString, request)
if err != nil {
return "", err
}
input := "apiKey:" + apiKey + "&randomKey:" + randomString + "&signature:" + hmac256
return base64.StdEncoding.EncodeToString([]byte(input)), nil
}
func getHmacSHA256Signature(uri, secretKey, randomString string, request interface{}) (string, error) {
payload, err := getPayload(uri, request)
if err != nil {
return "", err
}
dataToSign := randomString + payload
key := []byte(secretKey)
sig := hmac.New(sha256.New, key)
sig.Write([]byte(dataToSign))
return strings.ToLower(hex.EncodeToString(sig.Sum(nil))), nil
}
func getPayload(uri string, request interface{}) (string, error) {
startIndex := strings.Index(uri, "/v2")
endIndex := strings.Index(uri, "?")
uriPath := ""
if endIndex == -1 {
uriPath = uri[startIndex:]
} else {
uriPath = uri[startIndex:endIndex]
}
if request != nil {
marshaled, err := json.Marshal(request)
if err != nil {
return "", err
}
return uriPath + string(marshaled), nil
}
return uriPath, nil
}