Documentation
¶
Index ¶
- Constants
- Variables
- func ChargeIdempotencyKey(invoiceID string, chargeAttemptSeq int64, purpose string) string
- func IsDefiniteRefusal(err error) bool
- func IsUnknownPaymentFailure(err error) bool
- func RecordStripeBreakerState(state string)
- func SentIdempotencyKey(chargeKey, paymentMethodID string) string
- type AccountCatchUp
- type AuditEmitter
- type BelowMinimumError
- type CardDetails
- type CardFetcher
- type CatchUp
- type CatchUpReport
- type CatchUpRun
- type CheckoutCardRecorder
- type CheckoutClaim
- type CheckoutResponse
- type CheckoutSessionReader
- type CheckoutSessionResult
- type CheckoutSessionStore
- func (s *CheckoutSessionStore) ClaimOpen(ctx context.Context, tenantID, invoiceID string, amountCents int64, ...) (CheckoutClaim, bool, error)
- func (s *CheckoutSessionStore) ClaimOpenAudited(ctx context.Context, tenantID, invoiceID string, amountCents int64, ...) (CheckoutClaim, bool, error)
- func (s *CheckoutSessionStore) FillSession(ctx context.Context, tenantID, claimID, stripeSessionID, url string, ...) (string, error)
- func (s *CheckoutSessionStore) GetOpenForInvoice(ctx context.Context, tenantID, invoiceID string) (CheckoutClaim, error)
- func (s *CheckoutSessionStore) ListHostedToReconcile(ctx context.Context, checkedBefore time.Time, limit int) ([]CheckoutClaim, error)
- func (s *CheckoutSessionStore) ListUnresolvedForInvoice(ctx context.Context, tenantID, invoiceID string) ([]CheckoutClaim, error)
- func (s *CheckoutSessionStore) MarkCompleted(ctx context.Context, stripeSessionID string) error
- func (s *CheckoutSessionStore) MarkExpired(ctx context.Context, tenantID, claimID string) error
- func (s *CheckoutSessionStore) MarkSessionCompleted(ctx context.Context, tenantID, claimID string) error
- func (s *CheckoutSessionStore) ReleaseRefused(ctx context.Context, tenantID, claimID string) error
- func (s *CheckoutSessionStore) Supersede(ctx context.Context, tenantID, claimID string) (bool, error)
- func (s *CheckoutSessionStore) TouchReconcile(ctx context.Context, tenantID, claimID string) error
- type CustomerByStripeIDResolver
- type CustomerEmailResolver
- type DisputeRecorder
- type DunningResolver
- type DunningRetryFailure
- type DunningStarter
- type EmailPaymentFailed
- type EmailReceipt
- type EndpointResolver
- type ExternalRefundRecorder
- type Handler
- type HostedSessionLedger
- type InvoiceUpdater
- type ListedRefund
- type LiveStripeClient
- func (c *LiveStripeClient) CancelPaymentIntent(ctx context.Context, paymentIntentID string) error
- func (c *LiveStripeClient) ConfirmPaymentIntent(ctx context.Context, paymentIntentID string, params PaymentIntentParams) (PaymentIntentResult, error)
- func (c *LiveStripeClient) CreateUnconfirmedPaymentIntent(ctx context.Context, params PaymentIntentParams) (PaymentIntentResult, error)
- func (c *LiveStripeClient) FetchCardDetails(ctx context.Context, stripeCustomerID string) (CardDetails, error)
- func (c *LiveStripeClient) FetchCardForPaymentIntent(ctx context.Context, paymentIntentID string) (CardDetails, error)
- func (c *LiveStripeClient) GetCheckoutSession(ctx context.Context, sessionID string) (CheckoutSessionResult, error)
- func (c *LiveStripeClient) GetPaymentIntent(ctx context.Context, paymentIntentID string) (PaymentIntentResult, error)
- type LostPayment
- type PaymentAnomalyRecorder
- type PaymentError
- type PaymentFailure
- type PaymentIntentParams
- type PaymentIntentResult
- type PaymentMethodAttacher
- type PaymentSetupStore
- type PaymentUpdateToken
- type PostgresWebhookStore
- func (s *PostgresWebhookStore) IngestEvent(ctx context.Context, tenantID string, event domain.StripeWebhookEvent) (domain.StripeWebhookEvent, bool, error)
- func (s *PostgresWebhookStore) ListByInvoice(ctx context.Context, tenantID, invoiceID string) ([]domain.StripeWebhookEvent, error)
- func (s *PostgresWebhookStore) WasProcessed(ctx context.Context, tenantID, stripeEventID string) (bool, error)
- type PublicPaymentCustomerReader
- type PublicPaymentHandler
- type ReconcileInvoiceStore
- type Reconciler
- type RefundError
- type RefundStatusUpdater
- type RestoreAccounts
- type RestoreCustomers
- type RestoreRefunds
- type SettlementSource
- type Settler
- type StaleChargeHoldStore
- type Stripe
- func (s *Stripe) ChargeInvoice(ctx context.Context, tenantID string, inv domain.Invoice, ...) (domain.Invoice, error)
- func (s *Stripe) ChargeInvoiceForDunningRetry(ctx context.Context, tenantID string, inv domain.Invoice, ...) (domain.Invoice, error)
- func (s *Stripe) ChargeInvoiceNow(ctx context.Context, tenantID string, inv domain.Invoice, ...) (domain.Invoice, error)
- func (s *Stripe) ExpireCheckoutSessions(ctx context.Context, tenantID string, inv domain.Invoice)
- func (s *Stripe) HandleWebhook(ctx context.Context, tenantID string, event domain.StripeWebhookEvent) error
- func (s *Stripe) MustHaveAnomalyRecorder()
- func (s *Stripe) RecordCheckoutBelowMinimum(ctx context.Context, tenantID string, inv domain.Invoice, ...)
- func (s *Stripe) RecordCheckoutCard(ctx context.Context, tenantID, customerID, stripeCustomerID, purpose string) error
- func (s *Stripe) SetAnomalyRecorder(r PaymentAnomalyRecorder)
- func (s *Stripe) SetAuditLogger(a AuditEmitter)
- func (s *Stripe) SetBreaker(b *breaker.Breaker)
- func (s *Stripe) SetCardFetcher(cf CardFetcher)
- func (s *Stripe) SetCheckoutSessionStore(cs *CheckoutSessionStore, clients *StripeClients)
- func (s *Stripe) SetClock(c clock.Clock)
- func (s *Stripe) SetCustomerResolver(r CustomerByStripeIDResolver)
- func (s *Stripe) SetDisputeRecorder(r DisputeRecorder)
- func (s *Stripe) SetDunningResolver(d DunningResolver)
- func (s *Stripe) SetDunningRetryFailure(d DunningRetryFailure)
- func (s *Stripe) SetEmailPaymentFailed(sender EmailPaymentFailed, customerEmail CustomerEmailResolver)
- func (s *Stripe) SetEmailReceipt(receipt EmailReceipt, customerEmail CustomerEmailResolver)
- func (s *Stripe) SetExternalRefundRecorder(r ExternalRefundRecorder)
- func (s *Stripe) SetKeyHealth(k StripeKeyHealth)
- func (s *Stripe) SetPaymentMethodAttacher(a PaymentMethodAttacher)
- func (s *Stripe) SetRefundStatusUpdater(u RefundStatusUpdater)
- func (s *Stripe) SettleFailed(ctx context.Context, tenantID string, inv domain.Invoice, f PaymentFailure, ...) error
- func (s *Stripe) SettleSucceeded(ctx context.Context, tenantID string, inv domain.Invoice, ...) error
- func (s *Stripe) StopCollection(ctx context.Context, tenantID string, inv domain.Invoice)
- type StripeBillingSync
- type StripeClient
- type StripeClients
- func (c *StripeClients) Has() bool
- func (c *StripeClients) HasFor(ctx context.Context, tenantID string, livemode bool) (bool, error)
- func (c *StripeClients) Resolve(ctx context.Context, tenantID string, livemode bool) (*stripe.Client, error)
- func (c *StripeClients) ResolveCtx(ctx context.Context) (*stripe.Client, error)
- type StripeCredentials
- type StripeCustomerEnsurer
- type StripeKeyError
- type StripeKeyHealth
- type StripeRefunder
- func (r *StripeRefunder) CreateRefund(ctx context.Context, paymentIntentID string, amountCents int64, ...) (string, domain.RefundStatus, error)
- func (r *StripeRefunder) FindRefundForCreditNote(ctx context.Context, paymentIntentID, creditNoteID string) (string, domain.RefundStatus, error)
- func (r *StripeRefunder) GetRefund(ctx context.Context, refundID string) (domain.RefundStatus, string, error)
- func (r *StripeRefunder) ReadRefund(ctx context.Context, refundID string) (domain.StripeRefundFacts, error)
- type TokenService
- func (s *TokenService) Cleanup(ctx context.Context) (int, error)
- func (s *TokenService) Consume(ctx context.Context, tenantID, rawToken string) (bool, error)
- func (s *TokenService) ConsumeAudited(ctx context.Context, tenantID, rawToken string, emit func(tx *sql.Tx) error) (bool, error)
- func (s *TokenService) Create(ctx context.Context, tenantID, customerID, invoiceID string) (string, error)
- func (s *TokenService) Restore(ctx context.Context, tenantID, rawToken string) error
- func (s *TokenService) RestoreAudited(ctx context.Context, tenantID, rawToken string, emit func(tx *sql.Tx) error) error
- func (s *TokenService) Validate(ctx context.Context, rawToken string) (*PaymentUpdateToken, error)
- type TokenValidateResponse
- type UnappliedEvent
- type WebhookStore
Constants ¶
const ( // RefundCreditNoteLost: Hardcount made the refund (hardcount_cn_id), // and no credit note in the restored database holds it. Applied, it // would be acknowledged with no record, and the invoice would show the // money as refundable again. RefundCreditNoteLost = "credit_note_lost" // RefundStripeTax: the refund was made in Stripe, the restored database // does not hold it, and its invoice was reported to Stripe Tax. The old // server may have recorded it and reversed its tax already; applied // again, it would reverse the tax a second time. RefundStripeTax = "stripe_tax" )
Why a refund is listed instead of applied.
const ( StripeKeyRejected = "rejected" StripeKeyNotConfigured = "not_configured" )
Reasons of a StripeKeyError; also the label of hardcount_stripe_key_unusable_total.
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 ¶
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.
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.
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.
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 a confirm after a network error, the first send under the same key may still be running at Stripe and charge the card (#976). The invoice already names the PaymentIntent, so the unknown sweep reads what it did. A 429 to the create is harmless: at most an unconfirmed PaymentIntent exists.
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.
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).
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").
Functions ¶
func ChargeIdempotencyKey ¶
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). The invoice names the charge's PaymentIntent before the confirm (ADR-137), so no claim admits it until the unknown sweep has read that PaymentIntent. A charge that stopped before then confirmed nothing: the stale-hold 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 clear of a hold whose charge never confirmed, 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 ¶
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 ¶
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 RecordStripeBreakerState ¶ added in v0.10.0
func RecordStripeBreakerState(state string)
RecordStripeBreakerState updates the global breaker state gauge. Called from the breaker's OnStateChange hook. Values mirror gobreaker's semantics: 0=closed (normal), 1=half_open (probing), 2=open (rejecting).
func SentIdempotencyKey ¶ added in v0.9.2
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 AccountCatchUp ¶ added in v0.10.0
type AccountCatchUp struct {
Account tenantstripe.Account
// Err is a failure that stopped this account part-way: Stripe or the
// database could not be reached. A rerun is safe.
Err error
// KeyRefused says why the account's key cannot be used: Stripe refused
// it (401 or 403), or it is a key of the other mode. Nothing more was
// read for the account.
KeyRefused string
// SessionsExpired counts the open payment pages closed at Stripe.
SessionsExpired int
// Events counts the events Stripe listed, and ByType by event type.
Events int
ByType map[string]int
// Applied counts events applied now, AlreadyRecorded events the
// database already held, Skipped events of another tenant or not
// Hardcount's, and Held the events held with a listed payment or
// refund.
Applied, AlreadyRecorded, Skipped, Held int
// Lost are the payments whose invoice the restore lost or left as a
// draft, oldest first.
Lost []LostPayment
// Refunds are the refunds not applied, oldest first.
Refunds []ListedRefund
// Unapplied are the other events not applied, in the order applied.
Unapplied []UnappliedEvent
}
AccountCatchUp is what one run did for one account.
type AuditEmitter ¶
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 CatchUp ¶ added in v0.10.0
type CatchUp struct {
// contains filtered or unexported fields
}
CatchUp applies Stripe's events since a restored backup.
func NewCatchUp ¶ added in v0.10.0
func NewCatchUp(s *Stripe, clients *StripeClients, accounts RestoreAccounts, customers RestoreCustomers, refunds RestoreRefunds) *CatchUp
NewCatchUp wires the catch-up to the adapter whose HandleWebhook applies the events, the clients that read Stripe, the account list, and the two lookups that decide what to list instead of applying.
func (*CatchUp) Run ¶ added in v0.10.0
func (c *CatchUp) Run(ctx context.Context, run CatchUpRun) (CatchUpReport, error)
Run reads and applies the events of every account. A failure on one account is reported on it and the run moves on; an error is returned only when the account list cannot be read.
type CatchUpReport ¶ added in v0.10.0
type CatchUpReport struct {
Accounts []AccountCatchUp
}
CatchUpReport is what one run did, per account.
type CatchUpRun ¶ added in v0.10.0
type CatchUpRun struct {
// Since is the creation time of the oldest event to read.
Since time.Time
// Extra are accounts to read besides those with stored keys: an
// account connected after the backup, whose key is given for this run
// only (KeyOverrides).
Extra []tenantstripe.Account
// Acknowledged are the ids of what the operator has handled: listed
// payments (pi_…), listed refunds (re_…) and listed events (evt_…).
Acknowledged map[string]bool
}
CatchUpRun is one run's input.
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 / 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, cause domain.DunningStartCause) (domain.InvoiceDunningRun, error)
}
DunningStarter starts dunning for failed payments.
type EmailPaymentFailed ¶
type EmailPaymentFailed interface {
// SendPaymentFailedTx enqueues on the settle transaction (ADR-040
// amendment). 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.
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).
type EmailReceipt ¶
type EmailReceipt interface {
// SendPaymentReceiptTx enqueues on the settle transaction so the receipt
// commits with the paid-flip (ADR-040 amendment).
// credit is set for a top-up: the receipt says what credit was added.
SendPaymentReceiptTx(ctx context.Context, tx *sql.Tx, tenantID, to string, cc []string, customerName, invoiceNumber string, amountCents int64, currency, publicToken string, credit *domain.TopupCredit) 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).
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)
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.
// capturedCents is the amount Stripe captured (0 = unknown): when it
// differs from the amount due, the same transaction records the anomaly
// and queues payment.amount_mismatch (ADR-068).
MarkPaidCardSettlementTransition(ctx context.Context, tenantID, id string, stripePaymentIntentID string, paidAt time.Time, capturedCents int64, 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)
// ListLineItems reads an unpaid top-up's line for its receipt.
ListLineItems(ctx context.Context, tenantID, invoiceID string) ([]domain.InvoiceLineItem, error)
// StampPendingConfirm puts the charge's PaymentIntent on the invoice as
// an unknown outcome and records the attempt, only while hold is still
// the charger's; the charge confirms only if it applied (ADR-137).
StampPendingConfirm(ctx context.Context, tenantID string, a domain.InvoiceChargeAttempt, hold domain.ChargeHold, attemptSeq int64) (domain.Invoice, bool, 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 confirm may be
// running at Stripe, and the unknown sweep leaves the invoice alone until
// the hold has ended.
ReleaseChargeHold(ctx context.Context, tenantID, id string, hold domain.ChargeHold) error
// EndUnstampedAttempt ends an attempt whose PaymentIntent was created
// but not put on the invoice: on an invoice still open it clears the
// caller's hold and moves the charge counter in one compare-and-set, so
// the next charge sends a fresh key; otherwise it only clears the
// caller's hold (ADR-137).
EndUnstampedAttempt(ctx context.Context, tenantID, id string, hold domain.ChargeHold, attemptSeq int64) 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 ListedRefund ¶ added in v0.10.0
type ListedRefund struct {
RefundID string
PaymentIntentID string
// InvoiceID is the invoice that holds the refunded payment.
InvoiceID string
// CreditNoteID is the refund's hardcount_cn_id, for a refund Hardcount
// made.
CreditNoteID string
// Reason is RefundCreditNoteLost or RefundStripeTax.
Reason string
AmountCents int64
Currency string
// Status is the refund's status in its newest event.
Status string
CreatedAt time.Time
// Events counts the refund's events held with it.
Events int
// Acknowledged: the operator handled it, now or on an earlier run.
Acknowledged bool
}
ListedRefund is a refund of a payment the restored database holds, which the catch-up does not apply. The operator handles it by hand (docs/ops/restore.md).
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: each call resolves the tenant and mode on ctx through StripeClients.ResolveCtx. A caller outside a request (a background job, a sweep) must set the tenant first with auth.WithTenantID, or the call fails and nothing reaches Stripe. 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) ConfirmPaymentIntent ¶ added in v0.10.0
func (c *LiveStripeClient) ConfirmPaymentIntent(ctx context.Context, paymentIntentID string, params PaymentIntentParams) (PaymentIntentResult, error)
ConfirmPaymentIntent confirms a PaymentIntent that CreateUnconfirmedPaymentIntent made: the step where money moves. Every error it returns names the PaymentIntent, so an unclear answer is never one Hardcount cannot look up.
A confirm Stripe refuses as payment_intent_unexpected_state is not a decline: an earlier confirm of the same PaymentIntent already moved it on (stripe-go resent after a lost reply, or a retry of this attempt). Read by its type (invalid_request_error) it would mark a paid invoice failed, so the PaymentIntent is read and its real state returned instead.
func (*LiveStripeClient) CreateUnconfirmedPaymentIntent ¶ added in v0.10.0
func (c *LiveStripeClient) CreateUnconfirmedPaymentIntent(ctx context.Context, params PaymentIntentParams) (PaymentIntentResult, error)
CreateUnconfirmedPaymentIntent creates one charge attempt's PaymentIntent without confirming it, so no money can move (ADR-137). The caller puts its id on the invoice, then calls ConfirmPaymentIntent. The confirm-time settings (off_session, error_on_requires_action) go on the confirm: Stripe takes off_session only together with confirmation.
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. The unknown and processing sweeps read it: Stripe is the source of truth for what a charge did. A failed read (a refused key, a PaymentIntent not in this account, a 5xx, no answer) is an error the sweep reports and retries on a later tick; the invoice stays as it is.
type LostPayment ¶ added in v0.10.0
type LostPayment struct {
PaymentIntentID string
// InvoiceID and CustomerID are the PaymentIntent's hardcount_invoice_id
// and hardcount_customer_id metadata.
InvoiceID string
CustomerID string
// InvoiceDraft is true when the invoice exists as a draft, false when
// no row holds it.
InvoiceDraft bool
AmountCents int64
Currency string
PaidAt time.Time
// Held counts the events held with this payment: its refunds and
// disputes, and the card events of its customer when the restore lost
// the customer too. The operator sees them on the payment in Stripe.
Held int
// Acknowledged: the operator handled it, now or on an earlier run.
Acknowledged bool
}
LostPayment is a payment Stripe took whose invoice the restored database does not have, or has only as a draft. The catch-up does not record it on any invoice: the operator matches it by hand (docs/ops/restore.md).
type PaymentAnomalyRecorder ¶
type PaymentAnomalyRecorder interface {
RecordPaymentAnomaly(ctx context.Context, tenantID, invoiceID, kind, paymentIntentID string, capturedCents int64, data map[string]any) (bool, error)
}
PaymentAnomalyRecorder persists the durable payment-anomaly marker the dashboard attention classifier reads (ADR-068), and queues the anomaly's webhook event (kind) with data in the same transaction, once per kind and charge: it returns false, having written nothing, when the marker already names this kind and PaymentIntent. Implemented by *invoice.PostgresStore; wired via SetAnomalyRecorder in wire.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
// Card: Stripe answered card_error, so the customer's card refused the
// charge, with a decline code or without. An invalid request is not one.
Card bool
}
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) LogLevel ¶ added in v0.12.0
func (e *PaymentError) LogLevel() slog.Level
LogLevel is the level to log this error at:
- ERROR: an unknown outcome, or Stripe refused the request, not the card;
- INFO: the card was refused, with any decline code;
- WARN: the card was refused with none.
A refused card is an ordinary outcome of collection, so it is not an ERROR.
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 errs.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 read. 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
// 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). Populated
// by the read paths.
InvoiceID string
// TenantID is the hardcount_tenant_id metadata, which every Hardcount
// PaymentIntent carries beside InvoiceID. Populated by the read paths.
// A refund of another tenant's payment on a shared Stripe account is
// told apart by it (unmatchedRefund).
TenantID string
// Charged is set when the PaymentIntent has a charge (latest_charge): some
// confirm reached the card network, whatever its result. A canceled
// PaymentIntent without one never asked a bank for money, so ending it
// is not a failed payment and tells the customer nothing.
Charged bool
}
type PaymentMethodAttacher ¶
type PaymentMethodAttacher interface {
AttachForWebhook(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, makeDefault bool, eventType string, extra map[string]any) (*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, or nil when the card was already removed and stays removed (a late event).
eventType is the payment_method.* event the attach reports, with extra beside the card. The attacher queues it in the attach's transaction, and only when the attach changed the card, so a redelivery sends nothing a second time; a removed card sends nothing.
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 (s *PostgresWebhookStore) IngestEvent(ctx context.Context, tenantID string, event domain.StripeWebhookEvent) (domain.StripeWebhookEvent, bool, error)
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
// EndAttemptWithoutPayment puts an invoice left unknown on a PaymentIntent
// that took no payment (never confirmed and canceled, or refunded in
// full) back where a charge picks it up, with no customer email; reason
// goes on the attempt's row (ADR-137).
EndAttemptWithoutPayment(ctx context.Context, tenantID, id, paymentIntentID, reason string) (domain.InvoicePaymentStatus, bool, error)
// The stale-hold sweep's reads and writes (ADR-127, ADR-137). Required,
// not optional: a stale hold blocks every charge and the irreversible
// actions, and this sweep is the only thing that clears one.
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, settler Settler, 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 ¶
Run reconciles unresolved payments against Stripe:
- stale charge holds (ADR-127, ADR-137, reconciler_stale_hold.go): holds whose charger is gone. It asks Stripe nothing. First, so an invoice it releases is charged by the same tick's auto-charge sweep;
- '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 never stamps an 'unknown' invoice, so one whose check panics 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.
type RefundError ¶
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 errs.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 RestoreAccounts ¶ added in v0.10.0
type RestoreAccounts interface {
ListAccounts(ctx context.Context) ([]tenantstripe.Account, error)
}
RestoreAccounts lists every tenant and mode with stored Stripe keys, across tenants. tenantstripe.Service implements it.
type RestoreCustomers ¶ added in v0.10.0
type RestoreCustomers interface {
Get(ctx context.Context, tenantID, id string) (domain.Customer, error)
}
RestoreCustomers reads a customer, to find a card event of a customer the restore lost. customer.PostgresStore implements it; a missing customer is errs.ErrNotFound.
type RestoreRefunds ¶ added in v0.10.0
type RestoreRefunds interface {
StripeRefundRecorded(ctx context.Context, tenantID, stripeRefundID string) (bool, error)
}
RestoreRefunds reports whether the restored database holds a refund: a credit note carries its id, or it is recorded as a refund made in Stripe. creditnote.PostgresStore implements it.
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, 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. NewReconciler requires one.
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
}
StaleChargeHoldStore is what the stale-hold sweep needs from the invoice store (ADR-127, ADR-137). 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 package-boundary rule in docs/architecture.md ("Design rules").
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 ¶
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:
- WasProcessed is a read-only idempotency pre-check.
- processEvent runs the side-effect (MarkPaid / dunning / etc.).
- 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."
- 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) MustHaveAnomalyRecorder ¶ added in v0.10.0
func (s *Stripe) MustHaveAnomalyRecorder()
MustHaveAnomalyRecorder panics unless SetAnomalyRecorder was called. The recorder is the only path a duplicate charge, a charge in another currency or a payment on a voided invoice takes to its marker and its webhook event, and anomalies are rare: a dropped wiring line would otherwise boot and go unnoticed until the first one failed its webhook. The composition root calls it after the wiring, as it does webhook.MustWiredOutbox.
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 default 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. payment_method.updated is queued in the attach's transaction, and only when the attach changed the card, so a card both report sends one event, the default or not.
func (*Stripe) SetAnomalyRecorder ¶
func (s *Stripe) SetAnomalyRecorder(r PaymentAnomalyRecorder)
SetAnomalyRecorder wires the store that writes each payment anomaly's marker and queues its webhook event. Required: without it, every anomaly fails its webhook (escalatePaymentAnomaly), and MustHaveAnomalyRecorder refuses to boot.
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 ¶
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) SetClock ¶ added in v0.10.0
SetClock wires the server's clock. An event the restore catch-up applies binds its instant from it (bindEvent), and a settle reads the result's time from it (clock.AtArrival). The router passes the clock the server bills by; the default is the machine's.
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) 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) 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.
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, at the time its result arrived (clock.AtArrival): 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, an anomaly is recorded once per kind and charge, and the card stamp is best-effort (log-only), so a duplicate call — e.g. the webhook arriving after the reconciler already settled — does not fail and sends nothing twice. A failed anomaly write does fail the call: the marker and its event are saved together or not at all, and the caller's retry (Stripe's redelivery, the reconciler's next run) records both.
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 transaction compares it against the amount due it books and records 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 ¶
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, and nothing retries either. The void's transaction already closed Hardcount's own claims, so Hardcount does not collect on this invoice again. A session whose expire fails stays payable until its ExpiresAt (at most an hour). A PaymentIntent whose cancel fails may stay open at Stripe for good. The customer cannot pay it, because Hardcount never shows its client secret. A payment that lands anyway raises the ADR-068 payment-received-on-voided-invoice anomaly.
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 makes the Stripe customer match the customer's email and the whole billing profile. It sets tax_exempt from the profile and leaves exactly the profile's tax ID at Stripe, deleting any other. Call it only with a profile just read or saved: an empty profile sets tax_exempt to none and deletes every tax ID.
func (*StripeBillingSync) SyncCustomer ¶ added in v0.10.0
func (s *StripeBillingSync) SyncCustomer(ctx context.Context, stripeCustomerID, customerEmail string) error
SyncCustomer pushes the customer's email to the Stripe customer and leaves every other field there as it is, the display name included. An empty email sends nothing: Hardcount then holds none, and email= would clear one set at Stripe.
type StripeClient ¶
type StripeClient interface {
CreateUnconfirmedPaymentIntent(ctx context.Context, params PaymentIntentParams) (PaymentIntentResult, error)
ConfirmPaymentIntent(ctx context.Context, paymentIntentID string, params PaymentIntentParams) (PaymentIntentResult, error)
CancelPaymentIntent(ctx context.Context, paymentIntentID string) error
GetPaymentIntent(ctx context.Context, paymentIntentID string) (PaymentIntentResult, error)
}
StripeClient is the interface for Stripe API calls. In production this wraps stripe-go; in tests it's a mock.
A charge is two calls (sendCharge): CreateUnconfirmedPaymentIntent, which moves no money, then ConfirmPaymentIntent on the id Hardcount saved in between. So Hardcount knows every PaymentIntent it could have charged, and finds out what one did by reading it by id: it never searches Stripe.
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 ¶
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 ¶
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.
func KeyOverrides ¶ added in v0.10.0
func KeyOverrides(creds StripeCredentials, keys map[tenantstripe.Account]string) StripeCredentials
KeyOverrides returns creds with the given secret keys in place of the stored ones. `hardcount restore catch-up --stripe-key` uses it for a key Stripe refuses since it was stored, or an account connected after the backup. The keys live in this process only and are never saved.
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
// AtConfirm: the key was refused at the confirm, after the invoice was
// stamped unknown on its PaymentIntent. The invoice is not unchanged, and
// collecting again is refused until the unknown sweep has read that
// PaymentIntent, which needs a working key.
AtConfirm bool
}
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 errs.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 wire.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 ¶
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 UnappliedEvent ¶ added in v0.10.0
type UnappliedEvent struct {
EventID string
Type string
CreatedAt time.Time
// CustomerID is the lost customer of a card event.
CustomerID string
// Err is why the handler failed, nil for a card event of a lost
// customer.
Err error
// Acknowledged: the event is recorded without being applied. A failed
// event is tried again first, and recorded only if it fails again.
Acknowledged bool
}
UnappliedEvent is an event the catch-up did not apply and that no listed payment or refund holds: a card event of a customer the restore lost, or an event whose handler failed.
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.