main.go60 lines, 1.9 KB
| 1 | // Command webhook-receiver is the other side of our webhooks: a small server, |
| 2 | // like a merchant would run, that verifies every delivery, and handles each |
| 3 | // event once. |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "encoding/json" |
| 8 | "io" |
| 9 | "log" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/fiston-user/payments/internal/webhook/signature" |
| 16 | ) |
| 17 | |
| 18 | func main() { |
| 19 | secret := os.Getenv("WEBHOOK_SECRET") |
| 20 | if secret == "" { |
| 21 | log.Fatal("WEBHOOK_SECRET is required: the secret you got with your endpoint") |
| 22 | } |
| 23 | // The events we've handled, by ID. In memory, for an example: a real |
| 24 | // receiver keeps them in its database, with a unique key. |
| 25 | var seen sync.Map |
| 26 | |
| 27 | http.HandleFunc("POST /webhooks", func(w http.ResponseWriter, r *http.Request) { |
| 28 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) |
| 29 | if err != nil { |
| 30 | http.Error(w, "body too large", http.StatusRequestEntityTooLarge) |
| 31 | return |
| 32 | } |
| 33 | // First, before decoding anything, or trusting a single byte of it. |
| 34 | if err := signature.Verify(r.Header, secret, body, time.Now()); err != nil { |
| 35 | log.Printf("rejected: %v", err) |
| 36 | http.Error(w, "invalid signature", http.StatusUnauthorized) |
| 37 | return |
| 38 | } |
| 39 | id := r.Header.Get(signature.HeaderID) |
| 40 | if _, dup := seen.LoadOrStore(id, true); dup { |
| 41 | log.Printf("duplicate %s: already handled, skipping", id) |
| 42 | w.WriteHeader(http.StatusNoContent) // a success: don't send it again |
| 43 | return |
| 44 | } |
| 45 | var evt struct { |
| 46 | Type string `json:"type"` |
| 47 | Data struct { |
| 48 | Amount int64 `json:"amount"` |
| 49 | Currency string `json:"currency"` |
| 50 | } `json:"data"` |
| 51 | } |
| 52 | json.Unmarshal(body, &evt) // verified: it's ours, and well formed |
| 53 | log.Printf("verified %s: %s, %d %s", id, evt.Type, evt.Data.Amount, evt.Data.Currency) |
| 54 | w.WriteHeader(http.StatusNoContent) // at once: real work goes to a queue |
| 55 | }) |
| 56 | |
| 57 | log.Print("webhook receiver listening on :8090") |
| 58 | srv := &http.Server{Addr: ":8090", ReadHeaderTimeout: 5 * time.Second} |
| 59 | log.Fatal(srv.ListenAndServe()) |
| 60 | } |