If every Stripe webhook your Go service receives fails with a log line like stripe webhook: signature verification failed, and you are certain the signing secret is right, this is for you. It happened to me right after I moved my store to a new Stripe account and a new secret. The env file held the new secret wrapped in single quotes, STRIPE_WEBHOOK_SECRET='whsec_...'. I removed them and restarted the service, and after more migration fixes in the same session the pipeline worked. The service is set up to load that file through systemd’s EnvironmentFile=, though, and systemd removes quotes like those, so the quotes alone should not have mattered. I never established the real cause. This article shows you how to check what your process actually received instead of guessing.

By the end you will have a standard-library Go handler that verifies Stripe signatures correctly, a test that signs its own payloads, a systemd setup that loads the secret predictably, and a debugging checklist that never prints the secret. It assumes you can write a basic Go HTTP server and have root on a Linux machine that runs systemd.

Last verified: December 2026. Versions used: Go 1.24.7 (standard library only, nothing version-specific; Go 1.24 is past upstream support, so build with a current release); systemd 255 (parser tested) and the systemd 252 and 262 man pages; Stripe CLI documentation for 1.55.x; stripe-go v87.2.0 for comparison.

What Happened

My license server, Quartermaster, takes a Stripe checkout.session.completed webhook, verifies it, and queues a license. The verifier is about forty lines of standard-library Go, and it had worked since I wrote it in July.

When I moved the store to a new Stripe account for my LLC, I created a new webhook endpoint and copied its new whsec_ secret into the service’s env file. The journal then showed two deliveries, fifteen seconds apart, both rejected:

Copied!
stripe webhook: signature verification failed
stripe webhook: signature verification failed

I was sure the secret was the right value, so I read the code instead. The verification logic was right, and the secret came straight from os.Getenv("STRIPE_WEBHOOK_SECRET"). The next step was to look for hidden characters in the env file with cat -A, which prints $ at each line end, ^M for a carriage return, and makes trailing spaces visible:

Copied!
STRIPE_WEBHOOK_SECRET='whsec_<REDACTED>'$

Single quotes. I removed them, restarted the service, and moved on to the rest of the migration. After that, and after several other fixes in the same session, the whole pipeline worked end to end.

One wrong turn on the way: the license signer’s log showed connection refused against the server’s queue API, which looked like a second failure. It was a stale line from before the restart. The tunnel and the listener were both healthy.

Here is the part I cannot close. systemd’s EnvironmentFile= documentation treats a single-quoted value like shell single-quoted text: the contents are taken literally and the quotes are not part of the value. A test of systemd 255’s env-file parser shows the line STRIPE_WEBHOOK_SECRET='whsec_example' coming out as STRIPE_WEBHOOK_SECRET=whsec_example. So if systemd loaded the file, those quotes never reached os.Getenv. My notes do not show how the running process got its environment that day or what it actually held, and these explanations all fit what I saw:

  • The process predated the edit. systemd reads environment files only when it starts the process. If the service was not restarted after the secret went in, it was still verifying with the old account’s secret. The restart I did after removing the quotes would have fixed that by itself.
  • The deliveries came from a different endpoint. Later in the same session a test checkout appeared to be running in the old account’s sandbox. Each endpoint has its own secret, so a delivery signed by the old account’s endpoint fails against the new account’s secret no matter how the file is quoted.
  • Something other than systemd loaded the file. A shell that sources the file strips the quotes too, but a loader that only splits each line on =, such as docker run --env-file or a few lines of hand-rolled Go, keeps them (see the table near the end). Quartermaster itself has no loader; it calls os.Getenv, so this would have to sit outside the binary.

My handler also logged the same line for a stale timestamp as for a wrong signature, so even the error text could not separate the cases. I did not capture the evidence that would tell these apart. The rest of this article makes sure you do.

How It Works

Stripe signs every webhook delivery with a secret that belongs to that one endpoint. The signature travels in the Stripe-Signature header, a single line of comma-separated key=value entries:

Copied!
Stripe-Signature: t=1798765432,v1=5257a8...,v1=38c9f7...,v0=6ffbb5...,secret=whsec_****PzVt,payload=a25aefc6
  • t is the Unix time when Stripe signed this delivery attempt. Retries get a new timestamp and a new signature.
  • v1 is the signature: an HMAC (a keyed hash; only someone holding the key can produce it) using SHA-256. There can be more than one.
  • v0 appears only on sandbox events and must be ignored.
  • secret, destination and payload are optional debug entries. secret is a redacted form of the endpoint’s newest secret, and payload is a suffix of the SHA-256 digest of the body Stripe sent. They are not covered by the signature, so never use them to authenticate anything, but they are very useful for diagnosis.

Your code must accept entries it does not recognize and must not depend on their order or count.

To verify a delivery:

  1. Split the header on ,, then each entry on the first =. Keep t and every v1.
  2. Build signed_payload: the timestamp string exactly as sent, a ., then the raw request body bytes.
  3. Compute HMAC-SHA256 over signed_payload, keyed with the endpoint’s signing secret.
  4. Compare the result with each v1 value using a constant-time comparison. If one matches, reject the request anyway if the timestamp is outside your tolerance. If none match, reject it.
Stripe computes the HMAC over the timestamp and raw body; the Go service recomputes it with the secret loaded from its environment and compares

The signature is computed on Stripe’s side and recomputed on yours. The amber path is the secret: if anything changes it between the env file and os.Getenv, every check fails.

Five details decide whether this works:

  • Raw body, before any parsing. The HMAC covers the exact bytes Stripe sent. If you decode the JSON and re-encode it, whitespace and key order change and the signature no longer matches. In Go, read r.Body into a []byte, verify, then json.Unmarshal those same bytes.
  • Constant-time comparison. A normal == or bytes.Equal can return as soon as the first byte differs, which leaks timing information to an attacker. hmac.Equal does not.
  • Timestamp tolerance. The timestamp is inside the signed payload, so an attacker cannot change it. Rejecting old timestamps stops someone from replaying a captured delivery. Stripe’s official libraries default to five minutes. Stripe says never to use a tolerance of 0 with its libraries, because that turns the check off, and to keep your clock synchronized with NTP.
  • Several v1 signatures during rotation. When you roll an endpoint’s secret in the Dashboard you can keep the old one valid for up to 7 days. During that window Stripe sends one v1 per active secret. Accept the request if any one matches.
  • Secrets are per endpoint and per mode. The same URL registered for sandbox and live has a different secret for each. The secret that stripe listen prints differs from any Dashboard endpoint’s secret. A new account means new endpoints and new secrets.

The official Go library does all of this in one call: webhook.ConstructEvent(payload, header, secret) from github.com/stripe/stripe-go/v87/webhook (check for the current major version). It uses the same five-minute default, rejects only timestamps that are too old, and by default also returns an error when the event’s API version is from a different release train (the name after the date, as in 2026-11-18.endive) than the one that library release was built for. Quartermaster briefly imported stripe-go for one API call. When that call went away nothing else needed the module, so go mod tidy removed it, and the signature check stayed in the standard library. It still calls Stripe’s API with plain net/http today. Either choice is reasonable. The library gets updated when Stripe changes something. Your own forty lines stay the same until you change them.

Prerequisites

  • Go installed (any supported release; the code uses only the standard library).
  • A Linux server with systemd and root access, and a reverse proxy that terminates TLS in front of the service. Stripe requires HTTPS for live-mode endpoints. If you have not set that up before, the self-hosting article covers it.
  • A Stripe account, and the Stripe CLI installed and logged in with stripe login.
  • The values you will need: your public webhook URL (for example https://example.com/stripe/webhook) and the endpoint’s signing secret, which starts with whsec_.

Step 1: Write the Verifier and Handler

Create a module and one file. The handler limits the body size, verifies before it parses, acknowledges events it does not handle, and ignores duplicate deliveries.

Copied!
mkdir stripewebhook && cd stripewebhook
go mod init example.com/stripewebhook
vim main.go

In vim, press i to insert, paste the code, then Esc and :wq to save and quit.

Copied!
// Command stripewebhook receives Stripe webhook events and verifies their
// signatures using only the Go standard library.
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
    "sync"
    "time"
)

