How webhook signatures work, the four checks a receiver must make (raw body, HMAC, constant-time compare, timestamp), key rotation, and a tested Go verifier for the Standard Webhooks format.

A webhook endpoint is a public URL that changes state in your system, so anyone who finds it can send a fake "payment succeeded" event. Signatures are how the receiver proves a request came from the sender and was not altered.
The scheme is simple, an HMAC over the request, but the verification has a few details that break in practice. This guide covers each one with a tested Go verifier.
The sender and the receiver share a secret, and for each delivery the sender computes an HMAC-SHA256 over a signed content string and puts the result in a header. The receiver builds the same string from what it received, computes its own HMAC and compares.
Providers differ in the details: GitHub signs the body and sends X-Hub-Signature-256: sha256=<hex>, while Stripe signs a timestamp and the body together. The Standard Webhooks specification, an open format for webhook senders, signs {id}.{timestamp}.{body} and sends three headers:
webhook-id: msg_2KWPBgLlAfxdpx2AI54pPJ85f4W webhook-timestamp: 1763500000 webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=
The signature header can carry several space-separated values, which is how key rotation works: during the overlap, the sender signs with both the old and new keys.
This verifier implements the Standard Webhooks format, taking the raw body, rejecting stale timestamps and comparing with hmac.Equal, which runs in constant time:
package webhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"net/http"
"strconv"
"strings"
"time"
)
var (
ErrMissingHeaders = errors.New("missing webhook headers")
ErrTooOld = errors.New("timestamp outside tolerance")
ErrBadSignature = errors.New("no matching signature")
)
const tolerance = 5 * time.Minute
// Verify checks a Standard Webhooks signature: base64(HMAC-SHA256(secret,
// "{id}.{timestamp}.{body}")) in the webhook-signature header, which can
// carry several space-separated "v1,<sig>" values during key rotation.
func Verify(secret []byte, h http.Header, body []byte, now time.Time) error {
id := h.Get("webhook-id")
ts := h.Get("webhook-timestamp")
sigs := h.Get("webhook-signature")
if id == "" || ts == "" || sigs == "" {
return ErrMissingHeaders
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return ErrMissingHeaders
}
if d := now.Sub(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
return ErrTooOld // blocks replays of old captured requests
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(id + "." + ts + "."))
mac.Write(body) // the raw bytes, before any JSON decoding
expected := mac.Sum(nil)
for _, s := range strings.Fields(sigs) {
version, sig, ok := strings.Cut(s, ",")
if !ok || version != "v1" {
continue
}
got, err := base64.StdEncoding.DecodeString(sig)
if err == nil && hmac.Equal(got, expected) { // constant-time compare
return nil
}
}
return ErrBadSignature
}
The handler reads the body once with a size limit, verifies before parsing anything, and answers quickly. An unset or malformed secret fails at startup, so verification never runs with an empty HMAC key. The worker claims webhook-id with a unique insert before the side effect, so a replay inside the timestamp window cannot run the work twice. Standard Webhooks secrets are whsec_ followed by a base64 key, and the HMAC uses the decoded bytes:
// Standard Webhooks secrets look like "whsec_<base64 key>".
var secret = func() []byte {
raw := os.Getenv("WEBHOOK_SECRET")
if !strings.HasPrefix(raw, "whsec_") {
panic("WEBHOOK_SECRET must start with whsec_")
}
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(raw, "whsec_"))
if err != nil || len(key) == 0 {
panic("WEBHOOK_SECRET must contain a non-empty base64 key")
}
return key
}()
func HandlePayments(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
if err := Verify(secret, r.Header, body, time.Now()); err != nil {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
// Enqueue the work, then answer. Do not claim webhook-id here, or a crash
// before the queue write can acknowledge a replay and drop the event.
if err := enqueuePayment(r.Context(), r.Header.Get("webhook-id"), body); err != nil {
http.Error(w, "try again", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
}
// claimWebhookID is called by the worker before the side effect.
func claimWebhookID(ctx context.Context, id string) (bool, error) {
res, err := db.ExecContext(ctx, `
INSERT INTO webhook_events (id) VALUES ($1)
ON CONFLICT (id) DO NOTHING`, id)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n == 1, err
}
A short test covers the cases that matter: a valid signature next to an unknown old one passes, while a body with one extra byte, a timestamp ten minutes off and the wrong secret all fail:
func TestVerify(t *testing.T) {
secret := []byte("whsec-test-secret")
body := []byte(`{"type":"payment.succeeded","data":{"id":"pay_1"}}`)
now := time.Unix(1_763_500_000, 0)
h := http.Header{}
h.Set("webhook-id", "msg_1")
h.Set("webhook-timestamp", strconv.FormatInt(now.Unix(), 10))
h.Set("webhook-signature", "v1,b2xkLWtleQ== "+sign(secret, "msg_1", now.Unix(), body))
if err := Verify(secret, h, body, now); err != nil {
t.Fatalf("valid: %v", err)
}
if err := Verify(secret, h, append(body, ' '), now); err != ErrBadSignature {
t.Fatalf("tampered body: %v", err)
}
if err := Verify(secret, h, body, now.Add(10*time.Minute)); err != ErrTooOld {
t.Fatalf("replay: %v", err)
}
if err := Verify([]byte("wrong"), h, body, now); err != ErrBadSignature {
t.Fatalf("wrong secret: %v", err)
}
}
Idempotency. Senders retry on timeouts and non-2xx responses, so the same event arrives more than once. Store the message ID with a unique constraint and skip IDs you have seen, the same approach as idempotency keys for APIs.
Fast responses. Verify, record and enqueue, then return 2xx, since doing the actual work inside the request risks the sender's timeout, which triggers a retry while the first attempt is still running.
Secret rotation. Accept every v1 signature in the header, store the new secret alongside the old one during the overlap, and remove the old one once the sender has switched.
Logging without secrets. Log the message ID and the rejection reason, never the secret or the full signature header, so failed verifications are debuggable without leaking material for forgeries.
Encore is a backend framework with built-in infrastructure, and a webhook receiver uses three of its pieces: a raw endpoint for the untouched body, a secret for the signing key, and a Pub/Sub topic to hand verified events to workers with retries.

Run in your terminal to get started locally.
With Verify from above in the same package, the endpoint looks like this:
// webhooks/webhooks.go
package webhooks
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"strings"
"time"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
// Set per environment with `encore secret set --type prod PaymentsWebhookSecret`.
var secrets struct {
PaymentsWebhookSecret string
}
var db = sqldb.NewDatabase("webhooks", sqldb.DatabaseConfig{
Migrations: "./migrations", // webhook_events(id TEXT PRIMARY KEY)
})
type PaymentEvent struct {
WebhookID string `json:"webhook_id"`
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
// Verified events are queued and handled by subscribers with retries.
var PaymentEvents = pubsub.NewTopic[*PaymentEvent]("payment-events", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
// A raw endpoint receives the untouched request body, which the HMAC needs.
//
//encore:api public raw method=POST path=/webhooks/payments
func Payments(w http.ResponseWriter, req *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, req.Body, 1<<20))
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
raw := secrets.PaymentsWebhookSecret
if !strings.HasPrefix(raw, "whsec_") {
http.Error(w, "misconfigured secret", http.StatusInternalServerError)
return
}
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(raw, "whsec_"))
if err != nil || len(key) == 0 {
http.Error(w, "misconfigured secret", http.StatusInternalServerError)
return
}
if err := Verify(key, req.Header, body, time.Now()); err != nil {
rlog.Warn("rejected webhook", "err", err)
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
var ev PaymentEvent
if err := json.Unmarshal(body, &ev); err != nil {
http.Error(w, "bad payload", http.StatusBadRequest)
return
}
ev.WebhookID = req.Header.Get("webhook-id")
if _, err := PaymentEvents.Publish(req.Context(), &ev); err != nil {
http.Error(w, "try again", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
}
// The unique insert lives in the subscriber, so a retried webhook can publish
// again without dropping work, and a second delivery is a no-op.
var _ = pubsub.NewSubscription(PaymentEvents, "record-payment",
pubsub.SubscriptionConfig[*PaymentEvent]{
Handler: func(ctx context.Context, e *PaymentEvent) error {
res, err := db.Exec(ctx, `
INSERT INTO webhook_events (id) VALUES ($1)
ON CONFLICT (id) DO NOTHING`, e.WebhookID)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
return nil // already processed
}
// Apply the payment side effect here.
return nil
},
},
)
Under encore run with a local secret, a correctly signed request returns 204, while the same request with one extra byte in the body or a timestamp 15 minutes old returns 401 and logs the reason. Returning 503 when publishing fails tells the sender to retry later, so no verified event is lost. The subscriber claims webhook-id with a unique insert before the side effect, so a replay or an at-least-once redelivery does not run the work twice.
The secret is stored per environment and never appears in code or config files. On deploy, Encore creates the topic in your own AWS or GCP account and provisions an IAM role for the service, or a service account on GCP. A coding agent adding a second provider writes another raw endpoint and secret in the same pattern, and the local request trace shows each rejection with its reason.
Best fit: Go and TypeScript teams receiving webhooks from several providers who want verification, secrets and asynchronous processing in one place without a separate queue to run.
The sender and receiver share a secret, and the sender computes an HMAC, usually HMAC-SHA256, over the request body and often a timestamp and message ID, and sends it in a header. The receiver computes the same HMAC over the bytes it received and accepts the request only if the two values match.
The most common cause is hashing a re-serialized body instead of the raw bytes. Frameworks that parse JSON before your handler runs change whitespace and key order, so the HMAC no longer matches. Other causes are using the secret string instead of its decoded bytes, a wrong signed-content format, and comparing hex with base64.
A normal string comparison returns as soon as one byte differs, so response timing can leak how much of a forged signature is correct. Constant-time functions such as Go's hmac.Equal or Python's hmac.compare_digest take the same time regardless of where the mismatch is.
Include a timestamp in the signed content and reject requests whose timestamp is more than a few minutes from your clock. Store the message ID of processed webhooks and skip duplicates, which also handles the sender's own retries.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.