payments

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package payments is the pluggable payment-provider contract (design expansion phase 6, M26), on the sending-provider pattern: a catalog of adapters with capability badges, one connection pattern (a write-only key, checked before it is used), health, and the shared contract-test suite in internal/payments/contracttest that every adapter passes.

Readers pay the publisher through the publisher's own account: an adapter talks to that account with the workspace's own key, nothing sits in between, and ReputeCast never sees or stores card details. Adapters live in internal/payments/<name>; core code (internal/earn) talks to these interfaces and finds adapters through the registry. Stripe comes first; Paddle and Lemon Squeezy are listed as not available yet.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSecretKey refuses an unrestricted secret key: it gives full access
	// to the account, payouts included.
	ErrSecretKey = errors.New("payments: secret keys are refused; create a restricted key")
	// ErrKeyFormat is a key that isn't a restricted key of this provider.
	ErrKeyFormat = errors.New("payments: not a restricted key")
	// ErrKeyRejected means the provider refused the key (rolled, deleted or cut short).
	ErrKeyRejected = errors.New("payments: the provider rejected the key")
	// ErrBadSignature is a webhook whose signature doesn't verify, or one
	// signed too long ago (a replay).
	ErrBadSignature = errors.New("payments: webhook signature verification failed")
	// ErrUnavailable means the provider can't be reached or answers 5xx.
	ErrUnavailable = errors.New("payments: provider unavailable")
	// ErrNotFound is an object the provider doesn't have.
	ErrNotFound = errors.New("payments: not found")
	// ErrPermission is a call the key isn't allowed to make.
	ErrPermission = errors.New("payments: the key lacks a permission")
)

Errors adapters return.

Functions

func Register

func Register(d Descriptor)

Register adds an adapter; adapters call it from their package's init.

func RegisterParser

func RegisterParser(key string, v WebhookVerifier)

RegisterParser adds an adapter's webhook verifier (it needs no key).

Types

type APIError

type APIError struct {
	Status  int
	Type    string
	Code    string
	Message string
}

APIError is a provider's error answer.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is maps an API error to the package's sentinel errors.

type Account

type Account struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Country  string `json:"country"`
	Currency string `json:"currency"`
	// TaxEnabled reports whether the provider calculates tax (Stripe Tax).
	TaxEnabled bool `json:"taxEnabled"`
}

Account is what checking a key reads about the account.

type Capability

type Capability string

Capability is a badge on a provider's catalog card.

const (
	CapSubscriptions    Capability = "subscriptions"
	CapOneTime          Capability = "one_time"
	CapTrials           Capability = "trials"
	CapCoupons          Capability = "coupons"
	CapPromotionCodes   Capability = "promotion_codes"
	CapPortal           Capability = "portal"
	CapTax              Capability = "tax"
	CapMerchantOfRecord Capability = "merchant_of_record"
	CapTestMode         Capability = "test_mode"
)

Capabilities, in the order of the cards.

type Charge

type Charge struct {
	ID             string
	CustomerID     string
	InvoiceID      string
	Amount         int64
	AmountRefunded int64
	Currency       string
	// The latest refund's amount (the event's delta).
	RefundAmount int64
	// FailureMessage is the card issuer's reason for a failed charge.
	FailureMessage string
	// PaymentIntentID ties a one-time payment's charge to its checkout (a
	// gift's refund).
	PaymentIntentID string
}

Charge is a payment's charge, for refunds and disputes.

type CheckoutRequest

type CheckoutRequest struct {
	PriceID       string
	CustomerID    string
	CustomerEmail string
	TrialDays     int
	// Tax adds tax at checkout and collects the address it needs.
	Tax bool
	// PromotionCode applies an offer; AllowCodes lets readers type one.
	PromotionCode string
	AllowCodes    bool
	SuccessURL    string
	CancelURL     string
	ClientRef     string
	Metadata      map[string]string
	// TrialEndCancel ends access when a trial ends without a card on file.
	TrialEndCancel bool
}

CheckoutRequest opens a subscription checkout.

type CheckoutSession

type CheckoutSession struct {
	ID             string
	URL            string
	Status         string // open, complete, expired
	PaymentStatus  string
	CustomerID     string
	CustomerEmail  string
	SubscriptionID string
	ClientRef      string
	Metadata       map[string]string
	Livemode       bool
	// Mode is subscription or payment; a one-time payment's checkout (a
	// gift) carries its total and payment.
	Mode            string
	AmountTotal     int64
	Currency        string
	PaymentIntentID string
}

CheckoutSession is a hosted checkout.

type Client

