Last active
July 25, 2022 14:36
-
-
Save xssnick/1dab55e3a349d628a6b46ee3ffc5c5ea to your computer and use it in GitHub Desktop.
Example how to handle webhooks from TonUtils bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha512" | |
"encoding/base64" | |
"io/ioutil" | |
"net/http" | |
) | |
const MyURL = "https://mybackend.com/webhooks" | |
const MySecretKey = "FPLLNGZIEYOH54E1244OLS7K" | |
func handler(w http.ResponseWriter, req *http.Request) { | |
requestBody, err := ioutil.ReadAll(req.Body) | |
if err != nil { | |
w.WriteHeader(http.StatusBadRequest) | |
w.Write([]byte("cannot read request data")) | |
return | |
} | |
dataToCheck := MyURL + "|" + string(requestBody) | |
h := hmac.New(sha512.New, []byte(MySecretKey)) | |
h.Write([]byte(dataToCheck)) | |
signCalculated := h.Sum(nil) | |
signFromRequest := req.Header.Get("HMAC512-Signature") | |
if signFromRequest != base64.StdEncoding.EncodeToString(signCalculated) { | |
w.WriteHeader(http.StatusForbidden) | |
w.Write([]byte("signature not match")) | |
return | |
} | |
/* Transaction JSON example, you can parse it and use safely on this step | |
{ | |
"tx_id": "VdUG1YMbYqrinFDR4QR7j5CfGQ2O75m34bvxUKvmn00=", | |
"amount": "0.0002", | |
"event_type": "INTERNAL_IN", | |
"tx_sender": "EQAvyxX5g_GvynfNl_XVQReZ3rstK5bM2OYu9nvren1SRnuN", | |
"tx_receiver": "EQDnYZIpTwo9RN_84KZX3qIkLVIUJSo8d1yz1vMlKAp2uRtK", | |
"comment": "Hey kelvin you have to go to the office", | |
"body_boc": "te6cckEBAQEALQAAVgAAAABIZXkga2VsdmluIHlvdSBoYXZlIHRvIGdvIHRvIHRoZSBvZmZpY2Wc/TB0", | |
"tx_time": "2022-07-02T20:40:30Z", | |
"tx_discovered_time": "2022-07-02T20:40:38.451855Z" | |
} | |
*/ | |
println("Successfully received transaction!") | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte("OK")) | |
} | |
func main() { | |
http.HandleFunc("/webhooks", handler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment