forked from jon4hz/go-btcpay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhooks.go
41 lines (34 loc) · 916 Bytes
/
webhooks.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
package btcpay
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
// Verify the webhook signatura and parse it into *InvoiceEvent
func VerifyWebhook(r *http.Request, webhookSecret string) (*InvoiceEvent, error) {
var messageMAC = []byte(strings.TrimPrefix(r.Header.Get("BTCPay-Sig"), "sha256="))
if len(messageMAC) == 0 {
return nil, errors.New("BTCPay-Sig header missing")
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var mac = hmac.New(sha256.New, []byte(webhookSecret))
mac.Write(body)
var expectedMAC = []byte(hex.EncodeToString(mac.Sum(nil)))
if !hmac.Equal(messageMAC, expectedMAC) {
return nil, fmt.Errorf("HMAC mismatch, got %s, want %s", messageMAC, expectedMAC)
}
var event = &InvoiceEvent{}
if err := json.Unmarshal(body, event); err != nil {
return nil, err
}
return event, nil
}