type Client interface {
	Mode() Mode
	// CheckKey reads the account and proves each permission with a call
	// that changes nothing. ErrKeyRejected when the key isn't valid.
	CheckKey(ctx context.Context) (KeyCheck, error)
	RegisterWebhook(ctx context.Context, url string, events []string) (Webhook, error)
	// WebhookExists reports whether a registered endpoint still exists.
	WebhookExists(ctx context.Context, id string) (bool, error)
	DeleteWebhook(ctx context.Context, id string) error
	// ListEvents returns events created at or after since, oldest first.
	ListEvents(ctx context.Context, since time.Time, types []string) ([]Event, error)
	ConfigurePortal(ctx context.Context, id string, c PortalConfig) (string, error)
	PortalSession(ctx context.Context, customer string, flow PortalFlow) (string, error)
	CreateCheckout(ctx context.Context, r CheckoutRequest) (CheckoutSession, error)
	GetCheckout(ctx context.Context, id string) (CheckoutSession, error)
	// SaveProduct creates the product (empty ID) or updates it.
	SaveProduct(ctx context.Context, p Product) (Product, error)
	CreatePrice(ctx context.Context, p Price) (Price, error)
	// RetirePrice stops a price from taking new subscriptions.
	RetirePrice(ctx context.Context, id string) error
	GetPrice(ctx context.Context, id string) (Price, error)
	GetSubscription(ctx context.Context, id string) (Subscription, error)
	// GetCharge reads a charge (a failed payment's reason).
	GetCharge(ctx context.Context, id string) (Charge, error)
	// GetCustomer reads a customer (the email a subscription belongs to).
	GetCustomer(ctx context.Context, id string) (Customer, error)
	// CancelSubscription cancels at the end of the period or now.
	CancelSubscription(ctx context.Context, id string, atPeriodEnd bool) (Subscription, error)
	ListSubscriptions(ctx context.Context, cursor string) (Page[Subscription], error)
	ListCustomers(ctx context.Context, cursor string) (Page[Customer], error)
	// DashboardURL links to an object in the provider's dashboard.
	DashboardURL(kind, id string) string
}

Client talks to one connected account.

type Config

type Config struct {
	// Key is the restricted key (write-only: never logged or returned).
	Key string
	// BaseURL overrides the provider's API address (tests and the demo).
	BaseURL string
	// HTTP overrides the client (the demo's in-process provider).
	HTTP *http.Client
	// Now overrides the clock (tests).
	Now func() time.Time
}

Config opens a client on an account.

type Coupon

type Coupon struct {
	ID         string
	Name       string
	PercentOff float64
	AmountOff  int64
	Currency   string
	// Duration is once, repeating or forever; Months is a repeating
	// coupon's length.
	Duration string
	Months   int
	Products []string
	// Valid is false once the coupon was deleted or can't be redeemed.
	Valid    bool
	Metadata map[string]string
}

Coupon is a discount an offer applies (X17): a percentage or an amount, once, for a number of months or forever, optionally on some products only.

type CustomAmount

type CustomAmount struct {
	MinimumCents int64
	PresetCents  int64
}

CustomAmount lets the buyer choose the amount: at least Minimum, with Preset filled in on the provider's page.

type Customer

type Customer struct {
	ID       string
	Email    string
	Name     string
	Created  time.Time
	Deleted  bool
	Livemode bool
}

Customer is a reader as the provider knows them.

type Descriptor

type Descriptor struct {
	Key  string
	Name string
	// Available is false for providers listed as "Not available yet".
	Available bool
	// MerchantOfRecord providers sell to readers on the publisher's behalf
	// and handle sales tax and VAT.
	MerchantOfRecord bool
	Capabilities     []Capability
	// Permissions the restricted key needs, in the table's order.
	Permissions []Permission
	// WebhookEvents are the events ReputeCast subscribes to.
	WebhookEvents []string
	// KeyPrefixes are the restricted keys' prefixes per mode ("rk_live_").
	KeyPrefixes map[Mode]string
	// Open connects to an account. Nil when the provider isn't available.
	Open func(cfg Config) (Client, error)
	// Hint is the part of a key that's safe to show ("rk_live_…9fQ2").
	Hint func(key string) string
	// Dashboard links to the provider's dashboard: an object of a kind
	// ("customers", "prices"), or a page ("apikeys", "webhooks", "emails").
	Dashboard func(mode Mode, kind, id string) string
}

Descriptor describes an adapter in the catalog.

func Catalog

func Catalog() []Descriptor

Catalog lists the adapters: available ones first, then in registration order.

func Lookup