const (
    maxBodyBytes = 1 << 20         // 1 MiB. My limit, not a number from Stripe.
    tolerance    = 5 * time.Minute // Same default as Stripe's official libraries.
)

var (
    errNoHeader  = errors.New("no Stripe-Signature header")
    errBadHeader = errors.New("Stripe-Signature header has no t or no v1 entry")
    errNoMatch   = errors.New("no v1 signature matches")
    errTooOld    = errors.New("timestamp outside tolerance")
)

// verifySignature checks a Stripe-Signature header against the raw request
// body. now is passed in so tests can control the clock.
func verifySignature(payload []byte, header, secret string, now time.Time) error {
    if header == "" {
        return errNoHeader
    }
    var ts string
    var sigs [][]byte
    for _, part := range strings.Split(header, ",") {
        key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
        if !ok {
            continue
        }
        switch key {
        case "t":
            ts = value
        case "v1":
            sig, err := hex.DecodeString(value)
            if err == nil {
                sigs = append(sigs, sig)
            }
        }
        // v0, secret, destination, payload and any future entries are ignored.
    }
    if ts == "" || len(sigs) == 0 {
        return errBadHeader
    }
    unix, err := strconv.ParseInt(ts, 10, 64)
    if err != nil {
        return errBadHeader
    }

    // signed_payload = <t exactly as sent> + "." + <raw body bytes>
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(ts))
    mac.Write([]byte("."))
    mac.Write(payload)
    expected := mac.Sum(nil)

    matched := false
    for _, sig := range sigs { // more than one v1 while a rolled secret is still active
        if hmac.Equal(expected, sig) {
            matched = true
            break
        }
    }
    if !matched {
        return errNoMatch
    }

    age := now.Sub(time.Unix(unix, 0))
    if age > tolerance || age < -tolerance {
        return errTooOld
    }
    return nil
}

// secretHint describes a secret without revealing it.
func secretHint(s string) string {
    if len(s) < 12 {
        return fmt.Sprintf("len=%d (too short to be a whsec_ secret)", len(s))
    }
    return fmt.Sprintf("len=%d first6=%q last4=%q", len(s), s[:6], s[len(s)-4:])
}

// headerEntry returns the first value for key in a Stripe-Signature header.
func headerEntry(header, key string) string {
    for _, part := range strings.Split(header, ",") {
        if k, v, ok := strings.Cut(strings.TrimSpace(part), "="); ok && k == key {
            return v
        }
    }
    return ""
}

// event declares only the fields this handler reads.
type event struct {
    ID   string `json:"id"`
    Type string `json:"type"`
    Data struct {
        Object struct {
            ID            string `json:"id"`
            PaymentStatus string `json:"payment_status"`
        } `json:"object"`
    } `json:"data"`
}

type server struct {
    secret string
    now    func() time.Time

    mu        sync.Mutex
    fulfilled map[string]bool // stand-in for a UNIQUE column in a real database
}

