import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io/ioutil"
"net/http"
"os"
)
func webhookHandler(w http.ResponseWriter, r *http.Request) {
// Get the signature from the header
webhookSignature := r.Header.Get("CodeQR-Signature")
if webhookSignature == "" {
http.Error(w, "No signature provided.", http.StatusUnauthorized)
return
}
// Copy this from the webhook details page
secret := os.Getenv("CODEQR_WEBHOOK_SECRET")
if secret == "" {
http.Error(w, "No secret provided.", http.StatusUnauthorized)
return
}
// Read the raw body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
// Calculate the HMAC
h := hmac.New(sha256.New, []byte(secret))
h.Write(body)
computedSignature := hex.EncodeToString(h.Sum(nil))
if webhookSignature != computedSignature {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
// Handle the webhook event
// ...
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}