func Lookup(key string) (Descriptor, bool)

Lookup returns a registered adapter.

type Discount

type Discount struct {
	CouponID   string     `json:"couponId,omitempty"`
	Name       string     `json:"name,omitempty"`
	PromoCode  string     `json:"promoCode,omitempty"`
	PercentOff float64    `json:"percentOff,omitempty"`
	AmountOff  int64      `json:"amountOff,omitempty"`
	Duration   string     `json:"duration,omitempty"` // once, repeating, forever
	Months     int        `json:"months,omitempty"`
	Start      *time.Time `json:"start,omitempty"`
	End        *time.Time `json:"end,omitempty"`
}

Discount is a coupon applied to a subscription.

type Event

type Event struct {
	ID       string
	Type     string
	Kind     EventKind
	Created  time.Time
	Livemode bool
	// The event's object, by kind.
	Subscription *Subscription
	Invoice      *Invoice
	Charge       *Charge
	Checkout     *CheckoutSession
	Customer     *Customer
	// Previous holds the fields an update changed (Stripe's previous_attributes).
	Previous map[string]any
	Raw      []byte
}

Event is one provider event, normalized; Raw keeps it as sent.

type EventKind

type EventKind string

EventKind is what an event means, whatever the provider calls it.

const (
	EventCheckoutCompleted EventKind = "checkout_completed"
	// A delayed payment method (a bank debit) cleared, or didn't, after
	// its checkout completed.
	EventCheckoutAsyncPaid   EventKind = "checkout_async_paid"
	EventCheckoutAsyncFailed EventKind = "checkout_async_failed"
	EventSubscriptionCreated EventKind = "subscription_created"
	EventSubscriptionUpdated EventKind = "subscription_updated"
	EventSubscriptionDeleted EventKind = "subscription_deleted"
	EventTrialEnding         EventKind = "trial_ending"
	EventInvoicePaid         EventKind = "invoice_paid"
	EventPaymentFailed       EventKind = "payment_failed"
	EventInvoiceUpcoming     EventKind = "invoice_upcoming"
	EventRefunded            EventKind = "refunded"
	EventDisputeOpened       EventKind = "dispute_opened"
	EventCustomerUpdated     EventKind = "customer_updated"
	EventCustomerDeleted     EventKind = "customer_deleted"
	EventOther               EventKind = "other"
)

Event kinds.

type Invoice

type Invoice struct {
	ID             string
	CustomerID     string
	CustomerEmail  string
	SubscriptionID string
	PriceID        string
	AmountDue      int64
	AmountPaid     int64
	Currency       string
	// BillingReason: subscription_create, subscription_cycle, subscription_update…
	BillingReason string
	PeriodEnd     *time.Time
	// A failure: the provider's reason ("Your card has insufficient funds.")
	// and when it tries again.
	FailureMessage   string
	NextAttempt      *time.Time
	AttemptCount     int
	DiscountedAmount int64
	ChargeID         string
}

Invoice is a payment, a failed payment or an upcoming renewal.

type KeyCheck

type KeyCheck struct {
	Mode        Mode
	Account     Account
	Permissions []PermissionCheck
}

KeyCheck is the result of checking a key.

func (KeyCheck) Missing

func (k KeyCheck) Missing() []Permission

Missing returns the permissions the key lacks.

type Mode

type Mode string

Mode is a connection's mode: live payments or the provider's test mode, whose payments use test cards and are kept apart from everything live.

const (
	Live Mode = "live"
	Test Mode = "test"
)

Modes.

type Offers

type Offers interface {
	CreateCoupon(ctx context.Context, c Coupon) (Coupon, error)
	GetCoupon(ctx context.Context, id string) (Coupon, error)
	CreatePromotionCode(ctx context.Context, p PromotionCode) (PromotionCode, error)
	// SetPromotionCodeActive turns a code off (an offer ended early) or on.
	SetPromotionCodeActive(ctx context.Context, id string, active bool) error
	// ApplyCoupon puts a coupon on a subscription at once (the retention
	// offer a paid member accepts on the cancel page).
	ApplyCoupon(ctx context.Context, subscriptionID, couponID string) (Subscription, error)
}

Offers is what offers need from a provider that has coupons and promotion codes (X17). A client may implement it; offers stay drafts with a provider that doesn't.

type OneTimePayments

type OneTimePayments interface {
	CreatePaymentCheckout(ctx context.Context, r PaymentCheckoutRequest) (CheckoutSession, error)
}

OneTimePayments is what gifts need: a checkout for a single payment (X17). A client may implement it.

type OneTimePrice

