Loop B dup/mod attack findings:
- TillPurchases admin 2FA gate now mirrors PaymentModal and the backend: gateActive = twoFactorEnforced && customerTwoFactorEnabled && paymentMethod='saved_card'; the customer's setup flag is fetched from GET /api/admin/users/{id} on selection. A 2FA-disabled customer in an enforced env no longer hits a dead-end blocked input — the charge 403 surfaces the actionable message via the existing self-heal.
- Extracted twoFAMintThrottled helper shared by SetupTwoFAHandler and ensurePendingTwoFACode — mint-cooldown rule can no longer drift between setup and disable-flow paths
- Notification-helper drift documented: sweep copy states the intentional booking+user scoping vs the canonical webhook copy (cross-referenced); auth refresh_token_reuse insert verified to carry the same NOT EXISTS acknowledged_at IS NULL guard; no import cycle (webhooks→payments one-way)
- Pence convention: 'rounded to the cent' corrected to 'pence' (handlers.go:2726)
26/26 backend packages; 72/72 frontend tests + build; env-docs 41/41.
1410 lines
66 KiB
Go
1410 lines
66 KiB
Go
package webhooks
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"crussell/db"
|
|
"crussell/handlers/payments"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
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. It is a FAST-PATH cache only: the persistent source of truth is
|
|
// the square_webhook_events table (see HandleSquareWebhook). It lets a replayed
|
|
// delivery be dropped without a DB round-trip, but a restart clears it — the DB
|
|
// row is what keeps delivery at-least-once across restarts (a replay after a
|
|
// crash is re-dispatched and absorbed by the idempotent handlers, per the
|
|
// dispatch-first ordering in HandleSquareWebhook).
|
|
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,
|
|
}
|
|
}
|
|
|
|
// has reports whether id is in the set WITHOUT recording it. Used as the
|
|
// fast-path short-circuit before the DB dedup insert.
|
|
func (d *squareWebhookDedup) has(id string) bool {
|
|
d.mu.Lock()
|
|
defer d.mu.Unlock()
|
|
_, ok := d.seen[id]
|
|
return ok
|
|
}
|
|
|
|
// register records id, reporting whether it was already present (set untouched
|
|
// on a replay, preserving insertion order). Mutex-guarded — the handler may be
|
|
// hit concurrently. Called only after the DB insert has confirmed the event's
|
|
// fate, so a failed DB write never leaves a stale entry that would drop a retry.
|
|
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
|
|
}
|
|
|
|
// 500 IDs far exceeds the latency payoff of the fast-path cache; the DB row
|
|
// (square_webhook_events) is the unbounded, restart-safe source of truth.
|
|
var squareWebhookEventsSeen = newSquareWebhookDedup(500)
|
|
|
|
// errWebhookParseFailure marks a dispatch error caused by a KNOWN money event
|
|
// whose payload could not be parsed or extracted (as opposed to a DB failure).
|
|
// HandleSquareWebhook distinguishes it from other dispatch errors to log the
|
|
// failure at ERROR level with the event_id and type — and, like every dispatch
|
|
// error, it returns 5xx WITHOUT committing the dedup row, so Square re-delivers
|
|
// the event instead of the money state being lost forever.
|
|
var errWebhookParseFailure = errors.New("webhook payload parse failure")
|
|
|
|
// isSquareMoneyFamily reports whether an event type belongs to a money-state
|
|
// family (payment.*, refund.*, dispute.*, terminal.*, plus money-adjacent
|
|
// cash_drawer.*, gift_card.*, transaction.* and invoice.*). invoice.* is
|
|
// deliberately included even though this app does not use Square Invoices: an
|
|
// invoice event is money-adjacent (Invoice carries amounts and payment state),
|
|
// so if Square Invoices are ever used the funds must surface as unknown-money
|
|
// and stay retried rather than being acked 200 + dedup'd permanently (M11).
|
|
// Unknown events in these families MUST NOT be 200-acked — see the
|
|
// default-branch split in HandleSquareWebhook.
|
|
func isSquareMoneyFamily(eventType string) bool {
|
|
for _, prefix := range []string{
|
|
"payment.", "refund.", "dispute.", "terminal.",
|
|
"cash_drawer.", "gift_card.", "transaction.", "invoice.",
|
|
} {
|
|
if strings.HasPrefix(eventType, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// isSquareNonMoneyFamily reports whether an event type belongs to a known
|
|
// non-money family this app will never process (customer.*, card.*, order.*,
|
|
// booking.* and the other Square families below, none of which carry money
|
|
// state this app tracks). These are deliberately acked 200 WITH a dedup row so
|
|
// Square stops retrying them — see the default-branch split in
|
|
// HandleSquareWebhook.
|
|
func isSquareNonMoneyFamily(eventType string) bool {
|
|
for _, prefix := range []string{
|
|
"customer.", "card.", "order.", "booking.",
|
|
"appointment.", "availability.", "loyalty.", "merchant.",
|
|
"location.", "labor.", "inventory.", "site.", "device.",
|
|
"team_member.", "subscription.", "webhook.",
|
|
} {
|
|
if strings.HasPrefix(eventType, prefix) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// webhookDBTimeout bounds the DB work performed while dispatching a webhook.
|
|
// The work runs on a Background-derived context — so a client disconnect cannot
|
|
// cancel it (the at-least-once delivery contract must survive) — but is
|
|
// timeout-bound so a hung DB call cannot hold a pgx pool connection forever;
|
|
// repeated hangs would otherwise exhaust the pool. 30s is the same
|
|
// post-request DB budget used elsewhere in the backend (handlers/user).
|
|
const webhookDBTimeout = 30 * time.Second
|
|
|
|
// webhookDBContext returns a timeout-bound, Background-derived context for
|
|
// webhook dispatch DB work.
|
|
func webhookDBContext() (context.Context, context.CancelFunc) {
|
|
return context.WithTimeout(context.Background(), webhookDBTimeout)
|
|
}
|
|
|
|
// squareEnvironmentMismatch reports whether the webhook's square-environment
|
|
// header conflicts with the deployment's configured SQUARE_ENVIRONMENT.
|
|
//
|
|
// The check is enforced for every non-dev/mock deployment: configured
|
|
// production and sandbox are compared directly, and an EMPTY or UNKNOWN
|
|
// configured SQUARE_ENVIRONMENT is treated as PRODUCTION (LOW-4) — matching how
|
|
// the rest of the backend treats empty/unknown env fail-closed (main.go:214
|
|
// and payments twofa.go:40-42) — so a sandbox subscription mis-pointed at an
|
|
// unconfigured production URL cannot process sandbox events against production
|
|
// state. In dev/mock deployments the header is informational and a mismatch is
|
|
// not rejectable; the dev/mock determination delegates to the shared
|
|
// payments.IsExplicitDevOrMockEnv (handlers/payments/twofa.go) rather than
|
|
// re-implementing the env-value list, so this check and the 2FA gate can never
|
|
// diverge on what counts as the dev/mock stack.
|
|
//
|
|
// An absent header is allowed through: real Square deliveries always send it,
|
|
// so a missing header in an enforced deployment is a non-Square client (which
|
|
// already failed signature verification) or a local mock/dev poster — both
|
|
// safely handled downstream. Rejection is 403. NOTE: Square retries ANY
|
|
// non-2xx response (4xx included) with exponential backoff for up to ~24h, so
|
|
// the 403 does not by itself stop the retry loop — but a square-environment
|
|
// mismatch is a PERMANENT configuration error that no retry can resolve, the
|
|
// handler is intentionally fail-closed (every replay is rejected identically
|
|
// before any state change), and the DB-level dedup (square_webhook_events +
|
|
// ON CONFLICT) makes the replayed deliveries replay-safe. The 403 forces the
|
|
// operator to fix the subscription or the environment setting.
|
|
func squareEnvironmentMismatch(headerEnv string) bool {
|
|
headerEnv = strings.ToLower(strings.TrimSpace(headerEnv))
|
|
if headerEnv == "" {
|
|
return false
|
|
}
|
|
// Dev/mock deployments (mock/dev/development/test) are never enforced —
|
|
// the shared predicate is the single source of truth for that
|
|
// classification, so the webhook's interpretation matches the 2FA gate
|
|
// exactly (handlers/payments/twofa.go:IsExplicitDevOrMockEnv).
|
|
if payments.IsExplicitDevOrMockEnv() {
|
|
return false
|
|
}
|
|
configured := strings.ToLower(strings.TrimSpace(os.Getenv("SQUARE_ENVIRONMENT")))
|
|
if configured != "sandbox" {
|
|
// Empty/unknown configured environment is treated as PRODUCTION for the
|
|
// env check (LOW-4), matching the fail-closed production default the
|
|
// rest of the backend applies to empty/unknown SQUARE_ENVIRONMENT.
|
|
configured = "production"
|
|
}
|
|
return headerEnv != configured
|
|
}
|
|
|
|
// HandleSquareWebhook verifies and dispatches Square webhook events.
|
|
//
|
|
// Fail-closed chain: 503 when the signing key is unset, 403 on a missing/bad
|
|
// signature, 400 on malformed JSON or an empty event_id (which cannot be
|
|
// deduplicated — Square always sends one, so this is defensive). A correctly
|
|
// signed, well-formed event is deduplicated by event_id before dispatch and
|
|
// acknowledged 200. Unknown event types are split by family: money-state
|
|
// families (payment.*, refund.*, dispute.*, terminal.* and money-adjacent
|
|
// prefixes including invoice.*) and truly unknown prefixes get 501 (Square
|
|
// retries, no dedup row), while known non-money families (customer.*, card.*,
|
|
// order.*, booking.*, ...) are acked 200 WITH the dedup row so the subscription
|
|
// is never flooded into suspension.
|
|
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
|
|
}
|
|
|
|
// Fail-closed environment check: a sandbox subscription mis-pointed at the
|
|
// production URL + key would otherwise process sandbox events against
|
|
// production state. 403 is correct because a square-environment mismatch is
|
|
// a permanent config error no retry can fix — note that Square retries ANY
|
|
// non-2xx (4xx included) for up to ~24h, so the 403 does not stop the retry
|
|
// loop by itself; the handler rejects every replay identically (fail-closed,
|
|
// before any state change) and the DB-level dedup (square_webhook_events +
|
|
// ON CONFLICT) makes the replayed deliveries replay-safe. See
|
|
// squareEnvironmentMismatch for the exact enforcement conditions.
|
|
if squareEnvironmentMismatch(r.Header.Get("square-environment")) {
|
|
log.Printf("[SQUARE-WEBHOOK] Rejecting event: square-environment header %q does not match configured SQUARE_ENVIRONMENT %q (403)",
|
|
r.Header.Get("square-environment"), os.Getenv("SQUARE_ENVIRONMENT"))
|
|
http.Error(w, "square environment mismatch", 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
|
|
}
|
|
|
|
// An empty event_id cannot be deduplicated. Square always sends event_id,
|
|
// so this is defensive — but once handlers mutate state, a duplicate
|
|
// empty-ID event would double-apply. Reject with 400 (fail-safe, no
|
|
// dispatch, no dedup row). NOTE: Square retries ANY non-2xx response (4xx
|
|
// included) with exponential backoff for up to ~24h, so the 400 does NOT by
|
|
// itself stop the retry loop — but the handler is fail-closed: every replay
|
|
// is rejected identically BEFORE any state change or dedup insert, so no
|
|
// side effect can ever be applied, and the DB-level dedup
|
|
// (square_webhook_events + ON CONFLICT) keeps the repeated deliveries
|
|
// replay-safe.
|
|
if event.EventID == "" {
|
|
log.Printf("[SQUARE-WEBHOOK] Rejecting event with empty event_id (400)")
|
|
http.Error(w, "Invalid event", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Fast-path dedup: a correctly signed replay of a recently handled event is
|
|
// dropped in memory without a DB round-trip. The persistent source of truth
|
|
// is the square_webhook_events row committed AFTER dispatch below, so this
|
|
// cache never hides an event whose dedup row is not yet persisted — a crash
|
|
// before that commit simply replays the event, which the idempotent handlers
|
|
// absorb.
|
|
if squareWebhookEventsSeen.has(event.EventID) {
|
|
log.Printf("[SQUARE-WEBHOOK] Duplicate event_id %s; skipping (already processed)", event.EventID)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
return
|
|
}
|
|
if db.Conn == nil {
|
|
log.Printf("[SQUARE-WEBHOOK] DB unavailable — rejecting event_id %s (fail-closed)", event.EventID)
|
|
http.Error(w, "webhook processing unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
|
|
log.Printf("[SQUARE-WEBHOOK] Received event: %s", event.Type)
|
|
|
|
// Dispatch FIRST, then commit the dedup row. The handlers mutate state, so a
|
|
// dedup row committed before dispatch would permanently drop the event on a
|
|
// crash between the insert and the dispatch (Square's retry would be
|
|
// 200-skipped, and dispute.created has no sweep fallback). Committing after
|
|
// a successful dispatch keeps delivery at-least-once: on any dispatch error
|
|
// NO dedup row is written and we return 5xx so Square retries. The handlers
|
|
// are idempotent (status='pending'-guarded UPDATEs keyed on the Square id),
|
|
// so a retry — or two retries dispatching concurrently — applies each state
|
|
// change at most once and is otherwise a no-op.
|
|
var dispatchErr error
|
|
switch event.Type {
|
|
// Square fires payment.completed and payment.canceled as SEPARATE event
|
|
// types from payment.updated, but all of them carry the same full Payment
|
|
// object in data.object.payment, and handlePaymentUpdated reconciles purely
|
|
// from the payload's id/status (squarePaymentStatusToLocal maps COMPLETED/
|
|
// CANCELED/FAILED). Routing all four here closes the silent gap where a
|
|
// completed or canceled charge was previously acked 200 and never
|
|
// reconciled against the local pending row.
|
|
case "payment.updated", "payment.created", "payment.completed", "payment.canceled":
|
|
dispatchErr = handlePaymentUpdated(event.Data)
|
|
// Same reasoning for refunds: refund.completed/refund.canceled are distinct
|
|
// event types carrying the full PaymentRefund object in data.object.refund,
|
|
// which handleRefundUpdated reconciles by status.
|
|
case "refund.updated", "refund.created", "refund.completed", "refund.canceled":
|
|
dispatchErr = handleRefundUpdated(event.Data)
|
|
case "dispute.created":
|
|
dispatchErr = handleDisputeCreated(event.Data)
|
|
case "dispute.state.updated":
|
|
dispatchErr = handleDisputeStateUpdated(event.Data)
|
|
case "dispute.evidence.created", "dispute.evidence.deleted":
|
|
dispatchErr = handleDisputeEvidence(event.Data)
|
|
case "terminal.checkout.created", "terminal.checkout.updated":
|
|
dispatchErr = handleTerminalCheckout(event.Data)
|
|
default:
|
|
// Unknown-type handling is SPLIT by event family so Square's retry
|
|
// policy (it re-delivers 5xx responses) can never flood the
|
|
// subscription into suspension — a suspended subscription silently
|
|
// kills money-event delivery (payment.created/updated).
|
|
//
|
|
// • MONEY-STATE families (any payment.*, refund.*, dispute.*,
|
|
// terminal.*, cash_drawer.*, gift_card.*, transaction.*, invoice.*
|
|
// not explicitly handled above, plus future money-adjacent
|
|
// prefixes): keep 501 so Square retries. A money event this app does
|
|
// not yet handle is NEVER a safe 200-ack (the caller would commit the
|
|
// dedup row and the event would be dropped forever); no dedup row is
|
|
// written and a later retry re-dispatches idempotently if code
|
|
// support for the type lands before the retry window closes.
|
|
// invoice.* is treated as money-adjacent even though Square Invoices
|
|
// are unused today: an invoice carries amounts and payment state, so
|
|
// acked invoice funds would be invisible to the app (M11).
|
|
// • KNOWN NON-MONEY families (customer.*, card.*, order.*,
|
|
// booking.* — plus appointment.*, availability.*, loyalty.*,
|
|
// merchant.*, location.*, labor.*, inventory.*, site.*, device.*,
|
|
// team_member.*, subscription.*, webhook.* — and anything else
|
|
// Square can emit that this app will never process): deliberately
|
|
// acked 200 WITH the dedup row committed so Square stops retrying.
|
|
// They carry no money state this app tracks, so acking loses
|
|
// nothing — and retrying them at any regularity would fill the
|
|
// subscription's retry queue until Square suspends it, silently
|
|
// killing money-event delivery. Logged at WARN.
|
|
// • TRULY unknown prefixes (matching neither list): conservative
|
|
// 501 — the type could be a new money family Square just added.
|
|
switch {
|
|
case isSquareMoneyFamily(event.Type):
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: unhandled money-family Square event type %q (event_id=%s) — not acknowledged; returning 501 so Square retries", event.Type, event.EventID)
|
|
// A19: raise the operator-facing admin notification BEFORE the 501.
|
|
// Without it the event is retried by Square for ~24h and then
|
|
// silently dropped with only a log line. The notification is a
|
|
// SEPARATE table — no square_webhook_events dedup row is written
|
|
// here, so Square keeps retrying the event exactly as before.
|
|
notifCtx, notifCancel := webhookDBContext()
|
|
insertUnknownEventNotification(notifCtx, event.Type, event.EventID)
|
|
notifCancel()
|
|
http.Error(w, "unhandled webhook event type", http.StatusNotImplemented)
|
|
return
|
|
case isSquareNonMoneyFamily(event.Type):
|
|
log.Printf("[SQUARE-WEBHOOK] WARNING: acknowledged unhandled non-money event %q (event_id=%s) — committed dedup row; Square stops retrying", event.Type, event.EventID)
|
|
default:
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: unhandled Square event type %q (event_id=%s) — not acknowledged; returning 501 so Square retries", event.Type, event.EventID)
|
|
notifCtx, notifCancel := webhookDBContext()
|
|
insertUnknownEventNotification(notifCtx, event.Type, event.EventID)
|
|
notifCancel()
|
|
http.Error(w, "unhandled webhook event type", http.StatusNotImplemented)
|
|
return
|
|
}
|
|
}
|
|
if dispatchErr != nil {
|
|
// A parse failure on a known money event is logged at ERROR with the
|
|
// event_id and type so operators can see exactly which delivery was
|
|
// unparseable and is being retried (rather than silently lost). Every
|
|
// dispatch error — parse failure or DB failure — returns 5xx WITHOUT
|
|
// committing the dedup row, so Square re-delivers the event.
|
|
if errors.Is(dispatchErr, errWebhookParseFailure) {
|
|
log.Printf("[SQUARE-WEBHOOK] ERROR: known money event %s (event_id=%s) payload failed to parse: %v — NOT recording dedup row; Square will retry", event.Type, event.EventID, dispatchErr)
|
|
} else {
|
|
log.Printf("[SQUARE-WEBHOOK] Event %s (%s) dispatch failed: %v — NOT recording dedup row; Square will retry", event.Type, event.EventID, dispatchErr)
|
|
}
|
|
http.Error(w, "webhook processing failed", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
|
|
// Commit the dedup row AFTER successful dispatch. Fail closed on a write
|
|
// error: without a persisted row we cannot prove the event was handled, so
|
|
// reject and let Square retry (the retry re-dispatches idempotently and
|
|
// retries the insert). event_id is not PII, so logging it is safe.
|
|
// Commit the dedup row AFTER successful dispatch. Fail closed on a write
|
|
// error: without a persisted row we cannot prove the event was handled, so
|
|
// reject and let Square retry (the retry re-dispatches idempotently and
|
|
// retries the insert). event_id is not PII, so logging it is safe. A
|
|
// bounded Background context keeps this post-dispatch write alive across a
|
|
// client disconnect without letting a hung insert hold the pool forever.
|
|
dedupCtx, dedupCancel := webhookDBContext()
|
|
defer dedupCancel()
|
|
tag, err := db.Conn.Exec(dedupCtx,
|
|
"INSERT INTO square_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING", event.EventID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to record event_id %s (dedup write failed): %v", event.EventID, err)
|
|
http.Error(w, "webhook processing unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
// Record in the fast-path cache only after the DB write succeeds, so a
|
|
// failed write never leaves a stale entry that would drop a retry.
|
|
squareWebhookEventsSeen.register(event.EventID)
|
|
if tag.RowsAffected() == 0 {
|
|
// A concurrent duplicate delivery already committed this event's row.
|
|
log.Printf("[SQUARE-WEBHOOK] Duplicate event_id %s; acknowledging (already processed)", event.EventID)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
return
|
|
}
|
|
|
|
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))
|
|
}
|
|
|
|
// squareWebhookData is the `data` envelope of a Square webhook v1 event. The
|
|
// affected object's id is at data.id; the full resource is nested at
|
|
// data.object.<type> (e.g. data.object.payment). Only the id is logged — the
|
|
// nested object can contain PII and is never echoed to the log.
|
|
type squareWebhookData struct {
|
|
ID string `json:"id"`
|
|
Type string `json:"type"`
|
|
Object json.RawMessage `json:"object"`
|
|
}
|
|
|
|
// squareDisputePayload maps the Square Dispute fields this app records.
|
|
// Reference: https://developer.squareup.com/reference/square/objects/Dispute
|
|
type squareDisputePayload struct {
|
|
ID string `json:"id"`
|
|
State string `json:"state"`
|
|
AmountMoney *squareMoneyPayload `json:"amount_money"`
|
|
Reason string `json:"reason"`
|
|
DisputedPayment *squareDisputedPaymentField `json:"disputed_payment"`
|
|
}
|
|
|
|
type squareMoneyPayload struct {
|
|
Amount int64 `json:"amount"` // minor units (pence for GBP)
|
|
Currency string `json:"currency"`
|
|
}
|
|
|
|
type squareDisputedPaymentField struct {
|
|
PaymentID string `json:"payment_id"`
|
|
}
|
|
|
|
// squarePaymentPayload maps the Square Payment fields this app consumes.
|
|
type squarePaymentPayload struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"` // "APPROVED", "COMPLETED", "CANCELED", "FAILED", "PENDING"
|
|
// ReferenceID / IdempotencyKey / AmountMoney feed the B1-support orphan
|
|
// detection (detectOrphanedReplayCharge): Square's Payment object carries
|
|
// them, and a sweep-minted duplicate charge preserves the origin row's
|
|
// idempotency key / reference_id / amount (the sweep replays the stored
|
|
// request verbatim).
|
|
ReferenceID string `json:"reference_id"`
|
|
IdempotencyKey string `json:"idempotency_key"`
|
|
AmountMoney *squareMoneyPayload `json:"amount_money"`
|
|
}
|
|
|
|
// squareRefundPayload maps the Square Refund (PaymentRefund) fields this app
|
|
// consumes.
|
|
type squareRefundPayload struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"` // "PENDING", "COMPLETED", "FAILED"
|
|
}
|
|
|
|
// parseSquareObject unmarshals data.object.<type> into out. Returns false when
|
|
// the nested resource is absent (legacy envelope carrying only data.id).
|
|
func parseSquareObject(object json.RawMessage, key string, out any) bool {
|
|
if len(object) == 0 {
|
|
return false
|
|
}
|
|
var wrapper map[string]json.RawMessage
|
|
if err := json.Unmarshal(object, &wrapper); err != nil {
|
|
return false
|
|
}
|
|
raw, ok := wrapper[key]
|
|
if !ok || len(raw) == 0 {
|
|
return false
|
|
}
|
|
if err := json.Unmarshal(raw, out); err != nil {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// squareMoneyToAmount converts a Square Money object (minor units) to an exact
|
|
// two-decimal string for the NUMERIC(10,2) columns. String formatting avoids
|
|
// float64 rounding artifacts for money.
|
|
func squareMoneyToAmount(m *squareMoneyPayload) string {
|
|
if m == nil || m.Amount <= 0 {
|
|
return "0.00"
|
|
}
|
|
return fmt.Sprintf("%d.%02d", m.Amount/100, m.Amount%100)
|
|
}
|
|
|
|
// squarePaymentStatusToLocal maps Square's payment state machine to the local
|
|
// payment_status enum. APPROVED/PENDING are NON-terminal (Square may still
|
|
// complete or void them), so they map to a zero local status and the caller
|
|
// leaves the row untouched — the same classification the stale-pending sweeps
|
|
// use (handlers/payments/sweep.go).
|
|
func squarePaymentStatusToLocal(status string) (string, bool) {
|
|
switch status {
|
|
case "COMPLETED":
|
|
return "completed", true
|
|
case "CANCELED", "FAILED":
|
|
return "failed", true
|
|
case "APPROVED", "PENDING":
|
|
return "", false
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// squareRefundStatusToLocal maps Square's refund status to the local
|
|
// payment_status enum. Square's PaymentRefund states are PENDING, APPROVED,
|
|
// COMPLETED, CANCELED, FAILED and REJECTED (developer.squareup.com/reference/
|
|
// square/objects/PaymentRefund). COMPLETED/FAILED/REJECTED are TERMINAL —
|
|
// REJECTED (Square declined the refund) is a definitive failure and must be
|
|
// surfaced as local 'failed' instead of leaving the row pending until the slow
|
|
// sweep; PENDING and APPROVED are NON-terminal (the refund may still complete
|
|
// or be rejected) and map to a zero local status so the caller leaves the row
|
|
// untouched.
|
|
func squareRefundStatusToLocal(status string) (string, bool) {
|
|
switch status {
|
|
case "COMPLETED":
|
|
return "completed", true
|
|
case "FAILED", "REJECTED":
|
|
return "failed", true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// squareDisputeStateToLocal maps Square's dispute state to the local
|
|
// disputes.status. Only the terminal resolutions move the row to won/lost;
|
|
// ACCEPTED (seller accepted the dispute) is a loss — the money is gone.
|
|
// Everything else (inquiries, evidence required, processing) stays open.
|
|
func squareDisputeStateToLocal(state string) string {
|
|
switch state {
|
|
case "WON":
|
|
return "won"
|
|
case "LOST", "ACCEPTED":
|
|
return "lost"
|
|
default:
|
|
return "open"
|
|
}
|
|
}
|
|
|
|
// findPaymentBySquareID resolves the local payment id and booking id for a
|
|
// Square payment id. Multiple local rows can share one Square charge id (e.g.
|
|
// a deposit + balance split); the most recent is used. The caller supplies a
|
|
// bounded context (webhookDBContext) so this post-dispatch DB work survives a
|
|
// client disconnect without holding a pool connection forever.
|
|
func findPaymentBySquareID(ctx context.Context, squarePaymentID string) (paymentID, bookingID string, ok bool) {
|
|
if squarePaymentID == "" {
|
|
return "", "", false
|
|
}
|
|
var pid string
|
|
var bid *string
|
|
err := db.Conn.QueryRow(ctx, `
|
|
SELECT id, booking_id FROM payments
|
|
WHERE square_payment_id = $1
|
|
ORDER BY created_at DESC, id DESC
|
|
LIMIT 1
|
|
`, squarePaymentID).Scan(&pid, &bid)
|
|
if err != nil {
|
|
return "", "", false
|
|
}
|
|
if bid != nil {
|
|
bookingID = *bid
|
|
}
|
|
return pid, bookingID, true
|
|
}
|
|
|
|
// findPaymentByDisputeID resolves the local payment (and its booking) recorded
|
|
// for a dispute row. Used by dispute.state.updated when the dispute row already
|
|
// exists but the webhook payload carries no resolvable Square payment id. The
|
|
// caller supplies a bounded context (webhookDBContext).
|
|
func findPaymentByDisputeID(ctx context.Context, squareDisputeID string) (paymentID, bookingID string) {
|
|
var pid string
|
|
var bid *string
|
|
err := db.Conn.QueryRow(ctx, `
|
|
SELECT d.payment_id, p.booking_id
|
|
FROM disputes d
|
|
JOIN payments p ON p.id = d.payment_id
|
|
WHERE d.square_dispute_id = $1
|
|
`, squareDisputeID).Scan(&pid, &bid)
|
|
if err != nil {
|
|
return "", ""
|
|
}
|
|
if bid != nil {
|
|
bookingID = *bid
|
|
}
|
|
return pid, bookingID
|
|
}
|
|
|
|
// disputeNotificationID derives the deterministic admin_notifications id for an
|
|
// untracked dispute's critical_payment_log notification: 'D' + 11 lowercase hex
|
|
// chars of a SHA-256 over 'dispute-<square_dispute_id>'. generate_short_id
|
|
// (init-script.sql) only ever emits 12 lowercase hex chars
|
|
// (substr(encode(gen_random_bytes(6),'hex'),1,12)), so the uppercase 'D' prefix
|
|
// guarantees this can never collide with a DB-generated id. The id is stable
|
|
// per dispute, giving ON CONFLICT (id) DO NOTHING per-dispute idempotency.
|
|
func disputeNotificationID(squareDisputeID string) string {
|
|
sum := sha256.Sum256([]byte("dispute-" + squareDisputeID))
|
|
return "D" + hex.EncodeToString(sum[:])[:11]
|
|
}
|
|
|
|
// insertCriticalPaymentNotification surfaces a money event in the admin
|
|
// notification centre (reason='critical_payment_log'), the DB-backed stand-in
|
|
// for un-watched CRITICAL log lines (see ScanCriticalPaymentLogs in
|
|
// internal/jobs/cleanup.go). Dedup: one unacknowledged row per (reason,
|
|
// booking_id) — acknowledging re-arms it.
|
|
//
|
|
// NOTE: this is the WEBHOOK-specific variant of a same-named helper in the
|
|
// payments package (handlers/payments/sweep.go, insertCriticalPaymentNotification)
|
|
// with DIFFERENT semantics: that one has the signature (ctx, bookingID,
|
|
// userID *string), writes the user_id column, and dedups on (reason,
|
|
// booking_id, user_id); this one takes (ctx, bookingID, disputeID string),
|
|
// never writes user_id, and dedups on (reason, booking_id) or the
|
|
// deterministic per-dispute id. They share the admin_notifications table and
|
|
// the 'critical_payment_log' reason but serve different call paths (sweep vs
|
|
// webhook) — do not merge them.
|
|
//
|
|
// AUTHORITATIVE NOT EXISTS GUARD: the booking-scoped branch below is the
|
|
// canonical form of this dedup — `an.reason = 'critical_payment_log' AND
|
|
// an.booking_id IS NOT DISTINCT FROM $1 AND an.acknowledged_at IS NULL` (a
|
|
// notification blocks a re-notify until the admin acknowledges it, then a NEW
|
|
// event re-arms). sweep.go's insertCriticalPaymentNotification mirrors this
|
|
// predicate in shape (its copy applies the same NOT EXISTS/acknowledged_at
|
|
// IS NULL guard over (reason, booking_id, user_id) — an intentional
|
|
// user-scoping addition for sweep-originated events, documented on the sweep
|
|
// copy itself); if the guard ever changes, sweep.go must be updated to match.
|
|
//
|
|
// Untracked disputes (no local payment row, booking_id NULL) pass disputeID
|
|
// instead: each DISTINCT square dispute gets its OWN notification under the
|
|
// deterministic id (disputeNotificationID), so a second distinct chargeback is
|
|
// never suppressed by the first's (reason, NULL booking) row — and re-delivery
|
|
// of the same dispute is a no-op (ON CONFLICT (id) DO NOTHING). The
|
|
// booking-scoped NOT EXISTS guard does NOT apply to this path: it would
|
|
// collapse every untracked dispute onto one unacknowledged NULL-booking row.
|
|
// The caller supplies a bounded context (webhookDBContext).
|
|
func insertCriticalPaymentNotification(ctx context.Context, bookingID, disputeID string) {
|
|
if disputeID != "" {
|
|
id := disputeNotificationID(disputeID)
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO admin_notifications (id, reason, booking_id, created_at)
|
|
VALUES ($1, 'critical_payment_log'::admin_notification_reason, NULL, NOW())
|
|
ON CONFLICT (id) DO NOTHING
|
|
`, id)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to insert critical_payment_log admin notification: %v", err)
|
|
return
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] Inserted critical_payment_log admin notification (dispute_id=%s, booking_id=NULL)", disputeID)
|
|
}
|
|
return
|
|
}
|
|
var bid any
|
|
if bookingID != "" {
|
|
bid = bookingID
|
|
}
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO admin_notifications (reason, booking_id, created_at)
|
|
SELECT 'critical_payment_log'::admin_notification_reason, $1, NOW()
|
|
WHERE NOT EXISTS (
|
|
SELECT 1 FROM admin_notifications an
|
|
WHERE an.reason = 'critical_payment_log'
|
|
AND an.booking_id IS NOT DISTINCT FROM $1
|
|
AND an.acknowledged_at IS NULL
|
|
)
|
|
`, bid)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to insert critical_payment_log admin notification: %v", err)
|
|
return
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] Inserted critical_payment_log admin notification (booking_id=%s)", bookingID)
|
|
}
|
|
}
|
|
|
|
// unknownEventNotificationID derives the deterministic admin_notifications id
|
|
// for an unhandled money-family/truly-unknown webhook event's
|
|
// critical_payment_log notification: 'U' + 11 lowercase hex chars of a SHA-256
|
|
// over 'unknown-event-<event_id>'. Mirrors disputeNotificationID (which uses an
|
|
// uppercase 'D' prefix): the two are intentionally parallel — same
|
|
// prefix + hex(sha256(input))[:11] scheme (44 bits), DIFFERENT prefixes, so a
|
|
// dispute id and an unknown-event id can never collide even on identical hash
|
|
// input. generate_*_id (init-script.sql) only ever emits 12
|
|
// lowercase hex chars, so the uppercase 'U' prefix guarantees no collision with
|
|
// a DB-generated id. The id is stable per event_id, giving
|
|
// ON CONFLICT (id) DO NOTHING per-event idempotency across redeliveries.
|
|
func unknownEventNotificationID(eventID string) string {
|
|
sum := sha256.Sum256([]byte("unknown-event-" + eventID))
|
|
return "U" + hex.EncodeToString(sum[:])[:11]
|
|
}
|
|
|
|
// insertUnknownEventNotification raises a critical_payment_log admin
|
|
// notification for a money-family/truly-unknown webhook event the handler
|
|
// refuses to ack (501). Without it the event is retried by Square for ~24h and
|
|
// then silently dropped with only a log line. The notification is deduped by
|
|
// its deterministic id (unknownEventNotificationID) and lives in a SEPARATE
|
|
// table — no square_webhook_events dedup row is written on the 501 path, so
|
|
// Square keeps retrying the event exactly as before. Best-effort: an insert
|
|
// failure is logged, never a dispatch error (the 501 is already the response).
|
|
// The caller supplies a bounded context (webhookDBContext).
|
|
func insertUnknownEventNotification(ctx context.Context, eventType, eventID string) {
|
|
id := unknownEventNotificationID(eventID)
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO admin_notifications (id, reason, booking_id, created_at)
|
|
VALUES ($1, 'critical_payment_log'::admin_notification_reason, NULL, NOW())
|
|
ON CONFLICT (id) DO NOTHING
|
|
`, id)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to insert critical_payment_log admin notification for unhandled event %q (event_id=%s): %v", eventType, eventID, err)
|
|
return
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] Inserted critical_payment_log admin notification for unhandled event type %q (event_id=%s)", eventType, eventID)
|
|
}
|
|
}
|
|
|
|
// markPaymentFailed flips a payment to 'failed' after a lost dispute — the
|
|
// money was charged back, so the row must not read as collected. 'refunded'
|
|
// rows are left alone (the money was returned by refund, not charged back).
|
|
// The caller supplies a bounded context (webhookDBContext).
|
|
func markPaymentFailed(ctx context.Context, paymentID string) error {
|
|
if paymentID == "" {
|
|
return nil
|
|
}
|
|
_, err := db.Conn.Exec(ctx,
|
|
"UPDATE payments SET status = 'failed', updated_at = NOW() WHERE id = $1 AND status IN ('pending', 'completed')",
|
|
paymentID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to mark payment %s failed after lost dispute: %v", paymentID, err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// squarePaymentKnown reports whether ANY local payments row carries the Square
|
|
// payment id, whatever its status. The pending-only UPDATE in
|
|
// handlePaymentUpdated matches zero rows both when no row exists at all and
|
|
// when the row already settled (e.g. a completed webhook replay of an
|
|
// already-'completed' charge). This existence check distinguishes those two:
|
|
// a row existing means the event is a plain no-op replay of a known charge,
|
|
// while no row at all is the signature of an ORPHANED sweep-minted duplicate.
|
|
// Unlike findPaymentBySquareID (which swallows errors), a DB failure here
|
|
// propagates so the caller rejects the event and Square retries.
|
|
func squarePaymentKnown(ctx context.Context, squarePaymentID string) (bool, error) {
|
|
var one int
|
|
err := db.Conn.QueryRow(ctx,
|
|
`SELECT 1 FROM payments WHERE square_payment_id = $1 LIMIT 1`, squarePaymentID).Scan(&one)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// findPendingByOrphanKeys locates the pending ORIGIN row of a likely
|
|
// sweep-minted duplicate charge: the pending row that shares the replayed
|
|
// charge's idempotency key (primary — exact, because Square returns the key on
|
|
// the Payment object and payments.idempotency_key is UNIQUE) or, failing that,
|
|
// the pending row whose booking/gift-card reference AND amount match the
|
|
// payload's reference_id/amount_money (the sweep replays the stored snapshot
|
|
// verbatim, preserving both). Only 'pending' rows WITHOUT a square_payment_id
|
|
// are candidates — that is exactly the population the keyed stale-pending sweep
|
|
// replays (sweep.go), so a match is the sweep-minted duplicate's origin.
|
|
func findPendingByOrphanKeys(ctx context.Context, payment squarePaymentPayload) (paymentID, bookingID string, found bool, err error) {
|
|
if payment.IdempotencyKey != "" {
|
|
var pid string
|
|
var bid *string
|
|
err := db.Conn.QueryRow(ctx, `
|
|
SELECT id, booking_id FROM payments
|
|
WHERE status = 'pending' AND idempotency_key = $1 AND square_payment_id IS NULL
|
|
ORDER BY created_at DESC, id DESC
|
|
LIMIT 1
|
|
`, payment.IdempotencyKey).Scan(&pid, &bid)
|
|
if err == nil {
|
|
if bid != nil {
|
|
bookingID = *bid
|
|
}
|
|
return pid, bookingID, true, nil
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
return "", "", false, err
|
|
}
|
|
}
|
|
// reference_id fallback: booking charges carry the booking id as
|
|
// reference_id; a gift-card-linked payment carries the card code. The
|
|
// amount guard stops a coincidental reference match (a pending row for the
|
|
// same booking at a different amount) from being mistaken for the origin.
|
|
if payment.ReferenceID != "" && payment.AmountMoney != nil && payment.AmountMoney.Amount > 0 {
|
|
amount := float64(payment.AmountMoney.Amount) / 100.0
|
|
var pid string
|
|
var bid *string
|
|
err := db.Conn.QueryRow(ctx, `
|
|
SELECT id, booking_id FROM payments
|
|
WHERE status = 'pending' AND square_payment_id IS NULL
|
|
AND ABS(amount - $2) < 0.005
|
|
AND (booking_id = $1 OR gift_card_id = $1)
|
|
ORDER BY created_at DESC, id DESC
|
|
LIMIT 1
|
|
`, payment.ReferenceID, amount).Scan(&pid, &bid)
|
|
if err == nil {
|
|
if bid != nil {
|
|
bookingID = *bid
|
|
}
|
|
return pid, bookingID, true, nil
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
return "", "", false, err
|
|
}
|
|
}
|
|
return "", "", false, nil
|
|
}
|
|
|
|
// orphanReplayChargeNotificationID derives the deterministic admin_notifications
|
|
// id for an orphaned sweep-minted duplicate charge's critical_payment_log
|
|
// notification: 'O' + 11 lowercase hex chars of a SHA-256 over
|
|
// 'orphan-replay-<payment_id>'. Mirrors disputeNotificationID ('D') and
|
|
// unknownEventNotificationID ('U'): same prefix + hex(sha256(input))[:11]
|
|
// scheme with a distinct uppercase prefix, so the three id spaces can never
|
|
// collide and the uppercase prefix guarantees no collision with a DB-generated
|
|
// id (generate_*_id emits 12 lowercase hex chars). The id is stable per ORIGIN
|
|
// payment row, so ON CONFLICT (id) DO NOTHING keeps re-deliveries and
|
|
// re-notifications of the same orphan charge to one row.
|
|
func orphanReplayChargeNotificationID(paymentID string) string {
|
|
sum := sha256.Sum256([]byte("orphan-replay-" + paymentID))
|
|
return "O" + hex.EncodeToString(sum[:])[:11]
|
|
}
|
|
|
|
// insertOrphanReplayChargeNotification surfaces an orphaned sweep-minted
|
|
// duplicate charge in the admin notification centre (reason
|
|
// 'critical_payment_log'), deduped by the deterministic per-origin-row id so
|
|
// repeated deliveries of the same orphan charge's event never add a second
|
|
// row. booking_id is set when the origin payment row has one, giving the owner
|
|
// a booking to act from. Best-effort: an insert failure is logged, never a
|
|
// dispatch error.
|
|
func insertOrphanReplayChargeNotification(ctx context.Context, paymentID, bookingID string) {
|
|
if paymentID == "" {
|
|
return
|
|
}
|
|
id := orphanReplayChargeNotificationID(paymentID)
|
|
var bid any
|
|
if bookingID != "" {
|
|
bid = bookingID
|
|
}
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO admin_notifications (id, reason, booking_id, created_at)
|
|
VALUES ($1, 'critical_payment_log'::admin_notification_reason, $2, NOW())
|
|
ON CONFLICT (id) DO NOTHING
|
|
`, id, bid)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to insert orphaned-replay admin notification: %v", err)
|
|
return
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] Inserted orphaned-replay-charge admin notification (origin payment=%s, booking=%q)", paymentID, bookingID)
|
|
}
|
|
}
|
|
|
|
// detectOrphanedReplayCharge handles a COMPLETED payment.updated event whose
|
|
// square_payment_id matches NO local payments row — the signature of an
|
|
// ORPHANED SWEEP-MINTED duplicate charge (B1-support). When the stale-pending
|
|
// sweep replays a pending row's stored idempotency key against Square and the
|
|
// key has expired, Square creates a NEW charge under that same key; the new
|
|
// charge's payment.updated event arrives here with no local row of its own,
|
|
// while the pending ORIGIN row (the one the sweep replayed) still exists and
|
|
// shares the replayed idempotency key — and, for booking/gift-card charges,
|
|
// the same reference_id and amount.
|
|
//
|
|
// Action (the webhook half of B1): mark the origin row 'failed' — it is NOT
|
|
// the charge that completed, so rescuing it to 'completed' would hide the
|
|
// duplicate behind the original and rescuing by square_payment_id is
|
|
// impossible (the orphan has no row) — and surface a deduped 'orphaned replay
|
|
// charge detected' admin notification. The AUTO-REFUND of the orphan charge is
|
|
// the SWEEP's job (sweep.go, the money agent's B1 fix): this path NEVER issues
|
|
// a refund and must never be turned into one; it detects + notifies + settles
|
|
// the origin row so the sweep does not blind-fail or double-rescue it later.
|
|
func detectOrphanedReplayCharge(ctx context.Context, payment squarePaymentPayload) error {
|
|
originID, bookingID, found, err := findPendingByOrphanKeys(ctx, payment)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Orphan-replay origin lookup failed for square payment %s: %v", payment.ID, err)
|
|
return err
|
|
}
|
|
if !found {
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated: COMPLETED square payment %s matches no local row and no pending origin row by idempotency key/reference_id — acknowledging (not a sweep-minted duplicate)", payment.ID)
|
|
return nil
|
|
}
|
|
tag, err := db.Conn.Exec(ctx,
|
|
`UPDATE payments SET status = 'failed', updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
|
originID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to mark orphaned-replay origin payment %s failed: %v", originID, err)
|
|
return err
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: COMPLETED square payment %s (orphaned sweep-minted duplicate) — origin pending payment %s marked failed; admin notified", payment.ID, originID)
|
|
} else {
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: COMPLETED square payment %s (orphaned sweep-minted duplicate) — origin payment %s already resolved; admin notified", payment.ID, originID)
|
|
}
|
|
insertOrphanReplayChargeNotification(ctx, originID, bookingID)
|
|
return nil
|
|
}
|
|
|
|
// handlePaymentUpdated reconciles a Square Payment state change against the
|
|
// local payments row (real-time counterpart to the stale-pending sweep). The
|
|
// Square id is logged, never the payload (PII). Idempotent: the UPDATE is a
|
|
// no-op when the local status already matches, and event_id dedup prevents
|
|
// re-entry at the handler level. A non-nil error means dispatch failed and the
|
|
// caller must NOT commit the dedup row (Square retries). All DB work runs on a
|
|
// bounded Background context (webhookDBContext): a client disconnect must not
|
|
// cancel the state mutation, and a hung DB call must not hold the pool forever.
|
|
func handlePaymentUpdated(data json.RawMessage) error {
|
|
ctx, cancel := webhookDBContext()
|
|
defer cancel()
|
|
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
// Parse failure on a known money event: the caller returns 5xx without
|
|
// committing the dedup row (errWebhookParseFailure), so Square
|
|
// re-delivers and the payment state change is not permanently lost.
|
|
return fmt.Errorf("payment event data envelope: %v: %w", err, errWebhookParseFailure)
|
|
}
|
|
if len(env.Object) == 0 {
|
|
// Legacy envelope carrying only data.id — no nested payment object to
|
|
// reconcile, so there is nothing to apply; acknowledge as received.
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|
|
var payment squarePaymentPayload
|
|
if !parseSquareObject(env.Object, "payment", &payment) || payment.ID == "" || payment.Status == "" {
|
|
// A payment object is present but unusable (malformed, or missing the
|
|
// id/status reconciliation needs): cannot apply money state — retry.
|
|
return fmt.Errorf("payment.updated payload for data.id=%q missing/invalid payment object (id=%q status=%q): %w", env.ID, payment.ID, payment.Status, errWebhookParseFailure)
|
|
}
|
|
localStatus, terminal := squarePaymentStatusToLocal(payment.Status)
|
|
if !terminal {
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated: square payment %s status %q is non-terminal — no local state change", payment.ID, payment.Status)
|
|
return nil
|
|
}
|
|
// Only 'pending' rows are candidates for a terminal transition — the same
|
|
// conservative rule the stale-pending sweeps use. A webhook for an already
|
|
// settled row (Square fires payment.updated for ANY field change, e.g. fee
|
|
// recalculation on a fully-refunded charge) must never revert a terminal
|
|
// status like 'refunded' back to 'completed'.
|
|
tag, err := db.Conn.Exec(ctx,
|
|
`UPDATE payments SET status = $1, updated_at = NOW() WHERE square_payment_id = $2 AND status = 'pending'`,
|
|
localStatus, payment.ID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to update payment %s to status %s: %v", payment.ID, localStatus, err)
|
|
return err
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated: square payment %s → local status %s", payment.ID, localStatus)
|
|
} else if localStatus == "completed" {
|
|
// B1-support: a COMPLETED payment.updated that matched NO pending
|
|
// 'payments' row may be an ORPHANED SWEEP-MINTED duplicate — the
|
|
// stale-pending sweep replayed a stored idempotency key against an
|
|
// expired key, Square landed a NEW charge whose id matches nothing
|
|
// locally, and this is that new charge's completion event. If NO local
|
|
// row carries this square_payment_id at all (not even a settled one),
|
|
// hunt for the pending origin row and settle it so the sweep never
|
|
// blind-fails or double-rescues it. A settled row existing means this
|
|
// is a plain no-op replay of a known charge and is left untouched.
|
|
known, kErr := squarePaymentKnown(ctx, payment.ID)
|
|
if kErr != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to check whether square payment %s is known: %v", payment.ID, kErr)
|
|
return kErr
|
|
}
|
|
if !known {
|
|
if dErr := detectOrphanedReplayCharge(ctx, payment); dErr != nil {
|
|
return dErr
|
|
}
|
|
}
|
|
}
|
|
// A Square charge can also map to a till_sales row (online gift-card
|
|
// purchase, retail at the till) — reconcile those too. Same pending-only
|
|
// guard: never revert a terminal till-sale status. A definitively failed
|
|
// charge (Square FAILED/CANCELED) claws back the gift-card funding those
|
|
// pending sales added, exactly like the stale-pending sweep
|
|
// (handlers/payments/sweep.go); an ambiguous status never reaches here.
|
|
if localStatus == "failed" {
|
|
return clawbackFailedTillSales(ctx, payment.ID)
|
|
}
|
|
tsTag, err := db.Conn.Exec(ctx,
|
|
`UPDATE till_sales SET status = $1, updated_at = NOW() WHERE square_payment_id = $2 AND status = 'pending'`,
|
|
localStatus, payment.ID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to reconcile till_sales for square payment %s: %v", payment.ID, err)
|
|
return err
|
|
}
|
|
if tsTag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated: reconciled %d till_sale(s) for square payment %s → status %s", tsTag.RowsAffected(), payment.ID, localStatus)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// clawbackFailedTillSales reverts the gift-card funding of every still-pending
|
|
// till sale funded by a Square charge that is DEFINITIVELY failed (Square
|
|
// FAILED/CANCELED — never ambiguous). It mirrors the stale-pending sweep's
|
|
// clawbackTillSaleFunding + revertGiftCardFunding (handlers/payments/sweep.go,
|
|
// till.go): each sale is claimed with a status='pending' guard so an
|
|
// already-resolved row is skipped without error, and the failed mark + funding
|
|
// revert commit atomically. A non-nil error means a DB failure left a pending
|
|
// sale's funding unreverted — the caller rejects the webhook so Square retries
|
|
// the clawback (the sweep is the eventual backstop).
|
|
func clawbackFailedTillSales(ctx context.Context, squarePaymentID string) error {
|
|
rows, err := db.Conn.Query(ctx, `
|
|
SELECT ts.id, ts.item_type, ts.item_id, ts.total_amount, gc.redeemed_by,
|
|
(ts.created_at = gc.created_at) AS is_create
|
|
FROM till_sales ts
|
|
LEFT JOIN gift_cards gc ON gc.id = ts.item_id
|
|
WHERE ts.square_payment_id = $1 AND ts.status = 'pending'
|
|
`, squarePaymentID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to read pending till_sales for funding clawback (square payment %s): %v", squarePaymentID, err)
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var (
|
|
saleID string
|
|
itemType string
|
|
itemID sql.NullString
|
|
totalAmount float64
|
|
redeemedBy sql.NullString
|
|
isCreate *bool
|
|
)
|
|
if err := rows.Scan(&saleID, &itemType, &itemID, &totalAmount, &redeemedBy, &isCreate); err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to scan pending till_sale for funding clawback (square payment %s): %v", squarePaymentID, err)
|
|
return err
|
|
}
|
|
if err := clawbackOneTillSale(ctx, saleID, itemType, itemID, totalAmount, redeemedBy, isCreate); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return rows.Err()
|
|
}
|
|
|
|
// clawbackOneTillSale resolves one pending till sale of a definitively failed
|
|
// charge. A gift-card sale has its funding reverted atomically with the failed
|
|
// mark; a sale with no gift card (future retail product / orphaned item) is
|
|
// only marked failed. An already-resolved sale is skipped, not an error.
|
|
func clawbackOneTillSale(ctx context.Context, saleID, itemType string, itemID sql.NullString, totalAmount float64, redeemedBy sql.NullString, isCreate *bool) error {
|
|
if itemType != "gift_card" || !itemID.Valid || itemID.String == "" || isCreate == nil {
|
|
// No gift card to claw back — mark the sale failed without touching
|
|
// any card (mirrors the sweep's non-gift-card branch).
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
UPDATE till_sales SET status = 'failed', updated_at = NOW()
|
|
WHERE id = $1 AND status = 'pending'
|
|
`, saleID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to mark till sale %s failed: %v", saleID, err)
|
|
return err
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] payment.updated: marked till sale %s failed (no gift card to claw back)", saleID)
|
|
}
|
|
return nil
|
|
}
|
|
action := "topup"
|
|
if *isCreate {
|
|
action = "create"
|
|
}
|
|
var redeem *string
|
|
if redeemedBy.Valid && redeemedBy.String != "" {
|
|
redeem = &redeemedBy.String
|
|
}
|
|
if err := revertTillSaleGiftCardFunding(ctx, action, itemID.String, totalAmount, redeem, saleID); err != nil {
|
|
if payments.IsTillSaleNotPending(err) {
|
|
log.Printf("[SQUARE-WEBHOOK] Till sale %s was already resolved (not pending) — skipping funding clawback", saleID)
|
|
return nil
|
|
}
|
|
log.Printf("CRITICAL: [SQUARE-WEBHOOK] failed to claw back gift card %s funding for failed till sale %s: %v — MANUAL RECONCILIATION REQUIRED: gift card may still be funded", itemID.String, saleID, err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// revertTillSaleGiftCardFunding undoes the gift-card funding of a till sale
|
|
// whose charge definitively failed. It delegates to the single shared clawback
|
|
// implementation, payments.RevertGiftCardFunding (handlers/payments/
|
|
// giftcard_clawback.go) — the same helper the till handler and the stale-pending
|
|
// sweep use — so the webhook's money reversal can never drift from theirs. The
|
|
// claim-first status='pending' guard, the create/top-up branches, the
|
|
// redeem-to-user reversal, the CRITICAL reconciliation log lines and the
|
|
// errTillSaleNotPending sentinel all live in that one place.
|
|
func revertTillSaleGiftCardFunding(ctx context.Context, action, giftCardID string, amount float64, redeemToUserID *string, tillSaleID string) error {
|
|
return payments.RevertGiftCardFunding(ctx, action, giftCardID, amount, redeemToUserID, tillSaleID)
|
|
}
|
|
|
|
// handleRefundUpdated reconciles a Square Refund state change against the local
|
|
// refunds row. Idempotent (status-guarded UPDATE + event_id dedup). A non-nil
|
|
// error means dispatch failed and the caller must NOT commit the dedup row. DB
|
|
// work runs on a bounded Background context (webhookDBContext).
|
|
func handleRefundUpdated(data json.RawMessage) error {
|
|
ctx, cancel := webhookDBContext()
|
|
defer cancel()
|
|
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
// Parse failure on a known money event: retry via 5xx, no dedup row.
|
|
return fmt.Errorf("refund event data envelope: %v: %w", err, errWebhookParseFailure)
|
|
}
|
|
if len(env.Object) == 0 {
|
|
// Legacy envelope carrying only data.id — no nested refund object to
|
|
// reconcile; acknowledge as received.
|
|
log.Printf("[SQUARE-WEBHOOK] refund.updated received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|
|
var refund squareRefundPayload
|
|
if !parseSquareObject(env.Object, "refund", &refund) || refund.ID == "" || refund.Status == "" {
|
|
// A refund object is present but unusable: cannot apply money state — retry.
|
|
return fmt.Errorf("refund.updated payload for data.id=%q missing/invalid refund object (id=%q status=%q): %w", env.ID, refund.ID, refund.Status, errWebhookParseFailure)
|
|
}
|
|
localStatus, terminal := squareRefundStatusToLocal(refund.Status)
|
|
if !terminal {
|
|
log.Printf("[SQUARE-WEBHOOK] refund.updated: square refund %s status %q is non-terminal — no local state change", refund.ID, refund.Status)
|
|
return nil
|
|
}
|
|
// COMPLETED may promote any non-completed row (incl. a sweep-failed refund
|
|
// Square later shows complete) — the over-refund guard counts completed
|
|
// refunds, so this only tightens it. FAILED only demotes a 'pending' row:
|
|
// demoting 'completed' would let the guard exclude money that already moved
|
|
// (the exact risk refunds.go documents for failed refunds).
|
|
switch localStatus {
|
|
case "completed":
|
|
tag, err := db.Conn.Exec(ctx, `UPDATE refunds SET status = 'completed' WHERE square_refund_id = $1 AND status <> 'completed'`, refund.ID)
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to update refund %s to status %s: %v", refund.ID, localStatus, err)
|
|
return err
|
|
}
|
|
if tag.RowsAffected() > 0 {
|
|
log.Printf("[SQUARE-WEBHOOK] refund.updated: square refund %s → local status %s", refund.ID, localStatus)
|
|
}
|
|
return nil
|
|
case "failed":
|
|
// A5d: this webhook demotes a 'pending' row to 'failed' BEFORE the sweep
|
|
// ever sees it — the sweep only processes 'pending' rows, so its
|
|
// failed-refund admin notification would be permanently lost. Raise the
|
|
// same 'refund_failed' notification here (via the shared exported
|
|
// payments.InsertRefundFailedNotifications — the single source for the
|
|
// SQL and its (reason='refund_failed', booking_id) dedup guard), guarded
|
|
// to the actually-demoted row.
|
|
var rowID string
|
|
err := db.Conn.QueryRow(ctx,
|
|
`UPDATE refunds SET status = 'failed' WHERE square_refund_id = $1 AND status = 'pending' RETURNING id`,
|
|
refund.ID).Scan(&rowID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
// No pending row matched — the refund is already resolved; a late
|
|
// FAILED/REJECTED replay must not demote or notify anything.
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to update refund %s to status %s: %v", refund.ID, localStatus, err)
|
|
return err
|
|
}
|
|
log.Printf("[SQUARE-WEBHOOK] refund.updated: square refund %s → local status failed (row %s)", refund.ID, rowID)
|
|
payments.InsertRefundFailedNotifications(ctx, []string{rowID})
|
|
return nil
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// truncateDisputeReason caps a Square dispute reason at the disputes.reason
|
|
// VARCHAR(192) column width. An over-long reason would fail the disputes
|
|
// INSERT; the handler treats that as a dispatch error (no dedup row, 5xx), so
|
|
// Square would retry forever — truncating lets the event succeed instead.
|
|
// VARCHAR(192) counts CHARACTERS, not bytes, so truncation must slice on a rune
|
|
// boundary: byte-slicing (reason[:192]) can split a multi-byte UTF-8 rune and
|
|
// store invalid UTF-8 (which Postgres rejects), failing the INSERT the same way
|
|
// an over-long reason would. Slicing the []rune form keeps the stored reason a
|
|
// valid, at-most-192-character UTF-8 string.
|
|
func truncateDisputeReason(reason string) string {
|
|
runes := []rune(reason)
|
|
if len(runes) > 192 {
|
|
return string(runes[:192])
|
|
}
|
|
return reason
|
|
}
|
|
|
|
// handleDisputeCreated records a newly opened dispute: inserts the disputes row
|
|
// and surfaces a critical_payment_log admin notification so the owner sees the
|
|
// chargeback in-app. A disputed Square payment with NO local payments row (a
|
|
// Dashboard-initiated charge, a mismatched Square id, or a deleted/erased row)
|
|
// cannot be reconciled to a booking — no disputes row is written — but the
|
|
// admin notification is STILL raised with booking_id NULL, because there is no
|
|
// sweep fallback for disputes and a chargeback the app cannot see is a silent
|
|
// money-loss path the owner must always be told about. Idempotent via
|
|
// ON CONFLICT (square_dispute_id) DO NOTHING plus the event_id dedup. A non-nil
|
|
// error means dispatch failed (no dedup row committed — Square retries). DB
|
|
// work runs on a bounded Background context (webhookDBContext).
|
|
func handleDisputeCreated(data json.RawMessage) error {
|
|
ctx, cancel := webhookDBContext()
|
|
defer cancel()
|
|
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
// Parse failure on a known money event (chargeback): retry via 5xx, no
|
|
// dedup row — disputes have no sweep fallback, so a lost event is a
|
|
// silent money-loss path.
|
|
return fmt.Errorf("dispute event data envelope: %v: %w", err, errWebhookParseFailure)
|
|
}
|
|
if len(env.Object) == 0 {
|
|
// Legacy envelope carrying only data.id — no nested dispute object to
|
|
// record; acknowledge as received.
|
|
log.Printf("[SQUARE-WEBHOOK] dispute.created received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|
|
var dispute squareDisputePayload
|
|
if !parseSquareObject(env.Object, "dispute", &dispute) || dispute.ID == "" {
|
|
// A dispute object is present but unusable: cannot record the
|
|
// chargeback — retry.
|
|
return fmt.Errorf("dispute.created payload for data.id=%q missing/invalid dispute object (id=%q): %w", env.ID, dispute.ID, errWebhookParseFailure)
|
|
}
|
|
squarePaymentID := ""
|
|
if dispute.DisputedPayment != nil {
|
|
squarePaymentID = dispute.DisputedPayment.PaymentID
|
|
}
|
|
paymentID, bookingID, paymentFound := findPaymentBySquareID(ctx, squarePaymentID)
|
|
if !paymentFound {
|
|
// Untracked chargeback: no local payments row for this Square charge
|
|
// (Dashboard-initiated, mismatched Square payment id, or a deleted/erased
|
|
// row). There is NO sweep fallback for disputes — this notification is
|
|
// the only in-app trace the owner gets that Square is clawing back funds,
|
|
// so it must never be skipped. booking_id stays NULL; each DISTINCT
|
|
// dispute gets its OWN deterministic-id notification (the booking-scoped
|
|
// dedup would collapse separate chargebacks into one suppressed row).
|
|
// Still return nil so the dedup row commits and Square's retry is
|
|
// acknowledged.
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: dispute %s created for square payment %q with NO local payment row — chargeback cannot be reconciled in-app — admin notified (booking_id NULL)", dispute.ID, squarePaymentID)
|
|
insertCriticalPaymentNotification(ctx, "", dispute.ID)
|
|
return nil
|
|
}
|
|
amount := squareMoneyToAmount(dispute.AmountMoney)
|
|
tag, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO disputes (square_dispute_id, payment_id, status, amount, reason, created_at, updated_at)
|
|
VALUES ($1, $2, 'open', $3, NULLIF($4, ''), NOW(), NOW())
|
|
ON CONFLICT (square_dispute_id) DO NOTHING
|
|
`, dispute.ID, paymentID, amount, truncateDisputeReason(dispute.Reason))
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to insert dispute %s: %v", dispute.ID, err)
|
|
return err
|
|
}
|
|
_ = tag
|
|
insertCriticalPaymentNotification(ctx, bookingID, "")
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: dispute %s created (amount %s, reason %q) for square payment %s — admin notified", dispute.ID, amount, truncateDisputeReason(dispute.Reason), squarePaymentID)
|
|
return nil
|
|
}
|
|
|
|
// handleDisputeStateUpdated applies a Square dispute state change to the local
|
|
// disputes row (upsert — a state.updated may arrive before the created event),
|
|
// and on a terminal loss marks the payment failed + raises CRITICAL. Won is
|
|
// logged only. Idempotent: the upsert converges to the same row. A non-nil
|
|
// error means dispatch failed (no dedup row committed — Square retries). DB
|
|
// work runs on a bounded Background context (webhookDBContext).
|
|
func handleDisputeStateUpdated(data json.RawMessage) error {
|
|
ctx, cancel := webhookDBContext()
|
|
defer cancel()
|
|
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
// Parse failure on a known money event (chargeback): retry via 5xx, no
|
|
// dedup row — disputes have no sweep fallback.
|
|
return fmt.Errorf("dispute event data envelope: %v: %w", err, errWebhookParseFailure)
|
|
}
|
|
if len(env.Object) == 0 {
|
|
// Legacy envelope carrying only data.id — no nested dispute object;
|
|
// acknowledge as received.
|
|
log.Printf("[SQUARE-WEBHOOK] dispute.state.updated received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|
|
var dispute squareDisputePayload
|
|
if !parseSquareObject(env.Object, "dispute", &dispute) || dispute.ID == "" {
|
|
// A dispute object is present but unusable: cannot apply the state
|
|
// change — retry.
|
|
return fmt.Errorf("dispute.state.updated payload for data.id=%q missing/invalid dispute object (id=%q): %w", env.ID, dispute.ID, errWebhookParseFailure)
|
|
}
|
|
localStatus := squareDisputeStateToLocal(dispute.State)
|
|
amount := squareMoneyToAmount(dispute.AmountMoney)
|
|
|
|
squarePaymentID := ""
|
|
if dispute.DisputedPayment != nil {
|
|
squarePaymentID = dispute.DisputedPayment.PaymentID
|
|
}
|
|
paymentID, bookingID, paymentFound := findPaymentBySquareID(ctx, squarePaymentID)
|
|
if !paymentFound {
|
|
// Row may already exist from dispute.created — recover its payment.
|
|
paymentID, bookingID = findPaymentByDisputeID(ctx, dispute.ID)
|
|
if paymentID == "" {
|
|
// Untracked chargeback: no local payments row for this Square
|
|
// charge AND no dispute row to recover one from. Mirror the
|
|
// dispute.created untracked branch — there is NO sweep fallback for
|
|
// disputes, so this critical notification is the only in-app trace
|
|
// the owner gets that Square is clawing back funds; a state.updated
|
|
// arriving without a prior created event must surface it too, never
|
|
// drop it silently. booking_id stays NULL; disputeNotificationID
|
|
// gives each DISTINCT dispute its own deterministic-id notification
|
|
// and makes this insert a no-op if dispute.created already raised
|
|
// it. Still return nil so the dedup row commits and Square's retry
|
|
// is acknowledged.
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: dispute %s state change (state %s) for square payment %q with NO local payment row — chargeback cannot be reconciled in-app — admin notified (booking_id NULL)", dispute.ID, dispute.State, squarePaymentID)
|
|
insertCriticalPaymentNotification(ctx, "", dispute.ID)
|
|
return nil
|
|
}
|
|
}
|
|
|
|
_, err := db.Conn.Exec(ctx, `
|
|
INSERT INTO disputes (square_dispute_id, payment_id, status, amount, reason, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, NULLIF($5, ''), NOW(), NOW())
|
|
ON CONFLICT (square_dispute_id) DO UPDATE
|
|
SET status = EXCLUDED.status, amount = EXCLUDED.amount,
|
|
reason = EXCLUDED.reason, updated_at = NOW()
|
|
`, dispute.ID, paymentID, localStatus, amount, truncateDisputeReason(dispute.Reason))
|
|
if err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] Failed to update dispute %s to state %s: %v", dispute.ID, dispute.State, err)
|
|
return err
|
|
}
|
|
|
|
switch localStatus {
|
|
case "lost":
|
|
if err := markPaymentFailed(ctx, paymentID); err != nil {
|
|
return err
|
|
}
|
|
insertCriticalPaymentNotification(ctx, bookingID, "")
|
|
log.Printf("[SQUARE-WEBHOOK] CRITICAL: dispute %s LOST — payment %s marked failed; admin notified", dispute.ID, paymentID)
|
|
case "won":
|
|
log.Printf("[SQUARE-WEBHOOK] dispute %s WON — resolved in seller's favour; no action", dispute.ID)
|
|
default:
|
|
log.Printf("[SQUARE-WEBHOOK] dispute %s state → %s (status %s)", dispute.ID, dispute.State, localStatus)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// handleDisputeEvidence logs evidence submissions/removals. Evidence does not
|
|
// change the dispute's local status, so it is informational only.
|
|
func handleDisputeEvidence(data json.RawMessage) error {
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] dispute evidence event received (payload length=%d)", len(data))
|
|
return nil
|
|
}
|
|
var dispute squareDisputePayload
|
|
if !parseSquareObject(env.Object, "dispute", &dispute) || dispute.ID == "" {
|
|
log.Printf("[SQUARE-WEBHOOK] dispute evidence event received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|
|
log.Printf("[SQUARE-WEBHOOK] dispute evidence event for dispute %s (state %s)", dispute.ID, dispute.State)
|
|
return nil
|
|
}
|
|
|
|
// handleTerminalCheckout logs terminal checkout lifecycle events. Terminal
|
|
// checkout state is owned by the poll/sweep handlers (handlers/payments/),
|
|
// which fetch the authoritative status from Square — no state mutation here.
|
|
func handleTerminalCheckout(data json.RawMessage) error {
|
|
var env squareWebhookData
|
|
if err := json.Unmarshal(data, &env); err != nil {
|
|
log.Printf("[SQUARE-WEBHOOK] terminal.checkout event received (payload length=%d)", len(data))
|
|
return nil
|
|
}
|
|
log.Printf("[SQUARE-WEBHOOK] terminal.checkout event received (data.id=%s)", env.ID)
|
|
return nil
|
|
}
|