-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyandex.go
96 lines (78 loc) · 2.07 KB
/
yandex.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
package yandex
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
"github.com/shopspring/decimal"
"github.com/valyala/fasthttp"
)
type Yandex struct {
ShopId string
SecretKey string
OAuthToken string
}
type HttpRequest struct {
Path string
Method string
ShopId string
SecretKey string
IdempotenceKey string
OAuthToken string
Data url.Values
}
type ErrorResponse struct {
Type string `json:"type"`
Id string `json:"id"`
Code string `json:"code"`
Description string `json:"description"`
Parameter string `json:"parameter"`
}
type Amount struct {
Value decimal.Decimal `json:"value"`
Currency string `json:"currency"`
}
func (r *HttpRequest) SendRequest() ([]byte, error) {
const baseURL string = "https://payment.yandex.net/api/v3"
c := &fasthttp.Client{}
req := fasthttp.AcquireRequest()
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
if len(r.OAuthToken) > 0 {
req.Header.Set("Authorization", "Bearer "+r.OAuthToken)
} else {
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(r.ShopId+":"+r.SecretKey)))
}
req.Header.Set("Idempotence-Key", r.IdempotenceKey)
req.Header.SetRequestURI(baseURL + r.Path)
req.Header.SetMethod(strings.ToUpper(r.Method))
req.Header.SetUserAgent("Mozilla/4.0 (compatible; Golang Yandex API)")
req.Header.SetContentType("application/json")
if r.Method == "GET" {
req.SetRequestURI(fmt.Sprintf("%s%s?%s", baseURL, r.Path, r.Data.Encode()))
} else {
req.SetBody([]byte(r.Data.Encode()))
}
if err := c.Do(req, res); err != nil {
return nil, &Error{
Code: 500,
Message: err.Error(),
}
}
if res.StatusCode() != 200 {
e := &ErrorResponse{}
if err := json.Unmarshal(res.Body(), e); err != nil {
log.Printf("Failed unmarshaling bytes to struct: %v\n", err)
return nil, err
}
return nil, &Error{
Code: res.StatusCode(),
ApiCode: e.Code,
Message: e.Description,
}
}
return res.Body(), nil
}