type OneTimePrice struct {
	ProductID   string
	AmountCents int64
	Custom      *CustomAmount
	Currency    string
	// TaxInclusive marks a price that includes tax.
	TaxInclusive bool
	Metadata     map[string]string
}

OneTimePrice is a price paid once: AmountCents, or a custom amount.

type OneTimePrices

type OneTimePrices interface {
	CreateOneTimePrice(ctx context.Context, p OneTimePrice) (Price, error)
	CreatePriceCheckout(ctx context.Context, r PriceCheckoutRequest) (CheckoutSession, error)
	// GetPayment reads a payment checkout as its completion would report
	// it (the thank-you page, before the webhook arrives).
	GetPayment(ctx context.Context, sessionID string) (Payment, error)
}

OneTimePrices is implemented by clients that sell one-time prices.

type Page

type Page[T any] struct {
	Items []T
	// Next is the cursor of the next page; "" at the end.
	Next string
}

Page is one page of a list.

type Payment

type Payment struct {
	Kind PaymentKind
	// The checkout session (completed), the payment and its charge.
	SessionID       string
	PaymentIntentID string
	ChargeID        string
	// Mode is the checkout's: "payment" for one-time payments.
	Mode          string
	Paid          bool
	ClientRef     string
	CustomerEmail string
	CustomerName  string
	CustomerID    string
	AmountCents   int64
	TaxCents      int64
	Currency      string
	// Refunds: the total refunded so far, and this refund's part.
	RefundedCents int64
	RefundCents   int64
	// Disputes: the provider's id, status (needs_response,
	// under_review, won, lost…), reason ("fraudulent") and the date to
	// respond by; the fee the provider charges for it.
	DisputeID     string
	DisputeStatus string
	DisputeReason string
	DisputeDueBy  *time.Time
	DisputeFee    int64
	Metadata      map[string]string
	Livemode      bool
	Created       time.Time
}

Payment is a one-time payment as an event, or a checkout, reports it.

type PaymentCheckoutRequest

type PaymentCheckoutRequest struct {
	AmountCents   int64
	Currency      string
	Name          string
	Description   string
	CustomerEmail string
	Tax           bool
	SuccessURL    string
	CancelURL     string
	ClientRef     string
	Metadata      map[string]string
}

PaymentCheckoutRequest opens a checkout for one payment (a gift): an amount for a named item, nothing that renews.

type PaymentKind

type PaymentKind string

PaymentKind is what a one-time payment event says.

const (
	PaymentCompleted      PaymentKind = "completed"
	PaymentRefunded       PaymentKind = "refunded"
	PaymentDisputeOpened  PaymentKind = "dispute_opened"
	PaymentDisputeUpdated PaymentKind = "dispute_updated"
	PaymentDisputeClosed  PaymentKind = "dispute_closed"
	// PaymentFailed: a delayed payment method (a bank debit) didn't clear
	// after the checkout completed.
	PaymentFailed PaymentKind = "failed"
	PaymentOther  PaymentKind = "other"
)

Payment event kinds.

type PaymentParser

type PaymentParser interface {
	ParsePayment(body []byte) (Payment, error)
}

