Files
Crussell/backend/handlers/webhooks/square.go
T
popertots 54a5b1024e Implement full Square payment review fixes + frontend polish
Implement every finding from the deep payment review (P0-P2, minors,
nitpicks), then close the post-implementation re-review items, then
align card-form typography and roll out the Square trust badge.

Backend - Square API alignment:
- tip_settings.allow_tipping nested under device_options (was top-level:
  terminal tips were silently lost in prod)
- CreateCardOnFile now accepts customerID and sends card.customer_id;
  saved-card (ccof:) charges forward square_customer_id as CustomerID
- New SquareClient methods GetPayment, CreateCustomer, CancelCheckout
- SCA verification_token accepted + forwarded in all charge paths
- ExpMonth/ExpYear -> *int; URL-path id validation; CancelCheckout
  NOT_FOUND-only no-op (dropped unverified NOOP); exported ErrorCode/
  ErrorDetail helpers; mock rejects raw PANs, RList locks, redacts
  emails, ForceRefundPending hook

Backend - money safety:
- sweepManualPendingSquareRefunds reconciles rows WITH square_refund_id
  instead of stranding them forever
- SweepStalePendingPayments reconciles at Square before failing (tri-state:
  leave pending on transport error, rescue completed, fail definitively)
- GetCheckoutStatus cancellation-recheck; terminal CANCELED resolution;
  SweepStaleTerminalCheckouts covers terminal_checkouts table
- till gift-card clawback on definitive failure incl. retry path +
  INSUFFICIENT_FUNDS/ADDRESS_VERIFICATION_FAILURE/TRANSACTION_LIMIT
- cross-user saved-card collision fixed (UNIQUE(user_id,square_card_id))
- customer provisioning (lazy, save-only); one-off/guest mint no customer
- discount preview/apply unified in discounts.go (global-milestone visible
  in preview, N+1 eliminated, redemption counter preserved on failures)
- webhook event_id dedup; refund loop dedup; stale comment fixes
- test-isolation t.Cleanup on committed sweep tests

Frontend:
- SCA tokenizeWithVerification across all charge flows (amount as
  major-units decimal), 5-min token-expiry re-tokenize, verification_token
  in request bodies
- PaymentModal synchronous double-click + zero/negative-amount guards
- till online-card UI wired to /api/admin/till/sale
- policyPopover generalised; new /privacy-policy route; consent checkbox
  copy + Square privacy link
- Square card iframe styled to app typography (Inter 14px, oklch tokens);
  mock form md:text-sm parity
- 'Secure payment powered by Square' badge on all 8 card-payment flows

Schema/docs: terminal_checkouts + square_customer_id + per-user card
constraint in init-script.sql; README migrations; P14 plan + backlog +
Technical Manual updated.

Includes 39 modified/new test files; full backend suite (25 pkgs),
-race on payments+square, and frontend build are green.
2026-08-22 00:34:49 +01:00

155 lines
5.0 KiB
Go

package webhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
"os"
"sync"
)
type SquareWebhookEvent struct {
Type string `json:"type"`
EventID string `json:"event_id"`
CreatedAt string `json:"created_at"`
Data json.RawMessage `json:"data"`
LocationID string `json:"location_id"`
}
// squareWebhookDedup is a bounded, mutex-guarded set of recently handled
// event IDs. Square redelivers signed webhooks on retries (or a replay); once
// the handlers mutate state a duplicate delivery would double-apply, so drop
// replays while keeping the set bounded.
type squareWebhookDedup struct {
mu sync.Mutex
seen map[string]struct{}
order []string
max int
}
func newSquareWebhookDedup(max int) *squareWebhookDedup {
return &squareWebhookDedup{
seen: make(map[string]struct{}),
order: make([]string, 0, max),
max: max,
}
}
// register reports whether id was already handled: false on first occurrence
// (recording id, evicting the oldest once the cap is reached), true on a
// replay (set untouched, preserving insertion order). Mutex-guarded — the
// handler may be hit concurrently.
func (d *squareWebhookDedup) register(id string) bool {
d.mu.Lock()
defer d.mu.Unlock()
if _, ok := d.seen[id]; ok {
return true
}
d.seen[id] = struct{}{}
d.order = append(d.order, id)
if len(d.order) > d.max {
oldest := d.order[0]
d.order = d.order[1:]
delete(d.seen, oldest)
}
return false
}
// 1000 IDs far exceeds Square's redelivery window while capping memory.
var squareWebhookEventsSeen = newSquareWebhookDedup(1000)
func HandleSquareWebhook(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 512*1024)
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Failed to read webhook body: %v", err)
http.Error(w, "request body too large or unreadable", http.StatusRequestEntityTooLarge)
return
}
defer r.Body.Close()
// Verification logic per Square spec (HMAC-SHA256, base64, notificationURL + body).
// Production setup: set SQUARE_WEBHOOK_SIGNATURE_KEY and SQUARE_WEBHOOK_NOTIFICATION_URL
// in env vars (see Square Developer Console → Webhooks → Subscription).
// Reference: https://developer.squareup.com/docs/webhooks/step3validate
// Fail closed: a missing signing key means the webhook cannot be verified,
// so reject rather than process unauthenticated events (S-4). Square
// always sends the signature header, so an unset key in production is a
// misconfiguration that must not silently accept forged events.
signingKey := os.Getenv("SQUARE_WEBHOOK_SIGNATURE_KEY")
notificationURL := os.Getenv("SQUARE_WEBHOOK_NOTIFICATION_URL")
if notificationURL == "" {
notificationURL = "http://localhost:8080/webhooks/square"
}
if signingKey == "" {
log.Printf("SQUARE_WEBHOOK_SIGNATURE_KEY is not set — rejecting webhook (fail-closed)")
http.Error(w, "webhook signature verification unavailable", http.StatusServiceUnavailable)
return
}
signature := r.Header.Get("x-square-hmacsha256-signature")
if signature == "" {
log.Printf("Missing Square webhook signature header")
http.Error(w, "Invalid signature", http.StatusForbidden)
return
}
if !verifySquareSignature(body, signature, signingKey, notificationURL) {
log.Printf("Invalid Square webhook signature")
http.Error(w, "Invalid signature", http.StatusForbidden)
return
}
var event SquareWebhookEvent
if err := json.Unmarshal(body, &event); err != nil {
log.Printf("Failed to parse webhook event: %v", err)
http.Error(w, "Invalid event", http.StatusBadRequest)
return
}
// Dedup BEFORE dispatch: a correctly signed replay of a handled event
// must not re-enter the handlers (which will mutate state once wired).
// Returns 200 to acknowledge delivery without processing.
if event.EventID != "" && squareWebhookEventsSeen.register(event.EventID) {
log.Printf("[SQUARE-WEBHOOK] Duplicate event_id %s; skipping (already processed)", event.EventID)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
return
}
log.Printf("[SQUARE-WEBHOOK] Received event: %s", event.Type)
switch event.Type {
case "payment.updated":
handlePaymentUpdated(event.Data)
case "refund.updated":
handleRefundUpdated(event.Data)
case "dispute.created":
log.Printf("[SQUARE-WEBHOOK] Dispute created: %s", event.EventID)
default:
log.Printf("[SQUARE-WEBHOOK] Unknown event type: %s", event.Type)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
}
func verifySquareSignature(body []byte, signature, signingKey, notificationURL string) bool {
mac := hmac.New(sha256.New, []byte(signingKey))
mac.Write([]byte(notificationURL))
mac.Write(body)
expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(signature), []byte(expected))
}
func handlePaymentUpdated(data json.RawMessage) {
log.Printf("[SQUARE-WEBHOOK] payment.updated: %s", string(data))
}
func handleRefundUpdated(data json.RawMessage) {
log.Printf("[SQUARE-WEBHOOK] refund.updated: %s", string(data))
}