-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
298 lines (268 loc) · 6.62 KB
/
client.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
package qiwiP2P
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
)
// Client
// Object used for storing client data
//
// Fields:
// - `token` : Private key of QIWI P2P
// - `client` : http.Client object, used for http requests to API
// - `ch` : Channel of payment updates, used for webhook
type Client struct {
token string
client http.Client
ch chan PaymentUpdate
}
// CreateClient
// Method creates Client object with given private key
func CreateClient(key string) *Client {
return &Client{token: key, client: http.Client{}, ch: make(chan PaymentUpdate, 50)}
}
// SetSecretKey
// Method changes private key of Client to new key
func (c *Client) SetSecretKey(key string) *Client {
c.token = key
return c
}
// PutBill
// Methods sends Bill object to API, putting it to random ID
//
// Returns BillResponse on success, error on failed
func (c *Client) PutBill(b *Bill) (result *BillResponse, err error) {
billId := pseudoUUID()
res, code, err := c.makeRequest(
billId,
"PUT",
b.toJSON(),
)
if err != nil {
return nil, err
}
if code == 400 {
return nil, RequestError{
ErrorCode: "bad_request",
Description: "Bad request. Maybe you have bad expire time?",
}
}
if code == 401 {
return nil, RequestError{
ErrorCode: "bad_token",
Description: "Bad token",
}
}
if code != 200 {
return nil, &RequestError{
ErrorCode: "Error " + strconv.Itoa(code),
Description: "HTTP Error " + strconv.Itoa(code),
}
}
return parseResponse(res)
}
// GetBill
// Method gets info about bill with given id
//
// You can get ID from BillResponse, which was returned in PutBill
//
// Returns BillResponse on success, error on failed
func (c *Client) GetBill(id string) (result *BillResponse, err error) {
res, code, err := c.makeRequest(
id,
"GET",
"",
)
if err != nil {
return nil, err
}
if code == 401 {
return nil, &RequestError{
ErrorCode: "bad_token",
Description: "Bad token",
}
}
if code == 404 {
return nil, &RequestError{
ErrorCode: "bad_id",
Description: "No such bill found",
}
}
if code != 200 {
return nil, &RequestError{
ErrorCode: "Error " + strconv.Itoa(code),
Description: "HTTP Error " + strconv.Itoa(code),
}
}
return parseResponse(res)
}
// RejectBill
// Method sets bill status to rejected. ID is needed in arguments
//
// You can get ID from BillResponse, which was returned in PutBill
//
// Returns BillResponse on success, error on failed
func (c *Client) RejectBill(id string) (result *BillResponse, err error) {
res, code, err := c.makeRequest(
id+"/reject",
"POST",
"",
)
if err != nil {
return nil, err
}
if code == 401 {
return nil, &RequestError{
ErrorCode: "bad_token",
Description: "Bad token",
}
}
if code == 404 {
return nil, &RequestError{
ErrorCode: "bad_id",
Description: "No such bill found",
}
}
if code != 200 {
return nil, &RequestError{
ErrorCode: "Error " + strconv.Itoa(code),
Description: "HTTP Error " + strconv.Itoa(code),
}
}
return parseResponse(res)
}
// parseResponse
//
// Parses BillResponse or RequestError JSON
//
// Returns either BillResponse or error object
func parseResponse(jsonResponse string) (result *BillResponse, error error) {
var re RequestError
err := json.Unmarshal([]byte(jsonResponse), &re)
if err != nil {
return nil, err
}
if re.ErrorCode != "" {
return nil, re
}
var response BillResponse
err = json.Unmarshal([]byte(jsonResponse), &response)
if err != nil {
return nil, err
}
return &response, nil
}
// makeRequest
// Makes HTTP request to QIWI API server
//
// Arguments:
// - `url` : path to needed API method
// - `method` : HTTP method used in API call
// - `data` : JSON body data (for POST and PUT requests)
func (c *Client) makeRequest(url string, method string, data string) (json string, code int, err error) {
url = "https://api.qiwi.com/partner/bill/v1/bills/" + url
req, err := http.NewRequest(
method, url, strings.NewReader(data),
)
if err != nil {
return "", 0, err
}
req.Header.Add("Authorization", "Bearer "+c.token)
req.Header.Add("content-type", "application/json")
res, _ := c.client.Do(req)
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
buf := new(strings.Builder)
_, err = io.Copy(buf, res.Body)
if err != nil {
return "", 0, err
}
return buf.String(), res.StatusCode, nil
}
// pseudoUUID
// Generates random combination of symbols and letters
//
// Used as bill ID
func pseudoUUID() (uuid string) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println("Error: ", err)
return
}
uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return
}
// StartWebhook
// Starts webhook listening on given path and port.
//
// Returns channel with payment updates
//
// Usage:
//
// ch := c.StartWebhook("/qiwiWebhook", 80)
func (c *Client) StartWebhook(path string, port int) chan PaymentUpdate {
go c.startListening(path, port)
return c.ch
}
// startListening
// Starts webhook listening. Pauses current thread
func (c *Client) startListening(path string, port int) {
http.HandleFunc(path, c.onWebhook)
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil))
}
// onWebhook
// Called when new webhook request is caught
func (c *Client) onWebhook(w http.ResponseWriter, r *http.Request) {
buf := new(strings.Builder)
_, err := io.Copy(buf, r.Body)
if err != nil {
log.Println("Error while webhook: ", err.Error())
return
}
var upd PaymentUpdate
err = json.Unmarshal([]byte(buf.String()), &upd)
if err != nil {
log.Println("Error while webhook: ", err.Error())
return
}
w.Header().Add("Content-Type", "application/json")
_, err = w.Write([]byte("{\"error\":\"0\"}"))
if err != nil {
log.Println("Error while webhook: ", err.Error())
return
}
if c.verifyWebhook(upd, r.Header.Get("X-Api-Signature-SHA256")) {
c.ch <- upd
}
}
// verifyWebhook
// Method verifies update, returns true if update is authorized and false if not
//
// Arguments:
// - `update` : PaymentUpdate object
// - `hash` : X-Api-Signature-SHA256 header from webhook
func (c *Client) verifyWebhook(update PaymentUpdate, hash string) bool {
invoiceParameters := ""
invoiceParameters += update.Bill.Amount.Currency + "|"
invoiceParameters += update.Bill.Amount.Value + "|"
invoiceParameters += update.Bill.BillId + "|"
invoiceParameters += update.Bill.SiteId + "|"
invoiceParameters += update.Bill.Status.Value
h := hmac.New(sha256.New, []byte(c.token))
h.Write([]byte(invoiceParameters))
sha := hex.EncodeToString(h.Sum(nil))
if sha == hash {
return true
}
return false
}