PaymentParser reads the one-time payment in an event already verified (Kind PaymentOther when the event isn't about one).

type Permission

type Permission struct {
	// Resource names it ("customers", "checkout_sessions"); the app words it.
	Resource string `json:"resource"`
	Access   string `json:"access" enum:"read,write"`
}

Permission is one access a restricted key must have, with a harmless call that proves it.

type PermissionCheck

type PermissionCheck struct {
	Permission
	OK bool `json:"ok"`
}

PermissionCheck is one permission's result.

type PortalConfig

type PortalConfig struct {
	UpdateCard   bool
	Invoices     bool
	BillingEmail bool
	SwitchPeriod bool
	Cancel       bool
	// Prices readers may switch between (product → prices).
	Products map[string][]string
	// ReturnURL is where the portal's "Return" link leads.
	ReturnURL string
	// TermsURL and PrivacyURL show in the portal's footer.
	TermsURL   string
	PrivacyURL string
}

PortalConfig is what the customer portal lets readers do.

type PortalFlow

type PortalFlow struct {
	Cancel         bool
	SubscriptionID string
	ReturnURL      string
}

PortalFlow opens the portal on one step (the cancel step of a subscription).

type Price

type Price struct {
	ID          string
	ProductID   string
	AmountCents int64
	Currency    string
	// Interval is month or year; empty for a one-time price.
	Interval string
	Active   bool
	// TaxInclusive marks a price that includes tax.
	TaxInclusive bool
	Metadata     map[string]string
}

Price is an amount per period.

type PriceCheckoutRequest

type PriceCheckoutRequest struct {
	PriceID       string
	CustomerEmail string
	// Tax adds tax at checkout and collects the address it needs.
	Tax        bool
	SuccessURL string
	CancelURL  string
	ClientRef  string
	// Metadata goes on the session and on the payment, so refunds and
	// disputes can be traced back.
	Metadata map[string]string
}

PriceCheckoutRequest opens a checkout for one one-time price.

type Product

type Product struct {
	ID          string
	Name        string
	Description string
	Active      bool
	Metadata    map[string]string
}

Product is a tier as the provider stores it.

type PromotionCode

type PromotionCode struct {
	ID       string
	Code     string
	CouponID string
	Active   bool
	// MaxRedemptions and ExpiresAt end it; FirstTimeOnly keeps it to
	// customers who never paid.
	MaxRedemptions int
	ExpiresAt      *time.Time
	FirstTimeOnly  bool
	TimesRedeemed  int
	Metadata       map[string]string
}

PromotionCode is the code readers type, or an offer link applies, for a coupon.

type Subscription

type Subscription struct {
	ID         string
	CustomerID string
	// Status is the provider's: trialing, active, past_due, canceled,
	// unpaid, incomplete, incomplete_expired, paused.
	Status            string
	PriceID           string
	ProductID         string
	Interval          string
	AmountCents       int64
	Currency          string
	StartedAt         time.Time
	TrialEnd          *time.Time
	CurrentPeriodEnd  *time.Time
	CancelAt          *time.Time
	CancelAtPeriodEnd bool
	CanceledAt        *time.Time
	EndedAt           *time.Time
	Discount          *Discount
	Metadata          map[string]string
	Livemode          bool
}

Subscription is a reader's subscription, as the provider reports it.

type Webhook

type Webhook struct {
	ID     string
	URL    string
	Events []string
	// Secret signs the provider's requests (write-only).
	Secret string
}

Webhook is an endpoint registered at the provider.

type WebhookUpdater

type WebhookUpdater interface {
	UpdateWebhookEvents(ctx context.Context, id string, events []string) error
}

WebhookUpdater changes the events a registered endpoint receives, so a webhook registered by an older version gets the events a newer one subscribes to.

type WebhookVerifier

type WebhookVerifier interface {
	// ParseWebhook verifies the signature with the endpoint's secret
	// (ErrBadSignature, also for a request signed outside the tolerance)
	// and returns the normalized event.
	ParseWebhook(header http.Header, body []byte, secret string, now time.Time) (Event, error)
	// ParseEvent reads an event already verified (stored, or read from the
	// provider's list of events).
	ParseEvent(body []byte) (Event, error)
}

WebhookVerifier checks a webhook request's signature and parses it.

func ParserFor

func ParserFor(key string) (WebhookVerifier, bool)

ParserFor returns an adapter's webhook verifier.

Directories

Path Synopsis
Package contracttest is the shared suite every payment adapter passes, like the sending adapters' (internal/providers/contracttest): the catalog entry, the key rules (restricted keys only, secret keys refused before any call), the permission check, the webhook's registration and signature (bad signatures and replays refused), checkout, products and prices, and an outage — against the adapter's fake of the provider's API, with no network.
Package contracttest is the shared suite every payment adapter passes, like the sending adapters' (internal/providers/contracttest): the catalog entry, the key rules (restricted keys only, secret keys refused before any call), the permission check, the webhook's registration and signature (bad signatures and replays refused), checkout, products and prices, and an outage — against the adapter's fake of the provider's API, with no network.
Package stripe is the Stripe payment adapter: plain HTTPS calls to Stripe's API with the workspace's restricted key (no SDK), the webhook's signature check, and the mapping of Stripe's objects onto the payments contract.
Package stripe is the Stripe payment adapter: plain HTTPS calls to Stripe's API with the workspace's restricted key (no SDK), the webhook's signature check, and the mapping of Stripe's objects onto the payments contract.
stripetest
Package stripetest is an in-memory Stripe: the subset of Stripe's API the adapter calls, answered from recorded object shapes, with restricted keys and their permissions, failure injection and helpers that complete a checkout or change a subscription and sign the webhooks Stripe would send.
Package stripetest is an in-memory Stripe: the subset of Stripe's API the adapter calls, answered from recorded object shapes, with restricted keys and their permissions, failure injection and helpers that complete a checkout or change a subscription and sign the webhooks Stripe would send.

Jump to

Keyboard shortcuts

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