-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpingback.go
More file actions
251 lines (223 loc) · 6.28 KB
/
pingback.go
File metadata and controls
251 lines (223 loc) · 6.28 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
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
// Package paymentwall provides a Go SDK for interacting with the Paymentwall APIs.
package paymentwall
import (
"fmt"
"net"
"strconv"
"strings"
"sync"
)
var (
_ipWhitelist map[string]struct{}
_cidrNet *net.IPNet
_once sync.Once
)
func initWhitelist() {
// 1) seed fixed addresses
_ipWhitelist = map[string]struct{}{
"174.36.92.186": {},
"174.36.96.66": {},
"174.36.92.187": {},
"174.36.92.192": {},
"174.37.14.28": {},
}
// 2) parse the /24 CIDR
_, cidr, err := net.ParseCIDR("216.127.71.0/24")
if err == nil {
_cidrNet = cidr
}
}
// Pingback represents a Paymentwall webhook notification validator.
type Pingback struct {
Client *Client
Params map[string]any
IPAddress string
Errors []string
}
// NewPingback constructs a Pingback with given params and source IP.
func NewPingback(client *Client, params map[string]any, ip string) *Pingback {
return &Pingback{
Client: client,
Params: params,
IPAddress: ip,
Errors: []string{},
}
}
// Validate runs parameter, IP whitelist, and signature checks.
// skipIPWhitelist allows bypassing the IP check (for testing).
func (p *Pingback) Validate(skipIPWhitelist bool) bool {
if !p.isParamsValid() {
p.Errors = append(p.Errors, "Missing parameters")
return false
}
if !skipIPWhitelist && !p.isIPAddressValid() {
p.Errors = append(p.Errors, "IP address is not whitelisted")
return false
}
if !p.isSignatureValid() {
p.Errors = append(p.Errors, "Wrong signature")
return false
}
return true
}
// isParamsValid checks for required fields and records missing ones.
// VC needs ["uid","currency","type","ref","sig"];
// Goods/Cart need ["uid","goodsid","type","ref","sig"].
func (p *Pingback) isParamsValid() bool {
var required []string
if p.Client.APIType == APIVC {
required = []string{"uid", "currency", "type", "ref", "sig"}
} else {
required = []string{"uid", "goodsid", "type", "ref", "sig"}
}
valid := true
for _, key := range required {
if _, ok := p.Params[key]; !ok {
p.Errors = append(p.Errors, fmt.Sprintf("Parameter %s is missing", key))
valid = false
}
}
return valid
}
// isIPAddressValid checks if the source IP is in Paymentwall's whitelist.
func (p *Pingback) isIPAddressValid() bool {
// one-time init
_once.Do(initWhitelist)
// quick exact match
if _, ok := _ipWhitelist[p.IPAddress]; ok {
return true
}
// if we parsed the CIDR, check containment
if _cidrNet != nil {
ip := net.ParseIP(p.IPAddress)
if ip != nil && _cidrNet.Contains(ip) {
return true
}
}
return false
}
// isSignatureValid recalculates and compares the signature.
func (p *Pingback) isSignatureValid() bool {
// 1) Determine sign_version
sv := SigV1
if val, ok := p.Params["sign_version"]; ok {
if i, err := strconv.Atoi(fmt.Sprint(val)); err == nil {
sv = SignatureVersion(i)
}
} else if p.Client.APIType == APICart {
// default for Cart
sv = SigV2
}
// 2) Build a copy of params without "sig"
signedParams := make(map[string]any, len(p.Params))
for k, v := range p.Params {
if k == "sig" {
continue
}
signedParams[k] = v
}
// 3) Inject sign_version for v2/v3
if sv != SigV1 {
signedParams["sign_version"] = int(sv)
}
// 4) For SigV1, filter down to only the required fields
if sv == SigV1 {
var fields []string
switch p.Client.APIType {
case APIVC:
fields = []string{"uid", "currency", "type", "ref"}
case APIGoods:
fields = []string{"uid", "goodsid", "slength", "speriod", "type", "ref"}
default: // Cart
fields = []string{"uid", "goodsid", "type", "ref"}
}
filtered := make(map[string]any, len(fields))
for _, f := range fields {
if v, ok := signedParams[f]; ok {
filtered[f] = v
}
}
signedParams = filtered
}
// 5) Delegate to Client.CalculateSignature (handles V1, V2, V3 hashing)
sigCalc, err := p.Client.CalculateSignature(signedParams, sv)
if err != nil {
return false
}
// 6) Compare to the original
return fmt.Sprint(p.Params["sig"]) == sigCalc
}
// GetUserID returns the "uid" parameter.
func (p *Pingback) GetUserID() string {
return fmt.Sprint(p.Params["uid"])
}
// GetType returns the pingback type as int.
func (p *Pingback) GetType() (int, error) {
return strconv.Atoi(fmt.Sprint(p.Params["type"]))
}
// GetVCAmount returns the "currency" parameter for virtual currency.
func (p *Pingback) GetVCAmount() string {
return fmt.Sprint(p.Params["currency"])
}
// GetProductID returns the product ID from "goodsid".
func (p *Pingback) GetProductID() string {
return fmt.Sprint(p.Params["goodsid"])
}
// GetProduct reconstructs a Product from pingback parameters.
func (p *Pingback) GetProduct() (*Product, error) {
length, _ := strconv.Atoi(fmt.Sprint(p.Params["slength"]))
periodType := fmt.Sprint(p.Params["speriod"])
t := ProductTypeFixed
if length > 0 {
t = ProductTypeSubscription
}
return NewProduct(
fmt.Sprint(p.Params["goodsid"]),
0, "", "", t, length, periodType, false, nil,
)
}
// GetProducts returns a slice of Products for Cart API.
func (p *Pingback) GetProducts() ([]*Product, error) {
var prods []*Product
if vals, ok := p.Params["goodsid"].([]any); ok {
for _, v := range vals {
id := fmt.Sprint(v)
if prod, err := NewProduct(id, 0, "", "", ProductTypeFixed, 0, "", false, nil); err == nil {
prods = append(prods, prod)
}
}
}
return prods, nil
}
// IsDeliverable returns true if pingback type indicates delivery.
func (p *Pingback) IsDeliverable() bool {
t, err := p.GetType()
return err == nil && (t == 0 || t == 1 || t == 201)
}
// IsCancelable returns true if pingback type indicates cancellation.
func (p *Pingback) IsCancelable() bool {
t, err := p.GetType()
return err == nil && (t == 2 || t == 202)
}
// IsUnderReview returns true if pingback type indicates under review.
func (p *Pingback) IsUnderReview() bool {
t, err := p.GetType()
return err == nil && t == 200
}
// ErrorSummary returns accumulated errors.
func (p *Pingback) ErrorSummary() string {
return strings.Join(p.Errors, "\n")
}
// GetReferenceID returns the "ref" parameter.
func (p *Pingback) GetReferenceID() string {
return fmt.Sprint(p.Params["ref"])
}
// GetPingbackUniqueID returns a unique ID composed of ref and type, e.g. "REF123_0".
func (p *Pingback) GetPingbackUniqueID() string {
ref := p.GetReferenceID()
t, err := p.GetType()
if err != nil {
return ref
}
return fmt.Sprintf("%s_%d", ref, t)
}