This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnotify.go
70 lines (57 loc) · 1.86 KB
/
notify.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
package qiwi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// maxBodyBytes limit inbound payload to 64kb.
const maxBodyBytes int64 = 65536
// NotifyType from RSP.
type NotifyType string
const (
// PaymentNotify for payment notification.
PaymentNotify NotifyType = "PAYMENT"
// CaptureNotify for capture (2 stage) payments.
CaptureNotify NotifyType = "CAPTURE"
// RefundNotify for refunds.
RefundNotify NotifyType = "REFUND"
// CheckCardNotify for card check requests.
CheckCardNotify NotifyType = "CHECK_CARD"
)
// Notify holds incoming data from RSP.
type Notify struct {
Type NotifyType `json:"type"` // Notification type
Payment Payment `json:"payment,omitempty"`
Capture Payment `json:"capture,omitempty"`
Refund Payment `json:"refund,omitempty"`
CheckCard Card `json:"checkPaymentMethod,omitempty"`
Version string `json:"version"` // Notification version
}
// NewNotify returns Notify data from bytes.
func NewNotify(signkey, sign string, payload []byte) (*Notify, error) {
notify := &Notify{}
var err error
err = json.Unmarshal(payload, notify)
if err != nil {
return notify, fmt.Errorf("[QIWI] Notify: %w (%s)", ErrBadJSON, err)
}
// Check signature
if !NewSignature(signkey, sign).Verify(notify) {
err = ErrBadSignature
}
return notify, err
}
// NotifyParseHTTPRequest parses http request which returns Notify
// and also protects against a malicious client streaming
// an endless request body.
func NotifyParseHTTPRequest(signkey string, w http.ResponseWriter, r *http.Request) (*Notify, error) {
var payload bytes.Buffer
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
_, err := io.Copy(&payload, r.Body)
if err != nil {
return &Notify{}, fmt.Errorf("[QIWI] Notify payload http parser: %w: %s", ErrBadJSON, err)
}
return NewNotify(signkey, r.Header.Get("Signature"), payload.Bytes())
}