-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
165 lines (139 loc) · 3.99 KB
/
client.go
File metadata and controls
165 lines (139 loc) · 3.99 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
package cdek_pay
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/google/go-querystring/query"
"io"
"net/http"
"sort"
"strings"
)
type Config struct {
httpClient *http.Client
login string
secretKey string
baseURL string
}
func WithLogin(login string) func(*Config) {
return func(config *Config) {
config.login = login
}
}
func WithSecretKey(secretKey string) func(*Config) {
return func(config *Config) {
config.secretKey = secretKey
}
}
func WithBaseURL(baseURL string) func(*Config) {
return func(config *Config) {
config.baseURL = baseURL
}
}
func WithHTTPClient(c *http.Client) func(*Config) {
return func(config *Config) {
config.httpClient = c
}
}
// Client is the main entity which executes requests against the Tinkoff Acquiring API endpoint
type Client struct {
Config
}
// NewClient returns new Client instance
func NewClient(login string, secretKey string) *Client {
return NewClientWithOptions(
WithLogin(login),
WithSecretKey(secretKey),
)
}
func NewClientWithOptions(cfgOption ...func(*Config)) *Client {
defaultConfig := Config{
httpClient: http.DefaultClient,
baseURL: "https://secure.cdekfin.ru/merchant_api/",
}
cfg := defaultConfig
for _, opt := range cfgOption {
opt(&cfg)
}
return &Client{
Config: cfg,
}
}
// SetBaseURL allows to change default API endpoint
func (c *Client) SetBaseURL(baseURL string) {
c.baseURL = baseURL
}
func (c *Client) decodeResponse(response *http.Response, result interface{}) error {
if response.StatusCode != 200 {
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
return err
}
bodyString := string(bodyBytes)
return errors.New(fmt.Sprintf("%v - '%s'", response.StatusCode, bodyString))
}
return json.NewDecoder(response.Body).Decode(result)
}
// Deprecated: use PostRequestWithContext instead
func (c *Client) PostRequest(url string, request RequestInterface) (*http.Response, error) {
return c.PostRequestWithContext(context.Background(), url, request)
}
func (c *Client) secureRequest(request RequestInterface) {
request.SetLogin(c.login)
v := request.GetValuesForSignature()
request.SetSignature(generateSignature(v, c.secretKey))
}
// PostRequestWithContext will automatically sign the request with token
// Use BaseRequest type to implement any API request
func (c *Client) PostRequestWithContext(ctx context.Context, url string, request RequestInterface) (*http.Response, error) {
c.secureRequest(request)
data, err := json.Marshal(request)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+url, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return c.httpClient.Do(req)
}
// GetRequestWithContext will automatically sign the request with token
// Use BaseRequest type to implement any API request
func (c *Client) GetRequestWithContext(ctx context.Context, url string, request RequestInterface) (*http.Response, error) {
c.secureRequest(request)
// Add query parameters from request to URL
queryParams, err := query.Values(request)
if err != nil {
return nil, err
}
reqURL := c.baseURL + url + "?" + queryParams.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return c.httpClient.Do(req)
}
// Функция для генерации подписи
func generateSignature(data map[string]interface{}, secretKey string) string {
// Сортировка ключей
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
// Конкатенация значений в строку
signatureStr := ""
for _, k := range keys {
signatureStr += fmt.Sprintf("%v|", data[k])
}
signatureStr += secretKey
// Генерация SHA-256
hash := sha256.Sum256([]byte(signatureStr))
return strings.ToUpper(hex.EncodeToString(hash[:]))
}