payment

package
v0.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	StripeKeyRejected      = "rejected"
	StripeKeyNotConfigured = "not_configured"
)

Reasons of a StripeKeyError; also the label of hardcount_stripe_key_unusable_total.

View Source
const PurposeHostedInvoicePay = "hosted_invoice_pay"

PurposeHostedInvoicePay tags a PaymentIntent created by the hosted invoice page's Stripe Checkout session. Hardcount never waits on such an attempt — the customer drives it while Hardcount's own charges carry on — so its failure is recorded on its attempt row and never moves the invoice (SettleFailed).

Variables

View Source
var ErrChargeInFlight = errs.InvalidState("a payment for this invoice is already in progress").WithCode("payment_in_progress")

ErrChargeInFlight is the in-flight guard: a PaymentIntent is processing (dunning auto-retry racing the customer's Pay click — the most likely double-charge collision), or a drifted session the customer just completed is settling. Parity with the void/uncollectible/offline guards.

View Source
var ErrInvoiceNotPayable = errs.InvalidState("invoice is not in a payable state").WithCode("not_payable")

ErrInvoiceNotPayable is returned by ClaimOpen when the payable re-check inside the claim transaction fails — the invoice settled or voided under the caller. The mint-vs-settle TOCTOU killer: the FOR SHARE read serializes against the paid-flip's FOR UPDATE, so either the claim aborts here, or it commits first and the settle's in-tx close is guaranteed to see the row. errs.InvalidState-kinded so peer-import-free handlers map it to an honest 409 via the standard taxonomy.

View Source
var ErrNoSavedCard = errors.New("no saved card on the Stripe customer")

ErrNoSavedCard is FetchCardDetails' "the Stripe customer has no card" — a one-off payment where the customer did not save the card. It is the only FetchCardDetails error that means "nothing to record"; any other is a failed lookup and must be retried.

View Source
var ErrPaymentTransient = errors.New("payment attempt skipped; upstream breaker open, timeout before Stripe, or Stripe rate limit")

ErrPaymentTransient signals that this charge request charged nothing, so the invoice state is unchanged: the circuit breaker was open, the credentials could not be read, Stripe refused the request with 429, or Stripe refused the key (StripeKeyError). The scheduler/dunning path should treat this as "skip this tick" and not tick the dunning attempt count, unlike a real payment failure.

A 429 speaks only for the request it answers. When stripe-go resent the request after a network error, the first request under the same key may still be running at Stripe and charge the card (#976). The hold stays, so the same initiator resends the same key; another charge kind or a changed card sends a new one.

View Source
var ErrSessionCompleted = errors.New("checkout session already completed")

ErrSessionCompleted: a Stripe expire attempt found the session COMPLETED — the customer already paid it. The caller must NOT mint a replacement (a second payable vehicle = the double charge); the webhook settle is in flight and the amount-mismatch escalation owns any drift consequence.

View Source
var ErrStripeAuthFailed = errors.New("stripe rejected the API key")

ErrStripeAuthFailed marks a read Stripe refused with 401 or 403: the tenant's key is wrong or revoked, or is a restricted key without permission to read PaymentIntents. It will not succeed until someone fixes the key, so the stale-hold sweep logs it as a check that cannot run (ADR-127).

View Source
var ErrStripeCredentialsUnavailable = fmt.Errorf("%w: stripe credentials could not be read", ErrPaymentTransient)

ErrStripeCredentialsUnavailable is the ErrPaymentTransient for a request that never left: the tenant's Stripe credentials could not be read (a database blip). Unlike a 429 it says nothing could be running at Stripe, so the charge releases its hold (ADR-127).

View Source
var ErrStripeCustomerMissing = errors.New("stripe customer not found in this account")

ErrStripeCustomerMissing marks a read Stripe refused because the customer does not exist in this account (resource_missing on the customer): deleted, or created under other credentials. It will not succeed on retry.

View Source
var ErrStripeNotConfigured = &PaymentError{Message: "stripe not configured for this mode"}

ErrStripeNotConfigured is returned when a request routes to a Stripe mode (live or test) for which the tenant has not connected credentials. Surfaces as an explicit PaymentError rather than a nil deref so operators get an actionable signal ("connect Stripe under Settings → Payments").

View Source
var ErrStripeUnreachable = errors.New("stripe could not be reached")

ErrStripeUnreachable marks a read that got no answer from Stripe: a network error, or the caller's time limit ended it. Unlike a 5xx or a 429, which Stripe answers at once, it can take as long as the time limit allows, so the stale-hold sweep stops for the tick after several in a row.

Functions

func ChargeIdempotencyKey

func ChargeIdempotencyKey(invoiceID string, chargeAttemptSeq int64, purpose string) string

ChargeIdempotencyKey is the SINGLE SOURCE for an invoice charge's Stripe idempotency key. Exported so tests derive the key from this function instead of re-typing the format — a test that hardcodes the shape keeps passing when the real key changes, which is the divergence class §3.6 of docs/dev/manual-test-strategy.md exists to catch.

The key answers exactly one question: is this call the SAME charge attempt as before, or a new one? It must move exactly when an attempt's outcome is recorded:

  • a RECORDED decline must get a FRESH key, so a retry after the customer fixes their card isn't handed the declined PI forever (no liveness sink);
  • a charge whose result was lost (a crash, a shutdown) does NOT rely on the key to avoid a second charge. The key only dedupes the same initiator, same card and same amount within Stripe's 24 hours; another charge kind, a changed card, a pruned key or the hosted page all go around it (#976). Its hold stays set instead, every claim refuses it, and the stale-hold sweep asks Stripe what the lost charge did (ADR-127). When Stripe has nothing, the sweep moves the seq, so the next charge gets a fresh key and is never handed a 500 Stripe saved under the old one.

charge_attempt_seq is that signal directly: it is bumped by the writes that stamp stripe_payment_intent_id and by the stale-hold sweep's "nothing at Stripe" clear, and by nothing else (migration 0165, ADR-105 amendment, CI-enforced by TestChargeAttemptSeqBumpedByEveryPIStamp).

It replaced inv.UpdatedAt, which was a PROXY for the same question and answered a much broader one — "did anything at all touch this row?" — making every unrelated writer an accidental participant in the payment protocol. A tax-commit stamp or a credit application landing in the crash window re-seeded the key and minted a second PaymentIntent for an invoice already being charged (observed in #677; fixed in #678).

The purpose suffix keeps the finalize-time charge and a dunning retry distinct even at the same seq: they attach different PI metadata, and Stripe answers "same key, different parameters" with a 409.

func IsDefiniteRefusal

func IsDefiniteRefusal(err error) bool

IsDefiniteRefusal reports whether Stripe answered a create request with a refusal that proves it created nothing: a 4xx other than 409 (a request with the same idempotency key may still be running, #976) and 429 (it speaks only for this request), and not an idempotency_error (the key was used before, so an earlier request reached Stripe). A network error, a 5xx or anything that is not a Stripe error is not one.

func IsUnknownPaymentFailure

func IsUnknownPaymentFailure(err error) bool

IsUnknownPaymentFailure classifies an error returned from ChargeInvoice as a Stripe-side unknown outcome (5xx, timeout, network) — the failure category that should feed the circuit breaker. Explicit card declines and validation errors return false. Exported so the breaker factory can reuse the exact same classification used at the charge site.

func SentIdempotencyKey added in v0.9.2

func SentIdempotencyKey(chargeKey, paymentMethodID string) string

SentIdempotencyKey is the Idempotency-Key a charge sends to Stripe: the charge key plus the card, so charging a different card is a new request. Logs name this value, not the bare charge key: it is the one Stripe's dashboard finds the request by.

Types

type AuditEmitter

type AuditEmitter interface {
	LogInTx(ctx context.Context, tx *sql.Tx, e audit.Entry) error
}

AuditEmitter is the narrow in-tx audit seam (ADR-090).

type BelowMinimumError

type BelowMinimumError struct {
	Message string // Stripe's sentence, scrubbed; it names the minimum
}

BelowMinimumError is Stripe refusing a charge, or a payment-mode Checkout Session, because the amount is below Stripe's minimum charge: HTTP 400, invalid_request_error, code amount_too_small (seen on a test-mode account, 2026-10-22: "Amount must be at least $0.50 usd"). Stripe makes no PaymentIntent and no session, so nothing was charged, and asking again gets the same answer with any card. domain.ErrBelowMinimumCharge says what Hardcount does with it.

It must not be or wrap a *PaymentError, for the reason StripeKeyError gives: the auto-charge sweep, the dunning retry and Collect all read a *PaymentError with Unknown=false as a decline. Nor ErrPaymentTransient: that leaves the invoice queued, and the sweep would ask Stripe every tick.

func BelowMinimumOf

func BelowMinimumOf(err error) *BelowMinimumError

BelowMinimumOf is belowMinimumOf for the hosted page's Checkout Session create, which calls stripe-go itself (api/adapters.go).

func (*BelowMinimumError) Error

func (e *BelowMinimumError) Error() string

func (*BelowMinimumError) Unwrap

func (e *BelowMinimumError) Unwrap() error

type CardDetails

type CardDetails struct {
	PaymentMethodID string
	Brand           string
	Last4           string
	ExpMonth        int
	ExpYear         int
}

CardDetails holds card info fetched from Stripe for display.

type CardFetcher

type CardFetcher interface {
	FetchCardDetails(ctx context.Context, stripeCustomerID string) (CardDetails, error)
	FetchCardForPaymentIntent(ctx context.Context, paymentIntentID string) (CardDetails, error)
}

CardFetcher fetches card details from Stripe.

FetchCardDetails returns the NEWEST card saved on the Stripe customer (by created time), not Stripe's or Hardcount's default. RecordCheckoutCard uses it to find the card a finished Checkout session just saved; it reads only and never changes Stripe's default.

FetchCardForPaymentIntent returns the card actually charged on a specific PaymentIntent. Used by the payment-succeeded webhook handler to stamp the invoice's `payment_card_brand` / `payment_card_last4` columns (ADR-020). Works for one-off Checkout cards too — the customer doesn't have to save the PM for the timeline to show what was charged.

type CheckoutCardRecorder

type CheckoutCardRecorder interface {
	RecordCheckoutCard(ctx context.Context, tenantID, customerID, stripeCustomerID, purpose string) error
}

CheckoutCardRecorder records the card a finished Checkout session saved as the customer's payment method. *Stripe implements it (RecordCheckoutCard), shared with the checkout.session.completed webhook.

type CheckoutClaim

type CheckoutClaim struct {
	ID              string
	TenantID        string
	InvoiceID       string
	Livemode        bool
	StripeSessionID string
	URL             string
	AmountCents     int64
	Currency        string
	Status          string
	ExpiresAt       *time.Time
	CreatedAt       time.Time
}

CheckoutClaim is one row of the checkout_sessions claim ledger (0125, ADR-068). A claim is created BEFORE the Stripe session exists (StripeSessionID empty) and filled via CAS once the create returns; the claim ID derives the Stripe idempotency key, so any re-drive — crash recovery, the concurrent-double-POST loser — converges on the same Stripe session.

type CheckoutResponse

type CheckoutResponse struct {
	URL string `json:"url"`
}

CheckoutResponse is POST /v1/public/payment-updates/{token}/checkout.

type CheckoutSessionReader

type CheckoutSessionReader interface {
	GetCheckoutSession(ctx context.Context, sessionID string) (CheckoutSessionResult, error)
}

CheckoutSessionReader reads a Checkout Session's outcome at Stripe. *LiveStripeClient implements it.

type CheckoutSessionResult

type CheckoutSessionResult struct {
	Status          string // open | complete | expired
	PaymentStatus   string // paid | unpaid | no_payment_required
	PaymentIntentID string
	CustomerID      string // the Stripe customer the session saved the card to
}

CheckoutSessionResult is the part of a Stripe Checkout Session the sweep acts on.

type CheckoutSessionStore

type CheckoutSessionStore struct {
	// contains filtered or unexported fields
}

CheckoutSessionStore persists checkout-session claims. All methods are tenant-scoped via TxTenant (RLS-fenced).

func NewCheckoutSessionStore

func NewCheckoutSessionStore(db *postgres.DB) *CheckoutSessionStore

func (*CheckoutSessionStore) ClaimOpen

func (s *CheckoutSessionStore) ClaimOpen(ctx context.Context, tenantID, invoiceID string, amountCents int64, currency string, livemode bool) (CheckoutClaim, bool, error)

ClaimOpen inserts the open claim for an invoice, re-verifying payability in the same transaction. Returns (claim, winner=true) when this call created the claim; (existing, winner=false) when an open claim already exists (the partial unique index is the concurrent-double-POST guard — the loser gets the winner's row and re-drives its Stripe create with the winner's claim-derived idempotency key).

func (*CheckoutSessionStore) ClaimOpenAudited

func (s *CheckoutSessionStore) ClaimOpenAudited(ctx context.Context, tenantID, invoiceID string, amountCents int64, currency string, livemode bool, emit func(tx *sql.Tx, claim CheckoutClaim) error) (CheckoutClaim, bool, error)

ClaimOpenAudited is ClaimOpen with an in-tx audit emission hook (ADR-090). emit fires ONLY on the winner path (the call that actually created the claim) — the loser/reuse paths mutate nothing new, so they record nothing.

func (*CheckoutSessionStore) FillSession

func (s *CheckoutSessionStore) FillSession(ctx context.Context, tenantID, claimID, stripeSessionID, url string, expiresAt time.Time) (string, error)

FillSession records the Stripe session onto the claim via CAS (stripe_session_id IS NULL). Losing the CAS is fine — the idempotency key guarantees both racers hold the SAME session, so the row already carries these values. It returns the claim's status after the write: a claim superseded while its create was in flight still records the session (so the sweeps can find it), but the caller must not hand its URL out.

func (*CheckoutSessionStore) GetOpenForInvoice

func (s *CheckoutSessionStore) GetOpenForInvoice(ctx context.Context, tenantID, invoiceID string) (CheckoutClaim, error)

GetOpenForInvoice returns the invoice's open claim, errs.ErrNotFound when none.

func (*CheckoutSessionStore) ListHostedToReconcile

func (s *CheckoutSessionStore) ListHostedToReconcile(ctx context.Context, checkedBefore time.Time, limit int) ([]CheckoutClaim, error)

ListHostedToReconcile is the hosted sweep's input (reconciler_hosted.go):

  • recorded sessions whose outcome Hardcount has not seen ('open', 'superseded', and 'invoice_settled', where the customer may have paid in the same moment the invoice was settled another way); and
  • 'completed' sessions whose invoice is still unpaid: the checkout.session.completed webhook arrived but the payment's own did not. They leave this list when the payment settles.

Each row waits until it is checkedBefore old (created, filled or last looked at), so the ordinary webhook records a payment first and the sweep spends no call on it. Not until the session expires: a paid session is final at Stripe as soon as the customer pays, so waiting would only leave the invoice unpaid longer. An unpaid session reads 'open' and is touched to the back of the queue until it is paid or expires.

Cross-tenant (TxBypass) for the ctx's mode, least recently looked at first so a session that keeps erroring cannot hold the head of the queue.

func (*CheckoutSessionStore) ListUnresolvedForInvoice

func (s *CheckoutSessionStore) ListUnresolvedForInvoice(ctx context.Context, tenantID, invoiceID string) ([]CheckoutClaim, error)

ListUnresolvedForInvoice returns every claim whose Stripe session may still be payable — the settle-time expire sweep's input (all rows not yet confirmed expired/completed, not just the open one: a superseded row's session stays live at Stripe if its expire call failed).

func (*CheckoutSessionStore) MarkCompleted

func (s *CheckoutSessionStore) MarkCompleted(ctx context.Context, stripeSessionID string) error

MarkCompleted is the checkout.session.completed truth-sync: the session finished at Stripe. Keyed on the Stripe session id (webhook-side lookup); TxBypass because the webhook carries no tenant ctx and the row is located by the globally-unique Stripe id.

func (*CheckoutSessionStore) MarkExpired

func (s *CheckoutSessionStore) MarkExpired(ctx context.Context, tenantID, claimID string) error

MarkExpired records a confirmed Stripe-side expire (or an "already expired" response, which is the same truth).

func (*CheckoutSessionStore) MarkSessionCompleted

func (s *CheckoutSessionStore) MarkSessionCompleted(ctx context.Context, tenantID, claimID string) error

MarkSessionCompleted records the hosted sweep's finding that a session was paid. Keyed on the claim id and unconditional on the prior status, unlike the webhook's MarkCompleted: the sweep also resolves 'invoice_settled' rows, and a row it leaves unchanged would be swept again every tick.

func (*CheckoutSessionStore) ReleaseRefused

func (s *CheckoutSessionStore) ReleaseRefused(ctx context.Context, tenantID, claimID string) error

ReleaseRefused closes a claim whose Checkout Session create Stripe refused outright (payment.IsDefiniteRefusal): no session exists, so nothing can be paid on it. It becomes 'expired', which domain.HostedCheckoutLiveSQL does not count, so charges on the invoice are no longer held for it. Only an open claim with no session moves: one a concurrent create filled is a real page and stays.

func (*CheckoutSessionStore) Supersede

func (s *CheckoutSessionStore) Supersede(ctx context.Context, tenantID, claimID string) (bool, error)

Supersede CAS-flips an open claim to superseded (amount drift or time-expiry). Exactly one concurrent caller wins (rowcount=1) and proceeds to remint; losers re-read and follow the loser protocol.

func (*CheckoutSessionStore) TouchReconcile

func (s *CheckoutSessionStore) TouchReconcile(ctx context.Context, tenantID, claimID string) error

TouchReconcile moves a session the sweep could not resolve to the back of its queue.

type CustomerByStripeIDResolver

type CustomerByStripeIDResolver interface {
	CustomerIDByStripeID(ctx context.Context, tenantID, stripeCustomerID string) (string, error)
}

CustomerByStripeIDResolver maps a Stripe Customer ID back to the Hardcount customer ID. Optional fallback for setup_intent.succeeded: a Checkout session in setup mode only carries hardcount_customer_id on the SetupIntent when its creator set setup_intent_data.metadata — and not every call site does. Rather than depend on that discipline at every session-creation site, the webhook resolves the customer from the SetupIntent's `customer` field, which Stripe always populates for our customer-scoped setup flows. This makes PM persistence authoritative-by-construction instead of best-effort-by-metadata.

type CustomerEmailResolver

type CustomerEmailResolver interface {
	GetCustomerEmail(ctx context.Context, tenantID, customerID string) (email, displayName string, additionalEmails []string, err error)
}

CustomerEmailResolver resolves customer contact info for email notifications.

type DisputeRecorder

type DisputeRecorder interface {
	RecordStripeDispute(ctx context.Context, tenantID string, snap domain.DisputeSnapshot) (domain.DisputeRecordResult, error)
}

DisputeRecorder records a card dispute snapshot against the invoice whose payment was disputed (#979), queuing payment.dispute_opened / .closed in the same transaction. Returns errs.ErrNotFound when no Hardcount invoice holds the disputed PaymentIntent (a charge the tenant made outside Hardcount). payment imports nothing from invoice; *invoice.PostgresStore satisfies it.

type DunningResolver

type DunningResolver interface {
	ResolveByInvoice(ctx context.Context, tenantID, invoiceID string, resolution domain.DunningResolution) error
}

DunningResolver closes an active dunning run when a card payment settles — symmetric with the engine's DunningResolver for background settles (credits / threshold / auto-charge, #317). Optional; nil = skip (the dunning sweep's paid-pre-check floor still resolves the run when it next comes due). Wire via SetDunningResolver. ResolveByInvoice no-ops when there is no active run, so it is safe to call on every card success.

type DunningRetryFailure added in v0.9.2

type DunningRetryFailure interface {
	RetryPaymentFailed(ctx context.Context, tenantID string, inv domain.Invoice, paymentIntentID, declineCode, cardMessage string) func(tx *sql.Tx, fresh domain.Invoice) error
}

DunningRetryFailure is dunning's hook for the failure of a dunning retry's payment (#1289): a retry whose payment came back processing keeps its run active and waiting on that PaymentIntent, and its later failure is recorded, and the customer warned, from here. SettleFailed calls RetryPaymentFailed before its transaction opens (plain reads only) and runs the hook it returns inside that transaction, after the failed stamp, in place of the generic failure email a dunning retry never gets. nil means no run waits on this payment. Satisfied by *dunning.Service.

type DunningStarter

type DunningStarter interface {
	StartDunning(ctx context.Context, tenantID string, invoiceID, customerID string, simFailedAt time.Time, cause domain.DunningStartCause) (domain.InvoiceDunningRun, error)
}

DunningStarter starts dunning for failed payments.

type EmailPaymentFailed

type EmailPaymentFailed interface {
	// ask selects the copy (domain.DeclineAskOf the decline code):
	// DeclineAskConfirm is the "confirm your payment" email, sent when the
	// bank wants the customer to confirm the payment.
	SendPaymentFailed(ctx context.Context, tenantID, to string, cc []string, customerName, invoiceNumber, reason, publicToken string, ask domain.DeclineAsk) error
	// SendPaymentFailedTx enqueues on the settle transaction (ADR-040 amendment).
	SendPaymentFailedTx(ctx context.Context, tx *sql.Tx, tenantID, to string, cc []string, customerName, invoiceNumber, reason, publicToken string, ask domain.DeclineAsk) error
}

EmailPaymentFailed sends "your charge was declined" emails. Hits after a Stripe charge attempt actually went through and was declined — distinct from EmailPaymentSetup which fires when there's no PM on file at finalize (no charge was ever attempted). Same signature as dunning.EmailNotifier so OutboxSender satisfies both.

type EmailReceipt

type EmailReceipt interface {
	SendPaymentReceipt(ctx context.Context, tenantID, to string, cc []string, customerName, invoiceNumber string, amountCents int64, currency, publicToken string) error
	// SendPaymentReceiptTx enqueues on the settle transaction so the receipt
	// commits with the paid-flip (ADR-040 amendment) — the settle path uses
	// this one; the post-commit variant remains for non-transactional callers.
	SendPaymentReceiptTx(ctx context.Context, tx *sql.Tx, tenantID, to string, cc []string, customerName, invoiceNumber string, amountCents int64, currency, publicToken string) error
}

EmailReceipt sends payment receipt emails. ctx carries livemode so the enqueue/brand lookup runs against the right tenant_settings row.

type EndpointResolver

type EndpointResolver interface {
	LookupEndpoint(ctx context.Context, endpointID string) (tenantstripe.EndpointLookup, error)
}

EndpointResolver is the narrow surface the webhook handler needs from tenantstripe.Service. Exists so the handler can be tested without a DB.

type ExternalRefundRecorder added in v0.9.2

type ExternalRefundRecorder interface {
	RecordStripeRefund(ctx context.Context, tenantID string, snap domain.StripeRefundSnapshot) (domain.StripeRefundRecordResult, error)
}

ExternalRefundRecorder records a refund made in Stripe outside Hardcount on a Hardcount payment (ADR-134): as an issued credit note whose refund is already done, or flagged for the operator, with payment.refunded_in_stripe queued in the same transaction. It also moves the refund status of a credit note that already holds the refund id. Returns errs.ErrNotFound when no Hardcount invoice holds the refund's PaymentIntent (a charge the tenant made outside Hardcount); any other error is transient. payment imports nothing from creditnote; creditnote.Service satisfies it.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(stripe *Stripe, endpoints EndpointResolver) *Handler

NewHandler wires the Stripe webhook receiver. Credentials (signing secret, tenant id, livemode) are resolved per request via the endpoint id embedded in the URL path — there is no operator-level secret: each tenant registers their own webhook endpoint in their own Stripe dashboard pointing at /v1/webhooks/stripe/{endpoint_id}, where endpoint_id is the stripe_provider_credentials.id (hc_spc_XXX) Hardcount handed them when they connected. Moving secrets off env vars is the whole point of the per- tenant model (see migration 0032).

func (*Handler) Routes

func (h *Handler) Routes() chi.Router

type HostedSessionLedger

type HostedSessionLedger interface {
	ListHostedToReconcile(ctx context.Context, checkedBefore time.Time, limit int) ([]CheckoutClaim, error)
	MarkSessionCompleted(ctx context.Context, tenantID, claimID string) error
	MarkExpired(ctx context.Context, tenantID, claimID string) error
	TouchReconcile(ctx context.Context, tenantID, claimID string) error
}

HostedSessionLedger is the slice of the checkout-session ledger the hosted sweep needs. *CheckoutSessionStore implements it.

type InvoiceUpdater

type InvoiceUpdater interface {
	StampChargeOutcome(ctx context.Context, tenantID, id string, attemptSeq int64, paymentStatus domain.InvoicePaymentStatus, stripePaymentIntentID, lastPaymentError string) (domain.Invoice, bool, error)
	// StampBelowMinimum records Stripe's "below the minimum charge" refusal
	// (domain.ErrBelowMinimumCharge): payment_status 'pending', the
	// auto-charge queue cleared, below_minimum_at and Stripe's sentence, under
	// the same seq CAS as StampChargeOutcome.
	StampBelowMinimum(ctx context.Context, tenantID, id string, attemptSeq int64, lastPaymentError string) (domain.Invoice, bool, error)
	UpdateStatus(ctx context.Context, tenantID, id string, status domain.InvoiceStatus) (domain.Invoice, error)
	MarkPaid(ctx context.Context, tenantID, id string, stripePaymentIntentID string, paidAt time.Time) (domain.Invoice, error)
	// MarkPaidReportingTransition is MarkPaid plus a `transitioned` flag —
	// true only when THIS call moved the invoice into paid (false on the
	// already-paid no-op). SettleSucceeded gates its post-paid side-effects
	// on it so a concurrent redelivery of the same charge doesn't double-
	// fire the receipt email / payment.succeeded event.
	MarkPaidReportingTransition(ctx context.Context, tenantID, id string, stripePaymentIntentID string, paidAt time.Time) (domain.Invoice, bool, error)
	// MarkPaidCardSettlementTransition is MarkPaidReportingTransition for the
	// card path: it also enqueues payment.succeeded in the SAME tx as the
	// paid-flip, so that event (the only one bearing the Stripe payment_intent_id)
	// is crash-safe instead of fire-and-forget post-commit. SettleSucceeded uses
	// this; non-card settlement paths keep MarkPaidReportingTransition.
	MarkPaidCardSettlementTransition(ctx context.Context, tenantID, id string, stripePaymentIntentID string, paidAt time.Time, then func(tx *sql.Tx, fresh domain.Invoice) error) (domain.Invoice, bool, error)
	// MarkPaymentFailedReportingTransition records one report that a
	// PaymentIntent failed. It moves the invoice only for the attempt the
	// invoice is waiting on, and reports whether this was the first notice
	// for that PaymentIntent, so the charge response, a webhook redelivery
	// and the reconciler notify once between them.
	MarkPaymentFailedReportingTransition(ctx context.Context, tenantID, id string, report domain.PaymentFailureReport, then func(tx *sql.Tx, fresh domain.Invoice) error) (domain.Invoice, domain.PaymentFailureResult, error)
	// SetPaymentCard stamps the card brand + last4 used to settle
	// an invoice. Optional — empty values render no sub-line in
	// the timeline. Called by handlePaymentSucceeded after MarkPaid
	// lands. ADR-020.
	SetPaymentCard(ctx context.Context, tenantID, id, brand, last4 string) error
	GetByStripePaymentIntentID(ctx context.Context, tenantID, stripePaymentIntentID string) (domain.Invoice, error)
	Get(ctx context.Context, tenantID, id string) (domain.Invoice, error)
	// RecordChargeAttempt writes/upserts one charge-attempt fact
	// (ADR-102): inserted at PI-create time by the charge chokepoint,
	// outcome-resolved by the settle paths keyed on the PI. Best-effort
	// at every call site — the timeline's precedence chain falls back
	// to the webhook row when the attempt row is absent, so a lost
	// write degrades display, never money.
	RecordChargeAttempt(ctx context.Context, tenantID string, a domain.InvoiceChargeAttempt) error
	// ReleaseChargeHold frees the charge hold the caller's claim took,
	// comparing its token (ADR-127). The chokepoint calls it on DEFINITIVE
	// outcomes (Stripe answered: declined, or settled) — the round-trip is
	// complete, so no charge is in flight and holding it adds no protection
	// — and when nothing was sent: its re-check refused, the breaker was
	// open, or the credentials could not be read. Unclear outcomes (unknown
	// / timeout / still-processing / 429) never release: the call may have
	// reached Stripe, and the stale-hold sweep asks Stripe before anything
	// charges the invoice again. Found by the D1 walk: a declined dunning
	// retry held the hold 5 wall-minutes, starving every later same-advance
	// retry in test-clock catchup ("dunning catchup loop made no progress").
	ReleaseChargeHold(ctx context.Context, tenantID, id string, hold domain.ChargeHold) error
	// ConfirmChargeHold is the re-check right before a charge is sent: the
	// caller's hold is still its own with domain.ChargeSendMargin left, the
	// charge counter is unchanged, and the invoice is still finalized and
	// unpaid (ADR-127).
	ConfirmChargeHold(ctx context.Context, tenantID, id string, hold domain.ChargeHold, attemptSeq int64) (bool, error)
}

InvoiceUpdater updates invoice payment status.

type LiveStripeClient

type LiveStripeClient struct {
	// contains filtered or unexported fields
}

LiveStripeClient wraps the Stripe SDK for PaymentIntent operations. Despite the "Live" in the name, it handles both live and test modes — it selects the underlying per-mode client from clients.ForCtx(ctx) on each call. Implements the StripeClient interface used by the payment adapter.

func NewLiveStripeClient

func NewLiveStripeClient(clients *StripeClients) *LiveStripeClient

NewLiveStripeClient creates a client from the mode-aware StripeClients bundle. Returns nil if clients is nil or has no configured modes.

func (*LiveStripeClient) CancelPaymentIntent

func (c *LiveStripeClient) CancelPaymentIntent(ctx context.Context, paymentIntentID string) error

func (*LiveStripeClient) CreatePaymentIntent

func (c *LiveStripeClient) CreatePaymentIntent(ctx context.Context, params PaymentIntentParams) (PaymentIntentResult, error)

func (*LiveStripeClient) FetchCardDetails

func (c *LiveStripeClient) FetchCardDetails(ctx context.Context, stripeCustomerID string) (CardDetails, error)

func (*LiveStripeClient) FetchCardForPaymentIntent

func (c *LiveStripeClient) FetchCardForPaymentIntent(ctx context.Context, paymentIntentID string) (CardDetails, error)

FetchCardForPaymentIntent retrieves the card actually charged on a specific PaymentIntent. Unlike FetchCardDetails (which returns the newest card on the Stripe customer), this works for one-off Checkout payments where the customer didn't save the PM — Stripe still creates an ephemeral PaymentMethod object for the charge that stays accessible through the PI's `payment_method` field. ADR-020.

func (*LiveStripeClient) GetCheckoutSession

func (c *LiveStripeClient) GetCheckoutSession(ctx context.Context, sessionID string) (CheckoutSessionResult, error)

GetCheckoutSession reads a hosted Checkout Session's outcome (the hosted sweep, reconciler_hosted.go).

func (*LiveStripeClient) GetPaymentIntent

func (c *LiveStripeClient) GetPaymentIntent(ctx context.Context, paymentIntentID string) (PaymentIntentResult, error)

GetPaymentIntent fetches the current state of a PaymentIntent. Used by the reconciler to resolve PaymentUnknown invoices — Stripe is the source of truth for whether a charge actually succeeded.

func (*LiveStripeClient) ListPaymentIntentsForCustomer

func (c *LiveStripeClient) ListPaymentIntentsForCustomer(ctx context.Context, stripeCustomerID string, createdGTE time.Time) ([]PaymentIntentResult, error)

ListPaymentIntentsForCustomer is the stale-hold sweep's read (ADR-127): every PaymentIntent of the Stripe customer created at or after createdGTE, each with its hardcount_invoice_id, status, captured amount and whether its latest charge was refunded in full (expand[]=data.latest_charge).

Why List and not Search (Stripe's docs, fetched 2026-10-19): List is the read-after-write API — "Don't use search for read-after-write flows… use the various list APIs… These APIs aren't subject to the availability delays" — and it is offered in every country, while Search "isn't available to businesses in India". The sweep reads "no PaymentIntent for this invoice" as "Stripe never received the charge", which only a consistent read supports.

An error on any page fails the whole read: a partial list is never returned, because a missing page could hold the payment. Errors are typed for the sweep: ErrStripeNotConfigured, ErrStripeAuthFailed (401, 403) and ErrStripeCustomerMissing (resource_missing on the customer) will not succeed on retry; anything else (5xx, 429, network, unreadable credentials) may, and a read Stripe never answered (network, time limit) is also ErrStripeUnreachable.

type PaymentAnomalyRecorder

type PaymentAnomalyRecorder interface {
	RecordPaymentAnomaly(ctx context.Context, tenantID, invoiceID, kind, paymentIntentID string, capturedCents int64) error
}

PaymentAnomalyRecorder persists the durable payment-anomaly marker the dashboard attention classifier reads (ADR-068). Implemented by *invoice.PostgresStore; wired via SetAnomalyRecorder in router.go.

type PaymentError

type PaymentError struct {
	Message         string
	DeclineCode     string // why the card was refused (insufficient_funds, lost_card, …): see declineCodeOf
	PaymentIntentID string // set when Stripe returned a PI object alongside the error
	Unknown         bool
	// CardMessage is Stripe's message when the error is a card error, the
	// one kind of message Stripe says can be shown to the customer
	// (cardErrorMessage); empty otherwise.
	CardMessage string
}

PaymentError categorises a failed PaymentIntent attempt. Unknown=true means the request's outcome could not be determined from the response (5xx, network drop, timeout) — callers must NOT treat this as a decline, because Stripe may have processed the charge server-side. A reconciler resolves these by querying Stripe after a cool-off window.

func (*PaymentError) Error

func (e *PaymentError) Error() string

func (*PaymentError) OperatorErrorCode

func (e *PaymentError) OperatorErrorCode() string

OperatorErrorCode gives an unknown outcome its own wire code. Under the shared provider_error a caller could not tell "Stripe refused" (nothing was charged) from "no answer" (the card may have been charged), and the dashboard titled both "Couldn't charge".

func (*PaymentError) OperatorSafeMessage

func (e *PaymentError) OperatorSafeMessage() string

OperatorSafeMessage implements respond.SafeMessageError so the boundary sanitizer (respond.FromError) surfaces a curated message instead of falling through to "Internal error". For card declines we look up the typed decline_code in a curated map sourced from Stripe's docs (decline_codes.go) — gives operators readable English ("The card has been reported lost…") rather than the awkward title-cased SDK code ("Lost card."). Unknown codes fall back to title-case so new Stripe codes don't break the path. For non-decline errors we return a category-only message so raw Stripe SDK strings (idempotency conflicts, validation errors) never reach the operator UI verbatim. ADR-026.

type PaymentFailure

type PaymentFailure struct {
	PaymentIntentID string
	Message         string
	// Purpose is the PaymentIntent's hardcount_purpose metadata. A dunning
	// retry skips the generic customer email (dunning sends its own per
	// attempt); a hosted Checkout attempt never moves the invoice.
	Purpose string
	// ChargedAtSeq is set only by the charge call reporting its own attempt:
	// the charge_attempt_seq it charged with (see
	// domain.PaymentFailureReport).
	ChargedAtSeq *int64
	// DeclineCode is Stripe's decline_code and PaymentMethodID the card it
	// declined, when the source knows them: the charge call from its own
	// error, the webhook and the reconciler from the PaymentIntent's
	// last_payment_error. They land on the attempt row with the failure
	// (domain.PaymentFailureReport), where a dunning retry reads them.
	DeclineCode     string
	PaymentMethodID string
	// CardMessage is Stripe's message for a card error, when the source has
	// one (cardErrorMessage): the reason the customer's payment-failed email
	// shows. Message is the invoice's text, and can be Hardcount's own
	// ("reconciled: requires_payment_method", "payment failed") or Stripe's
	// developer text for another error type, so it is never emailed.
	CardMessage string
}

PaymentFailure is one report that a PaymentIntent failed, as the three sources that learn it hand it to SettleFailed: the charge call's own decline (SourceChargeResponse), the payment_intent.payment_failed webhook, and the reconciler.

type PaymentIntentParams

type PaymentIntentParams struct {
	AmountCents int64
	Currency    string
	CustomerID  string // Stripe customer ID
	// PaymentMethodID is the Stripe PaymentMethod to charge, resolved by
	// the caller from Hardcount's payment_methods table (the single source of
	// truth for the customer's default card). Required: the client charges
	// this exact PM and never asks Stripe to pick one. Empty → loud failure.
	PaymentMethodID string
	Description     string
	IdempotencyKey  string
	Metadata        map[string]string
}

type PaymentIntentResult

type PaymentIntentResult struct {
	ID           string
	Status       string
	ClientSecret string
	// CreatedAt is the PI's Stripe-side creation instant (unix seconds).
	// Populated by the List read, so the stale-hold sweep orders the payments
	// it finds (oldest succeeded first, newest processing adopted) on
	// provider truth, not result order. Zero when unset.
	CreatedAt int64
	// Purpose is the hardcount_purpose PI metadata (e.g. "dunning_retry",
	// "hosted_invoice_pay"). Populated by GetPaymentIntent so the reconciler
	// can replicate the webhook's customer-email suppression when it recovers a
	// failure (ADR-049 Phase 2). Empty for the create response / when unset.
	Purpose string
	// AmountReceivedCents is the amount Stripe actually captured. Populated
	// by GetPaymentIntent so the reconciler's SettleSucceeded carries the
	// real captured figure — it passed a literal 0 pre-2026-07-06, which
	// structurally disabled the ADR-068 payment.amount_mismatch alarm on
	// the webhook-drop backstop path (the settle skips the truth-check
	// when capturedCents == 0).
	AmountReceivedCents int64
	// AnchorAt is the charge's CONTRACTED simulated instant, read back from
	// the PI's hardcount_anchor_at metadata. It exists for the same reason the
	// webhook path reads that key: SettleSucceeded's invoice-pin binding
	// resolves the clock's CURRENT frozen_time, so a settle that lands after
	// an advance stamps paid_at on the advance target rather than the instant
	// the charge actually fired.
	//
	// The reconciler is the THIRD settle path and was the only one without
	// it — which is backwards, because it runs precisely when the webhook
	// that carries the anchor was dropped. Same charge, same clock, and
	// paid_at differed by however far the clock had moved, purely on whether
	// the webhook landed. Zero for wall-clock charges, which carry no anchor.
	AnchorAt time.Time
	// DeclineCode and PaymentMethodID are the PaymentIntent's
	// last_payment_error decline code (declineCodeOf) and payment_method.id,
	// populated by GetPaymentIntent. The reconciler passes them on when it records a
	// failure, as the webhook does, so a hard decline it is the first to
	// learn of still stops dunning from charging that card (#966).
	DeclineCode     string
	PaymentMethodID string
	// CardMessage is last_payment_error's message when it is a card error
	// (cardErrorMessage), for the customer's payment-failed email.
	CardMessage string
	// InvoiceID is the hardcount_invoice_id metadata every Hardcount PaymentIntent
	// carries (the off-session charge and the hosted page alike). The
	// stale-hold sweep matches on it. Populated by the read paths.
	InvoiceID string
	// FullyRefunded is set when the PaymentIntent's latest charge was
	// refunded in full (list with expand[]=data.latest_charge). The
	// stale-hold sweep does not count such a payment as paying the invoice.
	FullyRefunded bool
}

type PaymentMethodAttacher

type PaymentMethodAttacher interface {
	AttachForWebhook(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, makeDefault bool) (*domain.PaymentMethodView, error)
}

PaymentMethodAttacher persists a PM row after a Stripe setup_intent succeeds. Optional — if nil, setup_intent.succeeded events are logged and ack'd but no payment_methods row is created. In practice the router always wires paymentmethods.Service here.

makeDefault makes the card the customer's default, the card Hardcount charges next: set for a card saved through a Hardcount setup flow (ADR-021). Without it the store's rule decides (the first card, or one replacing a default the bank refused for good, becomes the default; any other is added beside).

The method name is AttachForWebhook (not AttachFromSetupIntent) so paymentmethods.Service can keep its richer AttachFromSetupIntent method — returning (PaymentMethod, error) — for tests and direct callers, while this package imports nothing from paymentmethods. It returns the card as the API shows it, which payment_method.* carries, or nil when the card was already removed and stays removed (a late event).

type PaymentSetupStore

type PaymentSetupStore interface {
	UpsertPaymentSetup(ctx context.Context, tenantID string, ps domain.CustomerPaymentSetup) (domain.CustomerPaymentSetup, error)
	// UpsertPaymentSetupAudited runs the caller-supplied audit emission on
	// the same tx as the persisted mapping write (ADR-090) — used by the
	// checkout.session.completed flip so the webhook's only durable
	// mutation carries its evidence atomically.
	UpsertPaymentSetupAudited(ctx context.Context, tenantID string, ps domain.CustomerPaymentSetup, emit func(tx *sql.Tx) error) (domain.CustomerPaymentSetup, error)
	GetPaymentSetup(ctx context.Context, tenantID, customerID string) (domain.CustomerPaymentSetup, error)
}

PaymentSetupStore persists Stripe customer/payment method data.

type PaymentUpdateToken

type PaymentUpdateToken struct {
	ID         string
	TenantID   string
	CustomerID string
	InvoiceID  string
	// Livemode is the mode of the referenced invoice, resolved at
	// validate-time via JOIN. Carrying it on the validated token lets
	// the public handler open a properly-scoped TxTenant for the
	// follow-on invoice / customer reads — RLS stays as defense-in-
	// depth. Without this, the handler would have to either bypass
	// RLS (loose) or do a separate livemode lookup (extra round-trip
	// + chicken-and-egg with RLS).
	Livemode  bool
	ExpiresAt time.Time
}

type PostgresWebhookStore

type PostgresWebhookStore struct {
	// contains filtered or unexported fields
}

PostgresWebhookStore persists Stripe webhook events for audit trail.

func NewPostgresWebhookStore

func NewPostgresWebhookStore(db *postgres.DB) *PostgresWebhookStore

func (*PostgresWebhookStore) IngestEvent

func (*PostgresWebhookStore) ListByInvoice

func (s *PostgresWebhookStore) ListByInvoice(ctx context.Context, tenantID, invoiceID string) ([]domain.StripeWebhookEvent, error)

ListByInvoice returns all webhook events for an invoice, ordered chronologically.

func (*PostgresWebhookStore) WasProcessed

func (s *PostgresWebhookStore) WasProcessed(ctx context.Context, tenantID, stripeEventID string) (bool, error)

WasProcessed reports whether an event with this stripe_event_id has already been ingested for the tenant+livemode. Read-only idempotency pre-check used by HandleWebhook before running side-effects; the dedup row itself is written by IngestEvent only after processing succeeds, so "row present" implies "side-effect committed."

The (tenant_id, livemode, stripe_event_id) tuple matches IngestEvent's ON CONFLICT target, so this check sees exactly the rows that would block an insert. A concurrent redelivery that passes this read and races into IngestEvent is still de-duplicated by the ON CONFLICT DO NOTHING there; double-processing is safe because the side-effects are idempotent.

type PublicPaymentCustomerReader

type PublicPaymentCustomerReader interface {
	Get(ctx context.Context, tenantID, id string) (domain.Customer, error)
}

PublicPaymentCustomerReader is the narrow hook the public handler uses to fetch a customer with PII fields decrypted. The customer package owns the encrypt-at-rest wrapper around display_name / email; reading through this interface (instead of joining the customers table directly) keeps decryption centralised and stops the public payment page from rendering raw `enc:…` ciphertext.

type PublicPaymentHandler

type PublicPaymentHandler struct {
	// contains filtered or unexported fields
}

PublicPaymentHandler serves tokenized payment update endpoints. These routes require NO auth — the token itself is the credential.

Mode routing: these endpoints are anonymous by design, so there's no API-key livemode on the incoming request. The token's referenced invoice determines the mode — Token.Validate JOINs invoices to resolve livemode in the same query, so the validated token already carries everything we need to open a properly-scoped TxTenant for follow-on reads. RLS stays as defense-in-depth past the token gate.

func NewPublicPaymentHandler

func NewPublicPaymentHandler(tokens *TokenService, db *postgres.DB, clients *StripeClients, customers PublicPaymentCustomerReader, ensurer StripeCustomerEnsurer, returnURL string) *PublicPaymentHandler

func (*PublicPaymentHandler) Routes

func (h *PublicPaymentHandler) Routes() chi.Router

func (*PublicPaymentHandler) SetAuditLogger

func (h *PublicPaymentHandler) SetAuditLogger(a AuditEmitter)

SetAuditLogger wires ADR-090 in-tx emission for the token consume/restore pair — the public payment-update flow's durable mutations.

type ReconcileInvoiceStore

type ReconcileInvoiceStore interface {
	ListUnknownPayments(ctx context.Context, olderThan time.Time, limit int) ([]domain.Invoice, error)
	// ListProcessingPayments returns invoices stuck in payment_status
	// 'processing' older than the (longer) processing cool-off — the dropped-
	// webhook backstop (ADR-049 Phase 2). A healthy card PI resolves in seconds
	// via webhook and async methods legitimately sit in processing for days, so
	// this window is much longer than the unknown one to keep the webhook
	// winning the common race.
	ListProcessingPayments(ctx context.Context, olderThan time.Time, limit int) ([]domain.Invoice, error)
	// Get re-reads an invoice fresh immediately before settling, so a webhook
	// that won the race during the GetPaymentIntent round-trip is observed
	// (the snapshot from the sweep list may be stale).
	Get(ctx context.Context, tenantID, id string) (domain.Invoice, error)
	// RecordProviderSync stamps the provider's verbatim PaymentIntent status
	// and the moment we observed it, for the non-terminal case this sweep
	// cannot settle. It is what makes the queue rotate rather than jam, and
	// what turns a long-running payment from silent into diagnosable
	// (migration 0167).
	RecordProviderSync(ctx context.Context, tenantID, id, providerStatus string) error
	MarkPaymentFailedReportingTransition(ctx context.Context, tenantID, id string, report domain.PaymentFailureReport, then func(tx *sql.Tx, fresh domain.Invoice) error) (domain.Invoice, domain.PaymentFailureResult, error)
	MarkPaid(ctx context.Context, tenantID, id string, stripePaymentIntentID string, paidAt time.Time) (domain.Invoice, error)
	// The stale-hold sweep's reads and writes (ADR-127). Required, not
	// optional: a stale hold blocks every charge and the irreversible
	// actions, and this sweep is the only thing that clears one or finishes a
	// parked invoice.
	StaleChargeHoldStore
}

ReconcileInvoiceStore is the narrow interface the reconciler needs from the invoice store. Kept separate from InvoiceUpdater so the reconciler can be wired independently of the hot charge / webhook paths.

type Reconciler

type Reconciler struct {
	// contains filtered or unexported fields
}

Reconciler resolves invoices stuck in PaymentUnknown by asking Stripe for the authoritative PaymentIntent state. An invoice lands in PaymentUnknown when ChargeInvoice returns an ambiguous error (5xx / timeout / connection reset) — Stripe might have processed the charge server-side, so we must not blindly retry.

Cool-off window: unknown invoices younger than `olderThan` are skipped to let the webhook (payment_intent.succeeded / failed) arrive first, which resolves the state without an extra API call.

func NewReconciler

func NewReconciler(client StripeClient, invoices ReconcileInvoiceStore, olderThan time.Duration) *Reconciler

NewReconciler constructs a Reconciler. If olderThan <= 0, defaults to 60s (the 'unknown' cool-off). The stale-'processing' cool-off defaults to 30m; override with SetProcessingReconcileAfter.

func (*Reconciler) Run

func (r *Reconciler) Run(ctx context.Context, limit int) (int, []error)

Run reconciles unresolved payments against Stripe:

  • stale charge holds (ADR-127, reconciler_stale_hold.go): a charge whose result was lost, and a parked invoice (an unclear answer that named no PaymentIntent). First, so an invoice it clears is charged by the same tick's auto-charge sweep, and a payment it finds is recorded before anything else looks at the invoice;
  • 'unknown' (ambiguous charge outcomes) past the short cool-off,
  • stale 'processing' (the dropped-webhook backstop, ADR-049 Phase 2) past the longer processing cool-off, and
  • finished hosted Checkout sessions (reconciler_hosted.go).

All route recovered terminals through the settler, so a backstop-recovered settlement fires the full side-effects. Returns the number resolved (succeeded or failed) and any per-invoice errors.

A row whose check panics is stamped like a failed check (guardRow), and the rows and sweeps after it still run. The first such panic is raised again only after the last sweep, so the billing tick still ends as panicked and pages. Raised sooner, it would stop the sweeps after it on every tick: the stale-hold check of an 'unknown' invoice that names its PaymentIntent is never stamped, so it comes back first.

func (*Reconciler) SetBreaker

func (r *Reconciler) SetBreaker(b *breaker.Breaker)

SetBreaker wires the same global circuit breaker used by ChargeInvoice. When the breaker is open, the reconciler skips unresolved invoices this tick rather than piling Stripe reads onto an already-sick service; the next tick after cooldown picks them up.

func (*Reconciler) SetHostedSessions

func (r *Reconciler) SetHostedSessions(ledger HostedSessionLedger, reader CheckoutSessionReader, cards CheckoutCardRecorder)

SetHostedSessions wires the hosted-page sweep. Unwired (tests, Stripe not configured), the sweep does nothing.

func (*Reconciler) SetProcessingReconcileAfter

func (r *Reconciler) SetProcessingReconcileAfter(d time.Duration)

SetProcessingReconcileAfter overrides the stale-'processing' cool-off. The caller picks it relative to the scheduler tick so the webhook wins the common race: long enough that a healthy card PI always resolves via webhook first, short enough that a dropped webhook resolves within an acceptable window.

func (*Reconciler) SetResolver

func (r *Reconciler) SetResolver(res clock.Resolver)

SetResolver wires the clock resolver so `paid_at` writes land in simulated time on clock-pinned invoices. Without this the reconciler would call MarkPaid with wall-clock — leaking wall-clock onto an invoice whose every other timestamp (issued_at, due_at, billing period) lives on the simulated timeline. Same shape as payment.Stripe.SetResolver + dunning.Handler.SetResolver.

func (*Reconciler) SetSettler

func (r *Reconciler) SetSettler(s Settler)

SetSettler wires the shared settlement primitive (production: *Stripe). When unset, recovered terminals fall back to legacy bare writes (test-only).

type RefundError

type RefundError struct {
	Message string
	Unknown bool
	NotRun  bool
}

RefundError is a refund create that returned no refund. Unknown is the split classifyStripeError makes for charges (#965):

  • true: Stripe's answer was lost or unclear (a timeout, a network error, a Stripe 5xx, a key already in use, a rate limit). Stripe may have made the refund. Stripe calls a 5xx result indeterminate (https://docs.stripe.com/error-low-level#server-errors).
  • false: Stripe refused (card_error, invalid_request_error, a 401 or 403), so no refund was made.

NotRun narrows false: Stripe ran nothing for this request. It refused the API key before running it (a 401 invalid key, a 403 key without refund permission), or Hardcount sent nothing (Stripe not configured for the mode). Stripe saves no result for such a request: "Errors that occur before execution begins, such as invalid parameters, an invalid API key or rate limiting, don't cache a result" (https://docs.stripe.com/error-low-level#content-errors). So when Retry refund resends an unclear request, a NotRun error says nothing about that earlier request.

The credit-note service reads both through OutcomeUnknown and RequestNotRun, because it may not import this package.

func (*RefundError) Error

func (e *RefundError) Error() string

func (*RefundError) OperatorErrorCode

func (e *RefundError) OperatorErrorCode() string

OperatorErrorCode shares the charge path's code for "no clear answer", so an API caller and the dashboard treat both the same way.

func (*RefundError) OperatorSafeMessage

func (e *RefundError) OperatorSafeMessage() string

OperatorSafeMessage implements respond.SafeMessageError (ADR-026): a curated sentence, never Stripe's raw text.

func (*RefundError) OutcomeUnknown

func (e *RefundError) OutcomeUnknown() bool

OutcomeUnknown reports whether Stripe may have made the refund.

func (*RefundError) RequestNotRun

func (e *RefundError) RequestNotRun() bool

RequestNotRun reports whether Stripe ran nothing for this request.

type RefundStatusUpdater

type RefundStatusUpdater interface {
	// failureReason is Stripe's failure_reason enum (empty unless failed) —
	// persisted with the transition so refund-failure forensics survive
	// beyond process logs.
	ApplyRefundWebhook(ctx context.Context, tenantID, stripeRefundID string, status domain.RefundStatus, failureReason string) error
}

RefundStatusUpdater applies an async refund-webhook status (already mapped to a Hardcount refund_status) to the credit note carrying stripeRefundID, monotonically. Returns errs.ErrNotFound when no credit note matches (foreign/dashboard refund, or the row hasn't committed yet). Optional — nil logs+acks refund events. payment imports nothing from creditnote; creditnote.Service satisfies this.

type SettlementSource

type SettlementSource string

SettlementSource tags which entry point discovered a payment's terminal status, for logs/metrics. The settlement side-effects are identical regardless of source — that is the whole point of the primitive (ADR-049): a dropped-webhook recovery is byte-identical to the webhook it replaces.

const (
	SourceWebhook        SettlementSource = "webhook"         // inbound payment_intent.* event
	SourceReconciler     SettlementSource = "reconciler"      // GetPaymentIntent backstop sweep (Phase 2)
	SourceChargeResponse SettlementSource = "charge_response" // synchronous Confirm:true create response (Phase 3)
	SourceManual         SettlementSource = "manual"          // operator on-demand "Check provider" (Phase 4)
)

type Settler

type Settler interface {
	SettleSucceeded(ctx context.Context, tenantID string, inv domain.Invoice, paymentIntentID string, capturedCents int64, source SettlementSource) error
	SettleFailed(ctx context.Context, tenantID string, inv domain.Invoice, f PaymentFailure, source SettlementSource) error
}

Settler is the shared payment-settlement primitive (ADR-049): it owns the complete terminal-transition side-effects (mark + sim-time, card stamp, payment.succeeded/failed event, dunning, customer email) plus the out-of-order guard. Implemented by *Stripe. The reconciler routes its recovered terminals through it so a dropped-webhook recovery fires the SAME consequences as the webhook — closing the silent-under-collection gap.

Optional (nil-tolerant): when unwired — narrow unit tests only; production always wires it via SetSettler — the reconciler falls back to the legacy bare MarkPaid / MarkPaymentFailedReportingTransition writes (no dunning/email). The fallback exists solely so status-discovery tests need not construct a full Stripe adapter.

type StaleChargeHoldStore

type StaleChargeHoldStore interface {
	ListStaleChargeHolds(ctx context.Context, limit int, skip []string) ([]domain.StaleChargeHold, error)
	ClearStaleChargeHold(ctx context.Context, tenantID, id string, hold time.Time, attemptSeq int64, moveSeq bool) (bool, error)
	MarkStaleHoldChecked(ctx context.Context, tenantID, id string) error
	StampChargeOutcome(ctx context.Context, tenantID, id string, attemptSeq int64, paymentStatus domain.InvoicePaymentStatus, stripePaymentIntentID, lastPaymentError string) (domain.Invoice, bool, error)
	UnparkAfterNoPayment(ctx context.Context, tenantID, id string, hold time.Time, attemptSeq int64) (domain.InvoicePaymentStatus, bool, error)
}

StaleChargeHoldStore is what the stale-hold sweep needs from the invoice store (ADR-127). Part of ReconcileInvoiceStore, so the sweep cannot be left unwired: without it a stale hold, which every claim and the irreversible actions refuse, would never clear.

type Stripe

type Stripe struct {
	// contains filtered or unexported fields
}

Stripe is the payment adapter. It creates PaymentIntents for finalized invoices and processes webhook events to update invoice payment status.

This is NOT an abstract "payment provider" interface. Hardcount is Stripe-native. If we ever support another provider, we'll refactor — not speculate now.

func NewStripe

func NewStripe(client StripeClient, invoices InvoiceUpdater, webhooks WebhookStore, paymentSetups PaymentSetupStore, dunning ...DunningStarter) *Stripe

func (*Stripe) ChargeInvoice

func (s *Stripe) ChargeInvoice(ctx context.Context, tenantID string, inv domain.Invoice, hold domain.ChargeHold, stripeCustomerID, stripePaymentMethodID string) (domain.Invoice, error)

ChargeInvoice creates a Stripe PaymentIntent for a finalized invoice. The invoice must have a customer with a Stripe customer ID already set up. hold is the charge hold the caller's claim returned (ADR-127): the charge re-checks it right before sending and sends nothing when it no longer holds.

func (*Stripe) ChargeInvoiceForDunningRetry

func (s *Stripe) ChargeInvoiceForDunningRetry(ctx context.Context, tenantID string, inv domain.Invoice, hold domain.ChargeHold, stripeCustomerID, stripePaymentMethodID string) (domain.Invoice, error)

ChargeInvoiceForDunningRetry charges an invoice as part of a dunning retry attempt. Identical to ChargeInvoice except the resulting PaymentIntent carries hardcount_purpose=dunning_retry metadata, so every source that reports its failure — this call's own decline, the payment_intent.payment_failed webhook, the reconciler — skips the generic payment-failed email (failureEmailSuppressed): dunning sends its own per-attempt warning / escalation inline from processRun / exhaustRun.

Exposed as a separate method rather than a variadic option so the engine's InvoiceCharger interface stays narrow (default-mode only) and the cross-domain import that a shared options type would force (billing → payment) is avoided per the per-domain-isolation rule in CLAUDE.md.

func (*Stripe) ChargeInvoiceNow

func (s *Stripe) ChargeInvoiceNow(ctx context.Context, tenantID string, inv domain.Invoice, hold domain.ChargeHold, stripeCustomerID, stripePaymentMethodID string) (domain.Invoice, error)

ChargeInvoiceNow is the charge someone asked for: "Charge now" in the dashboard, or POST /v1/invoices/{id}/collect. It charges exactly as ChargeInvoice does: the same PaymentIntent metadata and the same idempotency key, so Stripe sees no difference. Only the attempt row's trigger differs (charge_now, ADR-128 PR 6): it answers "why was this charged?", and the row's actor says who asked.

func (*Stripe) ExpireCheckoutSessions

func (s *Stripe) ExpireCheckoutSessions(ctx context.Context, tenantID string, inv domain.Invoice)

ExpireCheckoutSessions is StopCollection's first leg on its own, for a write-off: a written-off invoice must not stay payable on a Checkout page the customer still has open (ADR-110 closes self-service payment on one). The write-off's transaction already closed Hardcount's claims; this expires the sessions at Stripe. Best-effort, as for a void: ExpiresAt (at most an hour) bounds a session whose expire call fails, and a payment that still lands settles the written-off invoice once (uncollectible -> paid). It does not cancel the PaymentIntent: a write-off records that collection failed, and money that still arrives is recorded (ADR-113).

func (*Stripe) HandleWebhook

func (s *Stripe) HandleWebhook(ctx context.Context, tenantID string, event domain.StripeWebhookEvent) error

HandleWebhook processes a Stripe webhook event and updates the corresponding invoice.

Dedup ordering (the fix): the dedup marker is written AFTER the business side-effect commits, not before. The pre-2026-06 flow committed the dedup row first (IngestEvent's own tx) and then ran the handler — so a transient handler failure left a committed dedup row, the HTTP layer ack'd 200, and Stripe's redelivery short-circuited as a duplicate. The event was silently and permanently dropped.

Now:

  1. WasProcessed is a read-only idempotency pre-check.
  2. processEvent runs the side-effect (MarkPaid / dunning / etc.).
  3. On a TRANSIENT failure we persist NO row and return the error — the HTTP handler turns that into a 5xx so Stripe redelivers and the handler re-runs. "dedup row exists" now strictly implies "side-effect committed."
  4. On success OR a PERMANENT failure (the event references an entity that isn't in our DB and never will be — errs.ErrNotFound) we IngestEvent to persist the audit row + claim the dedup slot, then ack. Acking a permanent failure is deliberate: redelivering it forever achieves nothing.

Business side-effects on these paths are idempotent (MarkPaid is a no-op on an already-paid invoice; StartDunning is UNIQUE per invoice), so a redelivery that races a slow first delivery and double-processes converges to the same state — the ON CONFLICT DO NOTHING in IngestEvent collapses the duplicate audit row.

func (*Stripe) RecordCheckoutBelowMinimum

func (s *Stripe) RecordCheckoutBelowMinimum(ctx context.Context, tenantID string, inv domain.Invoice, bm *BelowMinimumError)

RecordCheckoutBelowMinimum records Stripe refusing the hosted page's Checkout Session because the amount is below its minimum charge. For a customer with no card it is the first time Hardcount learns this, so it is recorded as a charge's refusal is: the invoice is stamped (no Pay button, the operator's notice, out of the auto-charge queue) and the payment recovery the card-less finalize started ends, so no reminder or final action follows. No charge attempt row: no charge was made. inv is the invoice as read for the Pay click; its charge_attempt_seq is the CAS.

func (*Stripe) RecordCheckoutCard

func (s *Stripe) RecordCheckoutCard(ctx context.Context, tenantID, customerID, stripeCustomerID, purpose string) error

RecordCheckoutCard records the card a finished Checkout session saved to the customer's Stripe customer (setup_future_usage, ADR-021) as the customer's payment method. Two callers: the checkout.session.completed webhook, and the reconciler's hosted sweep for a paid session whose webhooks were lost — without the sweep's call, Hardcount recorded the payment but showed "no payment method" and sent the next invoice to card-less dunning, asking for a card the customer had just given. A card already on file with the same Stripe payment method is left alone, so a webhook and the sweep both reporting one session write one audit row and one payment_method.updated event.

func (*Stripe) SetAnomalyRecorder

func (s *Stripe) SetAnomalyRecorder(r PaymentAnomalyRecorder)

SetAnomalyRecorder wires the durable anomaly marker store.

func (*Stripe) SetAuditLogger

func (s *Stripe) SetAuditLogger(a AuditEmitter)

SetAuditLogger wires in-tx audit emission for the checkout.session.completed payment-setup flip — previously that webhook's only durable mutation left no audit trail (and payment-mode+save-card had no sibling record at all).

func (*Stripe) SetBreaker

func (s *Stripe) SetBreaker(b *breaker.Breaker)

SetBreaker wires a global circuit breaker around Stripe calls. When set, ChargeInvoice short-circuits with breaker.ErrOpen if the breaker is rejecting — the Stripe call is not made, the charge hold is released, and the invoice state is left untouched so dunning treats it as "try later" without ticking attempt_count.

func (*Stripe) SetCardFetcher

func (s *Stripe) SetCardFetcher(cf CardFetcher)

SetCardFetcher configures card detail fetching from Stripe.

func (*Stripe) SetCheckoutSessionStore

func (s *Stripe) SetCheckoutSessionStore(cs *CheckoutSessionStore, clients *StripeClients)

SetCheckoutSessionStore wires the claim ledger for webhook truth-sync and the settle-time best-effort Stripe expire (ADR-068). clients resolves the mode-keyed raw Stripe client for the expire calls (the narrow StripeClient interface deliberately has no session surface).

func (*Stripe) SetCustomerResolver

func (s *Stripe) SetCustomerResolver(r CustomerByStripeIDResolver)

SetCustomerResolver wires the Stripe-customer → hardcount-customer resolver used as the setup_intent.succeeded fallback. Optional: nil leaves the handler dependent on SetupIntent metadata alone (test default).

func (*Stripe) SetDisputeRecorder

func (s *Stripe) SetDisputeRecorder(r DisputeRecorder)

SetDisputeRecorder wires the charge.dispute.* handler's store. Optional: nil logs and acknowledges dispute events (test default).

func (*Stripe) SetDunningResolver

func (s *Stripe) SetDunningResolver(d DunningResolver)

SetDunningResolver wires the resolver that closes an active dunning run when a card payment settles (SettleSucceeded). See the DunningResolver doc-comment.

func (*Stripe) SetDunningRetryFailure added in v0.9.2

func (s *Stripe) SetDunningRetryFailure(d DunningRetryFailure)

SetDunningRetryFailure wires dunning's hook for a processing retry's later failure (see DunningRetryFailure). The producer always wires it; unwired (narrow tests), such a failure is recorded on the invoice only, and the run goes on at the retry date the in-flight write scheduled.

func (*Stripe) SetEmailPaymentFailed

func (s *Stripe) SetEmailPaymentFailed(sender EmailPaymentFailed, customerEmail CustomerEmailResolver)

SetEmailPaymentFailed configures the post-decline email sender. Mirrors the dunning email path — points the customer at the hosted invoice URL where they can update PM and retry. The customer-email resolver is shared with the receipt path.

func (*Stripe) SetEmailReceipt

func (s *Stripe) SetEmailReceipt(receipt EmailReceipt, customerEmail CustomerEmailResolver)

SetEmailReceipt configures payment receipt email sending.

func (*Stripe) SetEventDispatcher

func (s *Stripe) SetEventDispatcher(events domain.EventDispatcher)

SetEventDispatcher configures outbound webhook event firing.

func (*Stripe) SetExternalRefundRecorder added in v0.9.2

func (s *Stripe) SetExternalRefundRecorder(r ExternalRefundRecorder)

SetExternalRefundRecorder wires the recorder for refunds that carry no hardcount_cn_id. Without it such a refund only reaches a credit note that holds its id, as before ADR-134 (narrow tests).

func (*Stripe) SetKeyHealth

func (s *Stripe) SetKeyHealth(k StripeKeyHealth)

SetKeyHealth wires the Settings mark for a refused key. Optional: nil leaves only the metric and the log line.

func (*Stripe) SetPaymentMethodAttacher

func (s *Stripe) SetPaymentMethodAttacher(a PaymentMethodAttacher)

SetPaymentMethodAttacher configures the handler that processes setup_intent.succeeded events.

func (*Stripe) SetRefundStatusUpdater

func (s *Stripe) SetRefundStatusUpdater(u RefundStatusUpdater)

SetRefundStatusUpdater wires the async refund-status reconciler used by the refund.* / charge.refund.updated webhook handlers.

func (*Stripe) SetResolver

func (s *Stripe) SetResolver(r clock.Resolver)

SetResolver wires the unified clock.Resolver. Webhook handlers fire in their own goroutine with no inherited ctx binding — they bind effective-now from the invoice they're processing so MarkPaid / the failed stamp / StartDunning all stamp simulated time on clock-pinned invoices. Without this, webhook-driven writes leak wall-clock back into the simulation. Optional: nil leaves binding off (test default).

func (*Stripe) SettleFailed

func (s *Stripe) SettleFailed(ctx context.Context, tenantID string, inv domain.Invoice, f PaymentFailure, source SettlementSource) error

SettleFailed records a payment failure and fires its side effects once per PaymentIntent, whichever source reports it first: the charge call's own decline, the webhook, or the reconciler. It is the failed-path twin of SettleSucceeded (ADR-049).

The store decides whether the report moves the invoice: only a report about the attempt the invoice is waiting on does (see MarkPaymentFailedReportingTransition). A late decline for an older attempt, or a decline on the hosted Checkout page, lands on its own attempt row and nothing else.

When it does move the invoice, the first report for the PaymentIntent enqueues payment.failed and the customer email in the same transaction as the failed stamp. The email is skipped for a dunning retry (dunning sends its own) and for an invoice that is no longer finalized (voided or written off during the charge). Dunning is then started — on every report that records the failure, not only the first: the first reporter's start can fail after its stamp committed, and StartDunning is idempotent by invoice (0085 UNIQUE), so a later report is a free re-drive. Test-clock invoices have no other one: the dunning_backfill reconciler skips simulated invoices.

func (*Stripe) SettleSucceeded

func (s *Stripe) SettleSucceeded(ctx context.Context, tenantID string, inv domain.Invoice, paymentIntentID string, capturedCents int64, source SettlementSource) error

SettleSucceeded transitions an invoice to PAID and fires the complete success side-effect set: bind sim-time so paid_at lands on a clock-pinned invoice's timeline, MarkPaid (zero amount_due, record PI + paid_at), stamp the charged card for the activity timeline, fire payment.succeeded, and enqueue the receipt email.

Idempotent and safe to call from any entry point (ADR-049 discover-then- settle): MarkPaid is a no-op on an already-paid invoice, and the card-stamp / event / receipt steps are best-effort (log-only) so a duplicate call — e.g. the webhook arriving after the reconciler already settled — does not fail.

This is the consolidated implementation of what handlePaymentSucceeded did inline (ADR-049 Phase 1); the webhook handler now resolves the invoice and delegates here. capturedCents is the amount Stripe actually captured (0 = unknown/legacy caller): the settle compares it against the transitioned row's amount_paid and escalates payment.amount_mismatch on drift — a Checkout session can legally pay an amount a credit note has since changed (ADR-068); silent wrong books would corrupt the refund cap.

The fast-path duplicate check compares against the CALLER's inv snapshot — the webhook and reconciler both pass freshly-read rows (documented contract); the post-transition check below uses the row RETURNED by the FOR-UPDATE transition and needs no such trust.

func (*Stripe) StopCollection

func (s *Stripe) StopCollection(ctx context.Context, tenantID string, inv domain.Invoice)

StopCollection is the void path's twin of the settle path's cleanup: an invoice that will never be collected must stop being PAYABLE at Stripe.

Order matters. Session expiry comes FIRST because Stripe REFUSES to cancel a PaymentIntent it created for a Checkout Session ("You cannot perform this action on PaymentIntents created by Checkout. Try expiring the Checkout Session instead") — so for every hosted-page attempt, PI cancel alone was a no-op that logged a warning while the session stayed live until its ExpiresAt (<=1h), leaving a voided invoice payable. Found on the FLOW D2 walk (VLX-000004): void → PI cancel refused → session still open. Expiring the session is what actually closes that window; the PI then terminates with it.

The PI cancel still runs afterwards for engine-minted PIs (auto-charge, dunning retry) — those are cancelable and have no session. Both legs are best-effort: the DB-side claim close (in the void tx) already stops OUR reuse path, ExpiresAt bounds the Stripe-side window, and the ADR-068 payment-received-on-voided-invoice anomaly remains the last backstop.

type StripeBillingSync

type StripeBillingSync struct {
	// contains filtered or unexported fields
}

StripeBillingSync syncs billing profile data to Stripe customer objects. Mode-aware: uses the live or test client based on ctx livemode.

func NewStripeBillingSync

func NewStripeBillingSync(clients *StripeClients) *StripeBillingSync

NewStripeBillingSync returns nil if clients has no configured modes. The caller then skips sync entirely rather than silently no-opping each call.

func (*StripeBillingSync) SyncBillingProfile

func (s *StripeBillingSync) SyncBillingProfile(ctx context.Context, stripeCustomerID, customerEmail string, bp domain.CustomerBillingProfile) error

SyncBillingProfile pushes the canonical billing-profile fields to the Stripe customer. customerEmail is the canonical recipient (customers.email) — the billing-profile email column was removed in migration 0100, so the email is now plumbed through as a separate argument by the caller rather than read off bp.

type StripeClient

type StripeClient interface {
	CreatePaymentIntent(ctx context.Context, params PaymentIntentParams) (PaymentIntentResult, error)
	CancelPaymentIntent(ctx context.Context, paymentIntentID string) error
	GetPaymentIntent(ctx context.Context, paymentIntentID string) (PaymentIntentResult, error)
	// ListPaymentIntentsForCustomer is the stale-hold sweep's read
	// (ADR-127): every PaymentIntent of the Stripe customer created at or
	// after createdGTE, through List — the read-after-write API, offered in
	// every country — never Search. A failure on any page fails the whole
	// read; a partial list is never returned. Errors: ErrStripeNotConfigured,
	// ErrStripeAuthFailed or ErrStripeCustomerMissing for a read that will not
	// succeed on retry, anything else for one that may.
	ListPaymentIntentsForCustomer(ctx context.Context, stripeCustomerID string, createdGTE time.Time) ([]PaymentIntentResult, error)
}

StripeClient is the interface for Stripe API calls. In production this wraps stripe-go; in tests it's a mock.

type StripeClients

type StripeClients struct {
	// contains filtered or unexported fields
}

StripeClients builds per-tenant *stripe.Client instances on demand. Each tenant brings their own Stripe keys (stored encrypted via tenantstripe); this resolver looks them up and constructs a client with the right secret.

Resolve and ResolveCtx return (nil, nil) only when the tenant has not connected Stripe for the mode; callers surface that as ErrStripeNotConfigured. Any other miss is an error.

func NewStripeClients

func NewStripeClients(fetcher StripeCredentials) *StripeClients

NewStripeClients wires the per-tenant resolver. fetcher=nil returns nil so boot code can gate Stripe-dependent components on a single `if clients != nil` check, matching the ergonomics of the previous env-var version.

func NewStripeClientsWithHTTPClient

func NewStripeClientsWithHTTPClient(fetcher StripeCredentials, hc *http.Client) *StripeClients

NewStripeClientsWithHTTPClient is NewStripeClients sending every Stripe request through hc instead of the shared 30-second client. Tests outside this package use it to answer as Stripe would, so the real client decodes and classifies the reply.

func (*StripeClients) Has

func (c *StripeClients) Has() bool

Has returns true iff a credential fetcher is wired. Used at server startup to gate Stripe-dependent components. A true return does NOT mean any specific tenant has credentials connected — only that the system CAN resolve per-tenant keys when asked.

func (*StripeClients) HasFor

func (c *StripeClients) HasFor(ctx context.Context, tenantID string, livemode bool) (bool, error)

HasFor reports whether this tenant has Stripe credentials stored for the mode. Distinct from Has(): Has() reflects "the system can look up keys"; HasFor reflects "this specific tenant has connected." It returns an error when the credentials could not be read.

func (*StripeClients) Resolve

func (c *StripeClients) Resolve(ctx context.Context, tenantID string, livemode bool) (*stripe.Client, error)

Resolve returns the Stripe client for an explicit (tenant, mode). It returns (nil, nil) when Stripe is not wired or the tenant has not connected it for the mode, and an error when the credentials could not be read.

func (*StripeClients) ResolveCtx

func (c *StripeClients) ResolveCtx(ctx context.Context) (*stripe.Client, error)

ResolveCtx is Resolve for the tenant and mode on ctx.

type StripeCredentials

type StripeCredentials interface {
	GetPlaintext(ctx context.Context, tenantID string, livemode bool) (tenantstripe.PlaintextSecrets, error)
}

StripeCredentials resolves decrypted Stripe secrets for a (tenant, mode). Implemented by *tenantstripe.Service — payment depends only on this narrow interface so the credential store can evolve independently.

type StripeCustomerEnsurer

type StripeCustomerEnsurer interface {
	EnsureStripeCustomer(ctx context.Context, tenantID, customerID string) (string, error)
}

StripeCustomerEnsurer resolves — or lazily creates — the Stripe Customer for a Hardcount customer. The public first-payment-method flow needs this: a customer setting up their first card legitimately has no Stripe Customer yet, so requiring a pre-existing customers.stripe_customer_id dead-ends exactly the case this email exists to serve. Every sibling payment-setup path (operator "Add payment method", hosted-invoice Pay) already creates it on demand via this same helper. Satisfied by paymentmethods.StripeAdapter.EnsureStripeCustomer (which is built to run on public token-authenticated requests).

type StripeKeyError

type StripeKeyError struct {
	Reason  string // StripeKeyRejected or StripeKeyNotConfigured
	Message string // Stripe's own sentence, scrubbed; empty for not_configured
}

StripeKeyError is a charge that never ran because Stripe refused the tenant's API key (401: the key is invalid or was rolled; 403: a restricted key without permission to create PaymentIntents) or because no key is connected for this mode. The key is wrong, not the card, so it is not a decline: no dunning attempt is used, the invoice is not marked failed, and no customer email carries Stripe's sentence. The operator is told instead (a metric, an ERROR line, and the Settings → Payments notice).

It wraps ErrPaymentTransient so every charge caller skips the tick unchanged. It must not be or wrap a *PaymentError: the auto-charge sweep, the dunning retry and Collect all check errors.As(*PaymentError) with Unknown=false before ErrPaymentTransient, and would count it as a decline. So ErrStripeNotConfigured, itself a PaymentError that refunds, the checkout sync and the stale-hold sweep read, is not wrapped either.

func (*StripeKeyError) Error

func (e *StripeKeyError) Error() string

func (*StripeKeyError) OperatorErrorCode

func (e *StripeKeyError) OperatorErrorCode() string

OperatorErrorCode names the fault so a caller can tell it from a decline.

func (*StripeKeyError) OperatorSafeMessage

func (e *StripeKeyError) OperatorSafeMessage() string

OperatorSafeMessage implements respond.SafeMessageError. Stripe's own sentence names the key's last characters or the missing permission; it goes to the log and the Settings notice, not to this response.

func (*StripeKeyError) Unwrap

func (e *StripeKeyError) Unwrap() error

type StripeKeyHealth

type StripeKeyHealth interface {
	MarkKeyRejected(ctx context.Context, tenantID string, livemode bool, stripeMessage string) error
	ClearKeyRejected(ctx context.Context, tenantID string, livemode bool) error
}

StripeKeyHealth records that Stripe refused a tenant's key for one mode, so Settings → Payments shows it, and clears that notice once a charge goes through with the key. Implemented by *tenantstripe.Service; wired via SetKeyHealth in router.go.

type StripeRefunder

type StripeRefunder struct {
	// contains filtered or unexported fields
}

StripeRefunder processes refunds via the Stripe API. Mode-aware: selects live/test client per ctx livemode.

func NewStripeRefunder

func NewStripeRefunder(clients *StripeClients) *StripeRefunder

func (*StripeRefunder) CreateRefund

func (r *StripeRefunder) CreateRefund(ctx context.Context, paymentIntentID string, amountCents int64, idempotencyKey, creditNoteID string) (string, domain.RefundStatus, error)

CreateRefund creates a Stripe refund for the given PaymentIntent.

`idempotencyKey` is mandatory in production — same key + same params returns the existing refund without creating a duplicate. Hardcount passes `hardcount_cn_<credit_note_id>` so that a credit-note Issue() retry after a partial failure (e.g. DB hiccup on the post-refund credit grant step) hits Stripe's cache and gets back the original refund_id, not a second refund.

Without this protection, the pre-fix shape was: Stripe refund succeeds → in-memory refund_id set → credit grant fails → function returns error → CN stays draft → operator retries → Stripe called again with no idempotency key → DUPLICATE refund → customer over- refunded (caught 2026-05-22). Returns the refund id AND Stripe's create-time status (mapped to a Hardcount refund_status). A card refund on a healthy balance returns `succeeded` synchronously; ACH/balance-constrained refunds legitimately return `pending`, whose terminal outcome (succeeded/failed) lands later via a refund webhook — so the caller must record what Stripe actually said, not a blanket success. creditNoteID stamps metadata hardcount_cn_id on the refund. That metadata is the ADOPTION key: Stripe v1 idempotency keys expire after ~24h, so the key alone cannot make a late retry converge on an earlier attempt — but a metadata-stamped refund can always be found again by FindRefundForCreditNote and adopted instead of duplicated. Every error is a *RefundError, which says whether Stripe may have made the refund anyway.

func (*StripeRefunder) FindRefundForCreditNote

func (r *StripeRefunder) FindRefundForCreditNote(ctx context.Context, paymentIntentID, creditNoteID string) (string, domain.RefundStatus, error)

FindRefundForCreditNote searches the PaymentIntent's refunds for a LIVE (succeeded/pending) refund minted for this credit note (metadata hardcount_cn_id). Returns ("", "", nil) when none exists. This is the search half of search-and-adopt (ADR-108's pattern, applied to refunds): it recovers the lost-response shapes — a create that errored on the wire after Stripe minted the refund, in either the original Issue leg (Hardcount holds no id) or a later re-drive (Hardcount still holds a dead predecessor).

Failed matches are deliberately NOT returned. Adopting a live twin is what prevents a duplicate; a failed twin is a dead prior attempt, and returning it would let a pile of dead attempts permanently shadow the create leg (adopt returns early), livelocking the retry — the finder review caught exactly that with an exclude-one-id variant. Dead attempts stay visible in the audit trail, which records every id and failure reason as it happened.

func (*StripeRefunder) GetRefund

func (r *StripeRefunder) GetRefund(ctx context.Context, refundID string) (domain.RefundStatus, string, error)

GetRefund reads a refund's CURRENT provider state. This is a plain read — unlike an idempotency-key replay of the create call, it can never return a stale saved response, which is what makes it safe to consult before a retry. The second return is Stripe's failure_reason (empty unless failed).

func (*StripeRefunder) ReadRefund added in v0.9.2

func (r *StripeRefunder) ReadRefund(ctx context.Context, refundID string) (domain.StripeRefundFacts, error)

ReadRefund reads one refund's current state at Stripe: its PaymentIntent, amount, currency, status and hardcount_cn_id metadata. The credit-note service reads it before an operator links a refund made in Stripe to a credit note (ADR-134), so a link can only name a refund that exists, on the invoice's payment, that Hardcount did not make. A status Stripe adds later is refused: the link would store a status Hardcount cannot read.

type TokenService

type TokenService struct {
	// contains filtered or unexported fields
}

func NewTokenService

func NewTokenService(db *postgres.DB) *TokenService

func (*TokenService) Cleanup

func (s *TokenService) Cleanup(ctx context.Context) (int, error)

Cleanup deletes expired tokens older than 7 days across all tenants. Runs cross-tenant by design (a background scheduler, not a per-request path), so it uses TxBypass.

func (*TokenService) Consume

func (s *TokenService) Consume(ctx context.Context, tenantID, rawToken string) (bool, error)

Consume atomically marks a token used and reports whether THIS call was the one that consumed it. The conditional UPDATE (used_at IS NULL) is a compare-and-swap: under concurrent requests for the same single-use token, exactly one gets consumed=true and may proceed; the others get false and must abort. This closes the validate→mark-used TOCTOU where two requests both passed Validate's `used_at IS NULL` read and both opened a setup-mode checkout session. Callers must consume BEFORE the side effect, not after.

The caller passes the tenantID returned by Validate so the update runs under tenant RLS.

func (*TokenService) ConsumeAudited

func (s *TokenService) ConsumeAudited(ctx context.Context, tenantID, rawToken string, emit func(tx *sql.Tx) error) (bool, error)

ConsumeAudited is Consume with an in-tx audit emission hook (ADR-090). emit fires ONLY when this call won the CAS — the losing request of a concurrent double-click records nothing.

func (*TokenService) Create

func (s *TokenService) Create(ctx context.Context, tenantID, customerID, invoiceID string) (string, error)

Create generates a new payment update token. Returns the raw token (shown once in email).

func (*TokenService) Restore

func (s *TokenService) Restore(ctx context.Context, tenantID, rawToken string) error

Restore un-consumes a token whose side effect FAILED moments after Consume. The consume-then-create ordering in createCheckoutSession is the exactly-once CAS; but when the Stripe create itself errors, the customer's emailed link would stay permanently dead over a transient upstream failure. The recency guard bounds resurrection to the consume-create window of THIS request — a token consumed by a successful session create minutes ago cannot be revived by a replay.

func (*TokenService) RestoreAudited

func (s *TokenService) RestoreAudited(ctx context.Context, tenantID, rawToken string, emit func(tx *sql.Tx) error) error

RestoreAudited is Restore with an in-tx audit emission hook (ADR-090): the revival row keeps the log truthful — without it, a consumed-then- restored token would show a "checkout started" row for a flow that never produced a session. emit fires only when a row was actually revived.

func (*TokenService) Validate

func (s *TokenService) Validate(ctx context.Context, rawToken string) (*PaymentUpdateToken, error)

Validate checks a raw token and returns the associated data. Does NOT mark as used.

Runs under TxBypass because the caller is unauthenticated: the public portal endpoint receives a raw token from a URL and must resolve it to a tenant_id BEFORE any tenant context can be set. The token itself is the credential — 256 bits of entropy, verified by constant-time hash match, so cross-tenant enumeration isn't feasible.

type TokenValidateResponse

type TokenValidateResponse struct {
	CustomerName  string `json:"customer_name"`
	InvoiceNumber string `json:"invoice_number"`
	// InvoiceStatus lets the page tell the truth about a terminal
	// invoice. The token outlives the invoice's collectible life (24h
	// validity, and the operator can void/settle at any moment), so
	// without it the page asked a customer to pay an invoice we had
	// already annulled — amount_due_cents survives a void by design
	// (the void reverses collection, it doesn't rewrite the figure).
	// Found on the FLOW D4 walk (VLX-000005, voided).
	InvoiceStatus  string               `json:"invoice_status"`
	AmountDueCents int64                `json:"amount_due_cents"`
	Currency       string               `json:"currency"`
	Branding       publicUpdateBranding `json:"branding"`
}

TokenValidateResponse is GET /v1/public/payment-updates/{token}.

type WebhookStore

type WebhookStore interface {
	// WasProcessed reports whether an event with this stripe_event_id has
	// already been ingested for the tenant+livemode. Read-only; used as the
	// idempotency pre-check before running side-effects.
	WasProcessed(ctx context.Context, tenantID, stripeEventID string) (bool, error)
	IngestEvent(ctx context.Context, tenantID string, event domain.StripeWebhookEvent) (domain.StripeWebhookEvent, bool, error)
	ListByInvoice(ctx context.Context, tenantID, invoiceID string) ([]domain.StripeWebhookEvent, error)
}

WebhookStore persists and queries Stripe webhook events.

Dedup is split across two calls so the dedup marker can be written AFTER the business side-effect commits, not before. WasProcessed is the read-only pre-check; IngestEvent is the write that both records the audit row and claims the dedup slot (ON CONFLICT DO NOTHING). HandleWebhook calls IngestEvent only once processing has succeeded (or failed permanently) — a transient processing failure persists no row, so Stripe's redelivery re-runs the handler instead of being short-circuited as a duplicate.

Directories

Path Synopsis
Package breaker provides a global circuit breaker around Stripe API calls, built on sony/gobreaker/v2.
Package breaker provides a global circuit breaker around Stripe API calls, built on sony/gobreaker/v2.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL