-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebhook.go
52 lines (43 loc) · 1.14 KB
/
webhook.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
package ypmn
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"crypto/md5"
"encoding/hex"
"strconv"
)
type CallbackFunc func(map[string]interface{})
func WebhookHandler(path string, port int, merchant Merchant, externalUrl string, callback CallbackFunc, validateSignature bool) {
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
defer r.Body.Close()
if validateSignature {
date := r.Header.Get("X-Header-Date")
signature := r.Header.Get("X-Header-Signature")
h := md5.New()
h.Write([]byte(body))
hash := hex.EncodeToString(h.Sum(nil))
calculatedSignature := GetSignature(merchant, date, externalUrl, "POST", hash)
if(calculatedSignature != signature){
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
}
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
callback(data)
fmt.Fprintf(w, "OK")
})
log.Fatal(http.ListenAndServe(":" + strconv.Itoa(port), nil))
}