This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
/
signature.go
61 lines (49 loc) · 1.66 KB
/
signature.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
package qiwi
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
// Signature type holds keys to calculate signature.
type Signature struct {
Key, Message []byte
Hash string
Valid bool
}
// NewSignature return new signature.
func NewSignature(key, hash string) *Signature {
return &Signature{Key: []byte(key), Hash: hash}
}
// sign calculates checksum.
func (s *Signature) sign() bool {
mac := hmac.New(sha256.New, s.Key)
mac.Write(s.Message)
expectedMAC := mac.Sum(nil)
s.Valid = false
if hex.EncodeToString(expectedMAC) == s.Hash {
s.Valid = true
}
return s.Valid
}
// Verify HMAC-SHA256 signature hash used in Notify type.
func (s *Signature) Verify(p *Notify) bool {
switch p.Type {
case PaymentNotify:
// payment.paymentId|payment.createdDateTime|payment.amount.value
s.Message = []byte(fmt.Sprintf("%s|%s|%s", p.Payment.PaymentID, p.Payment.NotifyDate, p.Payment.Amount.Value))
case CaptureNotify:
// capture.captureId|capture.createdDateTime|capture.amount.value
s.Message = []byte(fmt.Sprintf("%s|%s|%s", p.Capture.CamptureID, p.Capture.NotifyDate, p.Capture.Amount.Value))
case RefundNotify:
// refund.refundId|refund.createdDateTime|refund.amount.value
s.Message = []byte(fmt.Sprintf("%s|%s|%s", p.Refund.RefundID, p.Refund.NotifyDate, p.Refund.Amount.Value))
case CheckCardNotify:
// checkPaymentMethod.requestUid|checkPaymentMethod.checkOperationDate
s.Message = []byte(fmt.Sprintf("%s|%s", p.CheckCard.RequestID, p.CheckCard.CheckDate))
default:
// fallback to PaymentType
s.Message = []byte(fmt.Sprintf("%s|%s|%s", p.Payment.PaymentID, p.Payment.NotifyDate, p.Payment.Amount.Value))
}
return s.sign()
}