func (s *server) webhook(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        w.Header().Set("Allow", http.MethodPost)
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }

    r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
    body, err := io.ReadAll(r.Body)
    if err != nil {
        var tooBig *http.MaxBytesError
        if errors.As(err, &tooBig) {
            http.Error(w, "payload too large", http.StatusRequestEntityTooLarge)
            return
        }
        http.Error(w, "bad request", http.StatusBadRequest)
        return
    }

    header := r.Header.Get("Stripe-Signature")
    if err := verifySignature(body, header, s.secret, s.now()); err != nil {
        sum := sha256.Sum256(body)
        log.Printf("stripe webhook: signature verification failed: %v; "+
            "ours: %s; stripe secret hint: %q; body sha256: %x; stripe payload hint: %q",
            err, secretHint(s.secret), headerEntry(header, "secret"), sum, headerEntry(header, "payload"))
        http.Error(w, "invalid signature", http.StatusBadRequest)
        return
    }

    // Only now is the body trusted enough to parse.
    var evt event
    if err := json.Unmarshal(body, &evt); err != nil {
        http.Error(w, "bad payload", http.StatusBadRequest)
        return
    }
    if evt.Type != "checkout.session.completed" {
        w.WriteHeader(http.StatusOK) // acknowledge events we don't handle so Stripe stops sending them
        return
    }

    session := evt.Data.Object
    s.mu.Lock()
    already := s.fulfilled[session.ID]
    s.fulfilled[session.ID] = true
    s.mu.Unlock()
    if already {
        log.Printf("stripe webhook: %s already fulfilled, ignoring duplicate (event %s)", session.ID, evt.ID)
        w.WriteHeader(http.StatusOK)
        return
    }

    // Queue the real work (license, email, ...) here and return quickly.
    log.Printf("stripe webhook: queued %s (payment_status=%s, event %s)", session.ID, session.PaymentStatus, evt.ID)
    w.WriteHeader(http.StatusOK)
}

func main() {
    secret := os.Getenv("STRIPE_WEBHOOK_SECRET")
    if !strings.HasPrefix(secret, "whsec_") || strings.TrimSpace(secret) != secret {
        log.Fatalf("STRIPE_WEBHOOK_SECRET does not look like a signing secret: %s", secretHint(secret))
    }
    log.Printf("webhook secret loaded: %s", secretHint(secret))

    addr := os.Getenv("LISTEN_ADDR")
    if addr == "" {
        addr = "127.0.0.1:8080"
    }

    s := &server{secret: secret, now: time.Now, fulfilled: make(map[string]bool)}
    mux := http.NewServeMux()
    mux.HandleFunc("/stripe/webhook", s.webhook)

    srv := &http.Server{
        Addr:              addr,
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       15 * time.Second,
        WriteTimeout:      15 * time.Second,
    }
    log.Printf("listening on %s", addr)
    log.Fatal(srv.ListenAndServe())
}

A few decisions worth knowing about:

  • The startup check refuses to run if the secret does not start with whsec_ or has whitespace around it. A quoted secret dies here with a clear message instead of failing every delivery later. Both Stripe-issued secret types start with whsec_.
  • secretHint logs the length, first six characters and last four. Stripe’s own secret= debug entry is redacted down to the last four in Stripe’s documented examples, so you can compare the two without either one appearing in full in your logs.
  • The tolerance check runs in both directions. Stripe’s manual verification steps describe the difference between the two times; stripe-go only rejects timestamps that are too old. A timestamp from the future is just as suspicious.
  • Idempotency. Stripe can deliver the same event more than once, and it retries any delivery that does not get a 2xx response: for up to three days in live mode, three times over a few hours in a sandbox. Quartermaster stores a key built from the Checkout Session ID in a database column with a UNIQUE constraint, so a retry hits the constraint and is acknowledged without issuing a second license. The map here stands in for that column. Use a real database in production.
  • Return 200 for anything you will not act on. Unhandled event types get a 200. So do sessions my shop declines to fulfil (in my case, a non-US billing country, because the shop sells to US customers only). A non-2xx would only make Stripe retry.

Step 2: Test It With a Generated Signature

The test signs payloads the way Stripe does, using a made-up secret, and covers the failure modes from this article: a quoted secret, a secret from a different endpoint, a rolled secret, a re-serialized body, a stale timestamp and an oversized body.

Copied!
vim main_test.go
Copied!
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
    "time"
)

// Made-up secrets for the test. Never put a real one in a test file.
const (
    testSecret    = "whsec_test_0123456789abcdef"
    rotatedSecret = "whsec_test_fedcba9876543210"
)

var fixedNow = time.Unix(1798765432, 0)

const body = `{"id":"evt_test_1","object":"event","type":"checkout.session.completed",` +
    `"data":{"object":{"id":"cs_test_1","object":"checkout.session","payment_status":"paid"}}}`

// sign does what Stripe does: HMAC-SHA256 over "<t>.<body>" with the secret.
func sign(t time.Time, payload, secret string) string {
    mac := hmac.New(sha256.New, []byte(secret))
    fmt.Fprintf(mac, "%d.%s", t.Unix(), payload)
    return hex.EncodeToString(mac.Sum(nil))
}

func newServer(secret string) *server {
    return &server{secret: secret, now: func() time.Time { return fixedNow }, fulfilled: map[string]bool{}}
}

func post(s *server, payload, header string) int {
    req := httptest.NewRequest(http.MethodPost, "/stripe/webhook", strings.NewReader(payload))
    req.Header.Set("Stripe-Signature", header)
    rec := httptest.NewRecorder()
    s.webhook(rec, req)
    return rec.Code
}

func TestWebhook(t *testing.T) {
    ts := fixedNow.Unix()
    good := fmt.Sprintf("t=%d,v1=%s", ts, sign(fixedNow, body, testSecret))

    tests := []struct {
        name    string
        secret  string // what the server loaded
        payload string
        header  string
        want    int
    }{
        {"valid", testSecret, body, good, http.StatusOK},
        {"valid with v0 and debug entries", testSecret, body,
            good + ",v0=00ff,secret=whsec_****cdef,payload=deadbeef", http.StatusOK},
        {"server secret wrapped in quotes", "'" + testSecret + "'", body, good, http.StatusBadRequest},
        {"server secret from another endpoint", rotatedSecret, body, good, http.StatusBadRequest},
        {"rolled secret, two v1 entries", rotatedSecret, body,
            good + ",v1=" + sign(fixedNow, body, rotatedSecret), http.StatusOK},
        {"body re-serialized by middleware", testSecret, strings.ReplaceAll(body, ",", ", "), good, http.StatusBadRequest},
        {"timestamp too old", testSecret, body,
            fmt.Sprintf("t=%d,v1=%s", ts-301, sign(fixedNow.Add(-301*time.Second), body, testSecret)),
            http.StatusBadRequest},
        {"no header", testSecret, body, "", http.StatusBadRequest},
        {"too large", testSecret, strings.Repeat("x", maxBodyBytes+1), good, http.StatusRequestEntityTooLarge},
    }
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            if got := post(newServer(tc.secret), tc.payload, tc.header); got != tc.want {
                t.Fatalf("status = %d, want %d", got, tc.want)
            }
        })
    }
}

func TestDuplicateDeliveryFulfilsOnce(t *testing.T) {
    s := newServer(testSecret)
    header := fmt.Sprintf("t=%d,v1=%s", fixedNow.Unix(), sign(fixedNow, body, testSecret))
    for i := 0; i < 2; i++ {
        if got := post(s, body, header); got != http.StatusOK {
            t.Fatalf("delivery %d: status = %d, want 200", i+1, got)
        }
    }
    if n := len(s.fulfilled); n != 1 {
        t.Fatalf("fulfilled %d sessions, want 1", n)
    }
}
Copied!
gofmt -l . && go vet ./... && go test ./...
Copied!
ok      example.com/stripewebhook   0.016s

Run go test -v ./... to see each case and the failure log lines. The quoted-secret case logs first6="'whsec" last4="def'", which is what a quoted secret looks like in that hint.

Step 3: Install the Service and Load the Secret

Build a static binary and create a system user with no login shell for the service.

Copied!
CGO_ENABLED=0 go build -o stripewebhook .
sudo useradd --system --no-create-home --shell /usr/sbin/nologin stripewebhook
sudo install -m 0755 stripewebhook /usr/local/bin/stripewebhook
sudo install -m 0600 -o root -g root /dev/null /etc/stripewebhook.env
sudo vim /etc/stripewebhook.env

Write the values without quotes. systemd would remove them, but other loaders keep them (see the table below), and a file without quotes means the same thing everywhere.

