Documentation
¶
Overview ¶
Package paymentmethods is the customer-facing view of payment methods.
payment_methods rows are the canonical many-to-one store (multiple cards per customer, one flagged default). The existing customer_payment_setups table stays as the 1:1 denorm summary that billing reads for the "one default card" path — this package writes both on every mutation.
The operator routes run under API-key auth: tenantID comes from the auth ctx and customerID from the URL path; both are pushed into BeginTx.
Index ¶
- type AuditWriter
- type CooldownGate
- type CustomerLookup
- type CustomerStripeLink
- type Handler
- type MethodDetails
- type OutboxEnqueuer
- type PaymentMethod
- type PostgresStore
- func (s *PostgresStore) CustomersWithDefault(ctx context.Context, tenantID string, customerIDs []string) (map[string]bool, error)
- func (s *PostgresStore) DetachAndRebalance(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, *PaymentMethod, error)
- func (s *PostgresStore) Get(ctx context.Context, tenantID, pmID string) (PaymentMethod, error)
- func (s *PostgresStore) List(ctx context.Context, tenantID, customerID string) ([]PaymentMethod, error)
- func (s *PostgresStore) SetDefault(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
- func (s *PostgresStore) SetOutboxEnqueuer(o OutboxEnqueuer)
- func (s *PostgresStore) Upsert(ctx context.Context, tenantID string, pm PaymentMethod, makeDefault bool, ...) (PaymentMethod, bool, error)
- type SendSetupEmailRequest
- type SendSetupEmailResponse
- type Service
- func (s *Service) AttachForWebhook(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, ...) (*domain.PaymentMethodView, error)
- func (s *Service) AttachFromSetupIntent(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, ...) (PaymentMethod, error)
- func (s *Service) CreateSetupSession(ctx context.Context, tenantID, customerID, returnURL string) (checkoutURL, sessionID string, err error)
- func (s *Service) CustomersWithDefault(ctx context.Context, tenantID string, customerIDs []string) (map[string]bool, error)
- func (s *Service) Detach(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
- func (s *Service) List(ctx context.Context, tenantID, customerID string) ([]PaymentMethod, error)
- func (s *Service) SetAuditLogger(a AuditWriter)
- func (s *Service) SetDefault(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
- func (s *Service) SetPortalBaseURL(u string)
- type SetupLinkEmailer
- type SetupSessionRequest
- type SetupSessionResponse
- type Store
- type StripeAPI
- type StripeAdapter
- func (a *StripeAdapter) CreateSetupCheckoutSession(ctx context.Context, stripeCustomerID, successURL, cancelURL string, ...) (string, string, error)
- func (a *StripeAdapter) DetachPaymentMethod(ctx context.Context, stripePaymentMethodID string) error
- func (a *StripeAdapter) EnsureStripeCustomer(ctx context.Context, tenantID, customerID string) (string, error)
- func (a *StripeAdapter) FetchPaymentMethod(ctx context.Context, stripePaymentMethodID string) (MethodDetails, error)
- func (a *StripeAdapter) SetDefaultPaymentMethod(ctx context.Context, tenantID, customerID, stripePaymentMethodID string) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AuditWriter ¶
type AuditWriter interface {
Log(ctx context.Context, tenantID, action, resourceType, resourceID, resourceLabel string, metadata map[string]any) error
}
AuditWriter is the narrow audit surface paymentmethods needs. Declared here (not imported from internal/audit) so the package stays decoupled and testable with a fake. Production wires *audit.Logger via SetAuditLogger in wire.go.
type CooldownGate ¶
type CooldownGate interface {
AllowKey(ctx context.Context, key string) (remaining int, resetAt time.Time, allowed bool)
}
CooldownGate enforces a per-customer minimum interval between send-setup-email calls. Defends against operator double-click and abusive automation. Satisfied by *middleware.RateLimiter via its AllowKey method. Optional: nil = no cooldown (local dev / tests).
type CustomerLookup ¶
type CustomerLookup interface {
GetForSetupLink(ctx context.Context, tenantID, customerID string) (email, displayName string, err error)
}
CustomerLookup resolves the recipient's email + display name for the operator "send setup email" flow. Implemented by *customer.PostgresStore via a thin adapter in adapters.go.
type CustomerStripeLink ¶
type CustomerStripeLink interface {
Get(ctx context.Context, tenantID, customerID string) (domain.Customer, error)
SetStripeCustomerID(ctx context.Context, tenantID, customerID, stripeCustomerID string) error
// GetBillingProfile returns the billing profile (legal_name, phone,
// address, tax_status) so EnsureStripeCustomer can pre-populate
// the Stripe Customer object at create time instead of leaving
// email/name/address null. ErrNotFound = customer doesn't have a
// profile yet — adapter passes only the Customer-level fields.
GetBillingProfile(ctx context.Context, tenantID, customerID string) (domain.CustomerBillingProfile, error)
}
CustomerStripeLink is the narrow surface the adapter uses to read/write the Stripe Customer ID mapping. customers.stripe_customer_id has been the canonical home since migration 0096; this interface abstracts the customer store so the adapter doesn't gain a hard dependency on internal/customer (which would create a cycle).
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler exposes the operator-side payment-method surface under /v1/customers/{customer_id}/payment-methods: list / set-default / detach, plus a "send setup link" affordance (email or copy-link) that mints a Stripe Checkout setup URL the operator hands to the customer — card data goes browser → Stripe, never the operator dashboard.
The customer lookup (resolves the recipient email + display name) and the email sender are optional: a Handler without them refuses the email path with 503 and still serves list/setDefault/detach.
func NewHandler ¶
func (*Handler) OperatorRoutes ¶
OperatorRoutes mounts the operator-side PM surface under /v1/customers/{customer_id}/payment-methods. Same Service backs both surfaces — the only difference is where customer_id comes from (portal session ctx vs URL path) and how auth is gated (portal session vs operator API key). Industry parity: Chargebee, Lago, Orb all expose operator-side list/setDefault/detach + a "send setup link" affordance. Card-data entry stays customer-side via Stripe Checkout, keeping every tenant in PCI SAQ-A scope. See docs/adr/ for the PCI-scope rationale.
func (*Handler) SetAuditLogger ¶
func (h *Handler) SetAuditLogger(a AuditWriter)
SetAuditLogger wires audit on operator-initiated actions.
func (*Handler) SetCooldown ¶
func (h *Handler) SetCooldown(c CooldownGate)
SetCooldown wires the per-customer cooldown gate on send-setup-email. Without it, an operator double-click could send two emails ~30s apart. Optional in tests / local dev.
func (*Handler) SetCustomerLookup ¶
func (h *Handler) SetCustomerLookup(c CustomerLookup)
SetCustomerLookup wires the customer-lookup dependency. Required for the operator send-setup-email endpoint; nil = endpoint refuses with 503.
func (*Handler) SetEmailConfigured ¶
SetEmailConfigured records whether this server can send email (email.Sender.IsConfigured at boot). Zero value refuses send-setup-email with 409 email_not_configured — the email is queued, so on a server with no SMTP it used to answer 202 and then fail unseen.
func (*Handler) SetEmailer ¶
func (h *Handler) SetEmailer(e SetupLinkEmailer)
SetEmailer wires the email sender. Required for operator send-setup-email; nil = endpoint refuses with 503.
type MethodDetails ¶ added in v0.11.0
type MethodDetails struct {
Type string
Brand string
Last4 string
ExpMonth int
ExpYear int
Fingerprint string
}
MethodDetails bundles the facts the Stripe adapter returns at attach time. Type is the method's type as Stripe names it. The card fields are set only for a card; Fingerprint is the dedupe key — Stripe's stable hash of the card number (CVC + expiry don't affect it).
type OutboxEnqueuer ¶ added in v0.10.0
type OutboxEnqueuer interface {
Enqueue(ctx context.Context, tx *sql.Tx, tenantID, eventType string, payload map[string]any) (string, error)
}
OutboxEnqueuer inserts a webhook-event row on the caller's tx, so the event commits or rolls back with the change that caused it (ADR-040 transactional outbox). Satisfied by *webhook.OutboxStore; declared here so this store needs no webhook import. Same seam as the invoice, subscription and dunning stores.
type PaymentMethod ¶
type PaymentMethod struct {
ID string
TenantID string
Livemode bool
CustomerID string
StripePaymentMethodID string
Type string // the method's type as Stripe names it; see Chargeable
CardBrand string
CardLast4 string
CardExpMonth int
CardExpYear int
// CardFingerprint is Stripe's stable hash of the card number
// (CVC + expiry don't affect it). Same physical card → same
// fingerprint across re-tokenizations. Used by Upsert to dedupe:
// if a customer re-runs Add and produces a PM with the same
// fingerprint as an existing active row, the old row is detached
// and the new one inherits its is_default flag. Empty for legacy
// rows attached before the fingerprint plumbing existed (will
// re-collapse the next time the customer re-attaches the card).
CardFingerprint string
IsDefault bool
DetachedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
PaymentMethod mirrors one row in payment_methods.
func (PaymentMethod) Chargeable ¶ added in v0.11.0
func (p PaymentMethod) Chargeable() bool
Chargeable reports whether Hardcount can charge this method (domain.PaymentMethodChargeable). One that isn't is saved and listed, and is never the customer's default.
func (PaymentMethod) IsActive ¶
func (p PaymentMethod) IsActive() bool
IsActive — convenience for "attached and usable".
func (PaymentMethod) View ¶
func (p PaymentMethod) View() domain.PaymentMethodView
View is the payment method as the API returns it and as the payment_method.* webhooks carry it.
type PostgresStore ¶
type PostgresStore struct {
// contains filtered or unexported fields
}
func NewPostgresStore ¶
func NewPostgresStore(db *postgres.DB) *PostgresStore
func (*PostgresStore) CustomersWithDefault ¶
func (*PostgresStore) DetachAndRebalance ¶
func (s *PostgresStore) DetachAndRebalance(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, *PaymentMethod, error)
DetachAndRebalance does the detach and the replacement-default promotion in one transaction so the invariant "a customer with an active chargeable PM has exactly one default" holds across the whole operation — no committed window with active cards but no default. See the Store interface for the contract.
func (*PostgresStore) Get ¶
func (s *PostgresStore) Get(ctx context.Context, tenantID, pmID string) (PaymentMethod, error)
func (*PostgresStore) List ¶
func (s *PostgresStore) List(ctx context.Context, tenantID, customerID string) ([]PaymentMethod, error)
func (*PostgresStore) SetDefault ¶
func (s *PostgresStore) SetDefault(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
SetDefault clears the customer's default and sets pmID as the default in one transaction, under the customer's card lock (lockCustomerCards).
func (*PostgresStore) SetOutboxEnqueuer ¶ added in v0.10.0
func (s *PostgresStore) SetOutboxEnqueuer(o OutboxEnqueuer)
SetOutboxEnqueuer wires payment_method.attached and .updated into the transaction of the attach each reports (Upsert). Optional: when unset (narrow tests), no event is queued. Production boot refuses an unset one (webhook.MustWiredOutbox).
func (*PostgresStore) Upsert ¶
func (s *PostgresStore) Upsert(ctx context.Context, tenantID string, pm PaymentMethod, makeDefault bool, eventType string, extra map[string]any) (PaymentMethod, bool, error)
Upsert inserts a row keyed by (tenant_id, livemode, stripe_payment_method_id). On conflict we refresh card metadata and keep is_default unless this attach makes the card the default. If no active default exists for the customer, the new row is promoted to default in the same tx (enforces "first PM is default").
Every rule below that makes the row the default applies only to a chargeable method (PaymentMethod.Chargeable): one Hardcount can't charge is saved with its type and never becomes the default, so the default is always a method a charge can use.
A card saved through a setup flow becomes the default (makeDefault, ADR-021): the customer, or the operator for them, gave this card to be charged, and the setup and update pages say Hardcount will use it for upcoming invoices. The other active defaults are cleared first, in this tx, on the insert and the conflict path alike, so the one-default-per-customer index never sees two and a redelivery of a card already saved beside still promotes it.
Without makeDefault, a default the bank refused for good is replaced (ADR-126, #966): when a charge attempt recorded a hard decline (domain.IsHardDecline) on the customer's current default card, the card being saved becomes the default, on the insert and the conflict path alike. That card cannot be charged again, and Stripe Billing's rule is the same: after a hard decline a retry runs only once it detects a new payment method. Otherwise a card the customer saved through the update link, asked for a different card, sat beside the refused one while every retry skipped it until dunning ran out. A working default is not replaced: a card saved by paying on the hosted page, or by a SetupIntent Hardcount did not create, is added beside it.
A card already removed stays removed. A late webhook (Stripe redelivers setup_intent.succeeded after a failed first delivery, for up to three days) can name a card the operator has since removed, or an older copy of a card the dedupe below replaced. Stripe does not let a detached PaymentMethod be used or attached again, so the row is returned unchanged and nothing else is touched: bringing it back, above all as the default, would point every retry at a card Stripe refuses.
replacedDefault is true when another card was the customer's default and this attach moved the default to this card (a setup flow, or a refused default replaced). The first card, a card added beside, a same-card dedupe and a redelivery of the current default report false.
Dedupe-by-fingerprint (ADR-0099): when a customer re-runs Add and produces a new pm_xxx with a fingerprint that already exists as an active row for this customer, the old row is detached in the same transaction and the new row inherits its is_default flag. Industry standard — Stripe explicitly recommends this pattern because each Checkout completion mints a fresh PaymentMethod even for the same physical card. Without dedupe, the customer sees "Visa ····4242" twice (or more) and the default-PM semantics drift across the duplicates. Skipped when fingerprint is empty (legacy rows / non-card types) — those keep current behavior.
eventType (payment_method.attached or .updated, "" for none) is queued in this transaction with the card as it commits (ADR-131) and extra beside it, so the card and its event are saved together or not at all. It is queued only when the write changed what the API shows of the card: a new row, or a change to its default flag, brand, last 4 digits or expiry. A Stripe event delivered again, or the hosted sweep reporting a card the webhook already saved, changes nothing and sends nothing, so a receiver never gets one change twice under two event ids. The second of the two events one setup session sends for its card sends one only if it changes the card, for example by making it the default. A removed card sends nothing either. A failed insert fails the attach.
type SendSetupEmailRequest ¶
type SendSetupEmailRequest struct {
Note string `json:"note,omitempty"`
}
SendSetupEmailRequest is the operator-initiated send-email payload. Note is optional — when present it prefaces the email body with the operator's own context ("Your card expired", "We're moving you to monthly billing"); when absent the template uses a generic body.
type SendSetupEmailResponse ¶
SendSetupEmailResponse echoes the recipient address back to the dashboard so the toast can read "Setup link sent to billing@acme.com" — useful confirmation when a customer has multiple addresses on different surfaces (profile vs billing_profile vs portal session).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func NewService ¶
NewService — `summary` parameter kept for back-compat with the existing wire.go wiring (passes customerStore which used to satisfy PaymentSetupSummaryWriter). Ignored. Remove this parameter once the writer interface is fully retired across all builders.
func (*Service) AttachForWebhook ¶
func (s *Service) AttachForWebhook(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, makeDefault bool, eventType string, extra map[string]any) (*domain.PaymentMethodView, error)
AttachForWebhook is AttachFromSetupIntent for payment.Stripe.HandleWebhook: it returns the card as the API shows it (domain.PaymentMethodView), so payment/ does not have to know about PaymentMethod. It returns nil for a card already removed, which stays removed: the API does not list it.
eventType is the payment_method.* event the attach reports, and extra its fields beside the card. The store queues it in the attach's transaction when the attach changed the card (PostgresStore.Upsert).
func (*Service) AttachFromSetupIntent ¶
func (s *Service) AttachFromSetupIntent(ctx context.Context, tenantID, customerID, stripePaymentMethodID string, makeDefault bool) (PaymentMethod, error)
AttachFromSetupIntent saves a card Stripe holds for the customer as a payment_methods row: the attach the webhook makes after setup_intent.succeeded (through AttachForWebhook), for callers that send no webhook event. Called with an RLS ctx already staged to the right tenant+livemode.
makeDefault is set for a card saved through a Hardcount setup flow (the operator's Add payment method link, the customer's payment-update link): that card becomes the default, the card Hardcount charges next (ADR-021). Without it the store's rule applies: the first card, or a card replacing a default the bank refused for good, becomes the default; any other is added beside it.
When the saved card is the default, Stripe's copy (invoice_settings.default_payment_method) is set to it after the commit. Best-effort and cosmetic, as in SetDefault: charges read Hardcount's default (ADR-053), so a Stripe failure logs, lands as stripe_sync_error on the audit row, and never fails the attach (or the webhook behind it).
A card already removed stays removed (a late webhook, see PostgresStore.Upsert): the removed row is returned, and no Stripe call or audit row follows. When the attach moved the default from another card, a default_changed audit row follows the attached one, as Set as default and Remove's auto-promote write, so the log shows the charged card changed.
It queues no webhook event. The webhook's attach, which reports one, is AttachForWebhook.
func (*Service) CreateSetupSession ¶
func (s *Service) CreateSetupSession(ctx context.Context, tenantID, customerID, returnURL string) (checkoutURL, sessionID string, err error)
CreateSetupSession returns a hosted Stripe Checkout URL the customer can be redirected to for adding a new card without being charged. On success Stripe fires setup_intent.succeeded, which the webhook handler turns into a payment_methods row via AttachForWebhook.
func (*Service) CustomersWithDefault ¶
func (s *Service) CustomersWithDefault(ctx context.Context, tenantID string, customerIDs []string) (map[string]bool, error)
CustomersWithDefault reports which of customerIDs have an active default payment method, in one read (see Store.CustomersWithDefault).
func (*Service) Detach ¶
func (s *Service) Detach(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
Detach marks the PM detached both in Stripe and locally and, if it was the default, promotes the newest remaining chargeable PM to default — the detach + promote run in a single store transaction so there is never a committed "active cards but no default" window. The promoted default is then best-effort synced to Stripe for display parity.
func (*Service) List ¶
List returns active PMs for (tenantID, customerID). Ordered default first for UI convenience.
func (*Service) SetAuditLogger ¶
func (s *Service) SetAuditLogger(a AuditWriter)
SetAuditLogger wires the audit-log writer. Without it, paymentmethods mutations (attach via webhook, set-default, detach, setup-session creation) succeed silently — operator Activity feed and AuditLog page would miss every card-on-file change. Optional: nil = no audit row written, all other behavior unchanged.
func (*Service) SetDefault ¶
func (s *Service) SetDefault(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
SetDefault flips is_default atomically in payment_methods AND refreshes the customer_payment_setups summary row so billing sees the new card.
func (*Service) SetPortalBaseURL ¶
SetPortalBaseURL sets the dashboard address (CUSTOMER_PORTAL_URL) that a setup session returns the customer to when the caller passes no return_url. Empty means there is no such page, so CreateSetupSession refuses those calls.
type SetupLinkEmailer ¶
type SetupLinkEmailer interface {
SendPaymentSetupLink(ctx context.Context, tenantID, to, customerName, operatorNote, setupURL string) error
}
SetupLinkEmailer dispatches the operator-initiated "add a payment method" email. Satisfied by *email.Sender. operatorNote may be empty — the template falls back to a default body when so.
type SetupSessionRequest ¶
type SetupSessionRequest struct {
ReturnURL string `json:"return_url,omitempty"`
}
type SetupSessionResponse ¶
SetupSessionResponse is the setup-session 201: the Stripe Checkout page that saves a card, and its session id.
type Store ¶
type Store interface {
List(ctx context.Context, tenantID, customerID string) ([]PaymentMethod, error)
Get(ctx context.Context, tenantID, pmID string) (PaymentMethod, error)
// Upsert writes a payment_methods row keyed by stripe_payment_method_id.
// Webhooks can fire more than once for the same setup intent (Stripe
// retries on 5xx), so the webhook path must be idempotent. The row is
// made the default in the same tx when makeDefault is set (a card saved
// through a setup flow becomes the default, ADR-021), when the customer
// has no active default, or when the bank refused the current default
// for good (ADR-126), and only when it is chargeable: a method Hardcount
// can't charge is saved and never the default. replacedDefault reports
// that another card was the default and this one took its place. A card
// already removed (detached) stays removed: the row is returned
// unchanged.
//
// eventType ("" for none) is the payment_method.* webhook event the write
// reports, queued in its transaction with the card and extra as its
// data, only when the write changed what the API shows of the card.
Upsert(ctx context.Context, tenantID string, pm PaymentMethod, makeDefault bool, eventType string, extra map[string]any) (out PaymentMethod, replacedDefault bool, err error)
// SetDefault atomically clears any existing default for (customerID)
// and flags pmID as the new default. Fails with ErrNotFound if pmID is
// detached or not owned by customerID, and with ErrInvalidState if it
// is a method Hardcount can't charge. Safe to call concurrently: it
// waits for any other change to the customer's default.
SetDefault(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, error)
// DetachAndRebalance detaches pmID and, in the SAME transaction,
// promotes the newest remaining active chargeable PM to default when the
// detached card was the default — so there is never a committed "active
// cards but no default" window (a transient failure on the promote rolls
// the detach back too). Returns the detached row plus the promoted
// default (nil when the detached card wasn't the default, or no active
// chargeable PM remained to promote). Idempotent: re-detaching an
// already-detached row promotes nothing (a detached row is never the
// default). Safe to
// call concurrently: it waits for any other change to the customer's
// default, so two removals at once still leave one default.
DetachAndRebalance(ctx context.Context, tenantID, customerID, pmID string) (PaymentMethod, *PaymentMethod, error)
// CustomersWithDefault reports, in one read, which of customerIDs have
// an active (not detached) default payment method — the same row List
// puts first and the payment-setup view calls ready. Customers without
// one are absent from the map.
CustomersWithDefault(ctx context.Context, tenantID string, customerIDs []string) (map[string]bool, error)
}
Store is the persistence contract. Kept narrow — each operation maps to exactly one handler action so we don't grow a god-store.
type StripeAPI ¶
type StripeAPI interface {
// CreateSetupCheckoutSession creates a Stripe Checkout Session in
// setup mode and returns a hosted URL the customer can redirect to.
// successURL and cancelURL are separate so the SPA can render
// different copy based on the outcome (?status=success vs cancel).
// Used by the default web-v2 portal UI, which redirects rather than
// embedding Stripe Elements.
CreateSetupCheckoutSession(ctx context.Context, stripeCustomerID, successURL, cancelURL string, metadata map[string]string) (checkoutURL, sessionID string, err error)
// EnsureStripeCustomer returns the existing Stripe customer ID from
// customer_payment_setups, or creates one if absent and writes it back
// to the setup row. Needed because a customer might not have a Stripe
// customer yet when they first land on the portal.
EnsureStripeCustomer(ctx context.Context, tenantID, customerID string) (string, error)
// DetachPaymentMethod calls Stripe's detach endpoint. Best-effort — if
// Stripe has already detached (e.g. card expired and Stripe removed
// it), we still want to mark the local row detached.
DetachPaymentMethod(ctx context.Context, stripePaymentMethodID string) error
// SetDefaultPaymentMethod updates the Stripe Customer's
// invoice_settings.default_payment_method. Required so any Stripe-side
// off-session auto-charge uses the operator's chosen card, not the one
// Stripe last had on file. Pre-2026-05-29 SetDefault flipped the local
// row only; Stripe's default stayed stale. The adapter looks up the
// Stripe Customer ID via its customerLink (same pattern as
// EnsureStripeCustomer). Best-effort: returns error if Stripe is
// unreachable; caller logs + audits and the operator action still
// commits (local-wins, per Lago / Recurly / Chargebee).
SetDefaultPaymentMethod(ctx context.Context, tenantID, customerID, stripePaymentMethodID string) error
// FetchPaymentMethod looks up a Stripe PM's type and, for a card, its
// brand / last4 / exp / fingerprint. Used by the webhook handler when
// persisting a newly attached PM. Fingerprint drives dedupe-on-attach
// (see PostgresStore.Upsert).
FetchPaymentMethod(ctx context.Context, stripePaymentMethodID string) (MethodDetails, error)
}
StripeAPI is the narrow subset of Stripe we need. Declared here instead of depending on internal/payment so the paymentmethods package can be tested with a fake and so internal/payment doesn't gain a reverse dependency.
type StripeAdapter ¶
type StripeAdapter struct {
// contains filtered or unexported fields
}
StripeAdapter wires the payment-methods Service to the existing payment.StripeClients pool. Mode-aware — ResolveCtx(ctx) returns the right client for the caller's livemode, set from the auth ctx.
func NewStripeAdapter ¶
func NewStripeAdapter(clients *payment.StripeClients, customerLink CustomerStripeLink) *StripeAdapter
func (*StripeAdapter) CreateSetupCheckoutSession ¶
func (a *StripeAdapter) CreateSetupCheckoutSession(ctx context.Context, stripeCustomerID, successURL, cancelURL string, metadata map[string]string) (string, string, error)
CreateSetupCheckoutSession creates a Checkout Session in setup mode so the customer can be redirected to Stripe's hosted UI to enter card details without being charged. Mirrors payment.PortalHandler but for the self-serve /me path — the metadata we attach here is what the setup_intent.succeeded webhook routes back to the right customer.
func (*StripeAdapter) DetachPaymentMethod ¶
func (a *StripeAdapter) DetachPaymentMethod(ctx context.Context, stripePaymentMethodID string) error
func (*StripeAdapter) EnsureStripeCustomer ¶
func (a *StripeAdapter) EnsureStripeCustomer(ctx context.Context, tenantID, customerID string) (string, error)
EnsureStripeCustomer resolves (or lazily creates) the Stripe customer for this Hardcount customer. Single source of truth: customers.stripe_customer_id (migration 0096). A Hardcount customer without a Stripe Customer record gets one created here on first PM action; subsequent calls short-circuit on the persisted ID.
Stripe client lookup uses explicit (tenantID, livemode) rather than `ResolveCtx` so this method works on BOTH authenticated portal requests (auth.TenantID populated) and public token-authenticated requests (hosted-invoice Pay flow — no auth ctx, tenantID comes from the public_token row, livemode pinned by hostedinvoice.resolveInvoice).
func (*StripeAdapter) FetchPaymentMethod ¶ added in v0.11.0
func (a *StripeAdapter) FetchPaymentMethod(ctx context.Context, stripePaymentMethodID string) (MethodDetails, error)
func (*StripeAdapter) SetDefaultPaymentMethod ¶
func (a *StripeAdapter) SetDefaultPaymentMethod(ctx context.Context, tenantID, customerID, stripePaymentMethodID string) error
SetDefaultPaymentMethod points the Stripe Customer's `invoice_settings.default_payment_method` at the given PM. Resolves the Stripe Customer ID via the customerLink — the local PM row was already updated, the Stripe Customer must already exist (the PM couldn't have been attached otherwise). Returns errs.ErrNotFound if the Hardcount customer has no linked Stripe customer (out-of-band data drift); the Service treats that as a soft skip + audit row entry, not a fail, because the local default is still authoritative.