Copied!
STRIPE_WEBHOOK_SECRET=<YOUR_WHSEC_SECRET>
LISTEN_ADDR=127.0.0.1:8080

The file can be readable by root only, because systemd’s service manager reads it as root before it starts the process as the unprivileged user. Now the unit:

Copied!
sudo vim /etc/systemd/system/stripewebhook.service
Copied!
[Unit]
Description=Stripe webhook receiver
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=stripewebhook
Group=stripewebhook
EnvironmentFile=/etc/stripewebhook.env
ExecStart=/usr/local/bin/stripewebhook
Restart=on-failure
RestartSec=5
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target
Copied!
sudo systemctl daemon-reload
sudo systemctl enable --now stripewebhook
sudo journalctl -u stripewebhook -n 5 --no-pager

You should see webhook secret loaded: len=<N> first6="whsec_" last4="<last four>", where <N> and the last four match the secret in the Dashboard. Point your reverse proxy at 127.0.0.1:8080.

Every time you change the env file, run sudo systemctl restart stripewebhook. systemd reads the file shortly before it starts the process, never while it runs.

Step 4: Test Locally With the Stripe CLI

Before touching production, run the handler on your workstation against events from your sandbox. In the first terminal, start forwarding. Current CLI versions require you to choose the events with --events, --all-snapshot or --all-thin whenever you use --forward-to:

Copied!
stripe listen --events checkout.session.completed --forward-to http://127.0.0.1:8080/stripe/webhook
Copied!
> Ready! Your webhook signing secret is whsec_<...> (^C to quit)

In a second terminal, start the handler with that secret. --print-secret prints the same secret and exits, and Stripe says it does not change between restarts of listen. The double quotes here are shell syntax, and the shell removes them before Go sees the value:

Copied!
export STRIPE_WEBHOOK_SECRET="$(stripe listen --print-secret)"
go run .

In a third terminal:

Copied!
stripe trigger checkout.session.completed

The handler logs stripe webhook: queued cs_test_<...>, and the listen terminal shows the delivery with your handler’s status code, which should be 200. Trigger the event your handler acts on. Stripe’s own examples use stripe trigger payment_intent.succeeded, which a handler like this one acknowledges and ignores.

Step 5: Register the Production Endpoint

In the Dashboard, open Workbench, go to the Webhooks tab, choose Create an event destination, select Your account, choose the Snapshot payload format and an API version, select checkout.session.completed, choose Webhook endpoint, and enter https://<YOUR_DOMAIN>/stripe/webhook. Then Reveal secret, put it in /etc/stripewebhook.env, and restart the service. Stripe changes these labels from time to time; if they differ, follow Stripe’s “Receive Stripe events in your webhook endpoint” guide.

Stripe now recommends thin events for new integrations. This handler uses snapshot events because it reads the session from data.object in the payload; both formats are verified from the same three inputs (raw body, header, endpoint secret). Do this separately in the sandbox and in live mode. They are separate endpoints with separate secrets.

Verify

With the production endpoint registered in your sandbox, stripe trigger checkout.session.completed creates real sandbox objects, and Stripe delivers the event to that endpoint as well as to any listen session. Watch the service:

Copied!
sudo journalctl -u stripewebhook -f

You want a queued line. Then open the endpoint in Workbench and check the Event deliveries tab: the delivery should show 200. To test duplicate handling, resend that same event rather than triggering a new one (each stripe trigger creates a new Checkout Session): click Resend on the event in the Dashboard, or run stripe events resend <EVENT_ID> --webhook-endpoint=<ENDPOINT_ID>. The resent delivery should log already fulfilled rather than a second queued line.

Env File Quoting Rules Compared

There is no single env-file format. Each loader has its own rules, and the same line can produce different values. Here is what each one does with a value of abc123:

Loader K='abc123' K="abc123" K=abc123 (trailing spaces) K=abc123 # note $VAR expanded CRLF line ending
systemd EnvironmentFile= quotes removed quotes removed, escapes processed spaces removed # note kept in value no \r removed
Shell, set -a; . ./file quotes removed quotes removed spaces removed comment dropped yes \r kept in value
docker run --env-file quotes kept quotes kept spaces kept # note kept in value no \r removed
Compose env_file: and .env quotes removed, literal quotes removed, escapes and interpolation spaces ignored comment dropped yes, unless single-quoted not documented
Hand-rolled Go loader (bufio.Scanner, strings.Cut(line, "="), os.Setenv) quotes kept quotes kept spaces kept # note kept in value no \r removed

The systemd row comes from the man page and from a test of systemd 255’s parser. The shell row is a test of bash. The Docker CLI row comes from its documentation and parser source, which says quotes are part of the value and whitespace is preserved. The Compose row comes from the Compose file reference. The Go row is the obvious ten-line loader; bufio.Scanner drops the \r before each newline, and everything else stays in the value unless your code strips it.

The practical rule: write env files with no quotes, no inline comments and no trailing whitespace, and they mean the same thing to every loader. If a value really needs spaces, test it with the loader that will read it.

Troubleshooting

  • Every delivery fails and the secret is “definitely right”: usually the right secret for a different endpoint: the stripe listen secret on a server that receives Dashboard deliveries, a sandbox secret against live events, or the old account’s secret after a migration. Compare the last4 in your log with Stripe’s secret hint, a redacted form of the endpoint’s newest active secret that ends in its last four characters in Stripe’s examples. If they differ, you have the wrong secret. If the hint is empty, compare against Reveal secret in the Dashboard.

  • You edited the env file and nothing changed: the process is still running with the old environment. Compare when the service started with when the file changed. If the file is newer, restart.

    Copied!
    systemctl show -p ActiveEnterTimestamp stripewebhook
    sudo stat -c '%y' /etc/stripewebhook.env
  • You need to see what the running process actually has: read its environment from /proc, masking the secret. Quotes, ^M or trailing spaces show up around the masked value:

    Copied!
    PID=$(systemctl show -p MainPID --value stripewebhook)
    sudo cat /proc/$PID/environ | tr '\0' '\n' | grep '^STRIPE_WEBHOOK_SECRET=' | sed -E 's/(whsec_).*(.{4})$/\1****\2/' | cat -A
    Copied!
    STRIPE_WEBHOOK_SECRET=whsec_****AbCd$

    A quoted value would print as STRIPE_WEBHOOK_SECRET='whsec_****bCd'$. Use the same sed mask when you inspect the file itself, so the full secret never lands in your terminal scrollback.

  • systemctl show -p Environment shows nothing: that property lists only Environment= lines from the unit. Values from EnvironmentFile= are read when the process starts and do not appear there. Use /proc/<pid>/environ as above.

  • The CLI test passes but production fails: something between Stripe and your handler changed the body. Compare Stripe’s payload hint with the end of the body sha256 in your log. If they differ, look at your reverse proxy, any web application firewall, and any middleware that decodes and re-encodes JSON. Your code needs the bytes exactly as Stripe sent them.

  • timestamp outside tolerance: the server clock is off. Run timedatectl and confirm System clock synchronized: yes.

  • Old errors that look current: a log line from before your last restart looks exactly like a new one. Filter by time with sudo journalctl -u stripewebhook --since "10 min ago" before you chase it. My connection refused red herring was one of these.

  • Orders fulfilled twice: your idempotency check is missing or is not atomic. Enforce it in the database with a unique constraint on the Checkout Session ID, not with a read-then-write in application code.

One more thing I would do differently: as of this writing, Quartermaster’s handler still reads the body with a plain io.ReadAll and checks only for old timestamps. The version above caps the body and checks both directions, and that is what I would ship today. The systemd man page also warns that environment variables are a poor place for secrets, because they can leak to child processes and through the service manager’s interfaces. It recommends LoadCredential= instead. For a single-purpose service I still find an env file readable only by root acceptable, but that is a judgment call, and the credentials mechanism is the stricter option.

Sources and further reading