paymentsv1

import paymentsv1 "pocketone.dev/ext/contracts/payments/v1"

Package paymentsv1 is the payments/v1 contract: what a payment processor (Stripe, Paddle, Creem, ...) does for an app, behind one interface. A provider talks to its processor's API and translates; it keeps no state and knows no users. billing/v1 (ext/billing) keeps the state: who bought what, entitlements, events.

Keyed by processor name ("stripe", "paddle", "creem"): every installed processor provides it, so items bought through one keep working while new checkouts go to another. billing/v1's settings pick the one that takes checkouts.

Source: ext/contracts/payments/v1.

Constants

const (
	KindSubscription = "subscription"
	KindOrder        = "order"
	KindCustomer     = "customer"
)

Kinds of things a processor sells or knows.

const (
	Trialing   = "trialing"
	Active     = "active"
	PastDue    = "past_due"   // a payment failed; the processor is retrying
	Unpaid     = "unpaid"     // the processor gave up retrying; not active
	Paused     = "paused"     // paused at the processor; not active
	Cancelling = "cancelling" // active until EndsAt, then ends
	Ended      = "ended"
)

Subscription statuses, normalized.

const (
	Paid              = "paid"
	PartiallyRefunded = "partially_refunded"
	Refunded          = "refunded"
	Disputed          = "disputed"
)

Order statuses, normalized.

const (
	CheckoutCompleted   = "checkout.completed"
	SubscriptionChanged = "subscription.changed"
	PaymentSucceeded    = "payment.succeeded"
	PaymentFailed       = "payment.failed"
	OrderRefunded       = "order.refunded"
	DisputeOpened       = "dispute.opened"
	DisputeClosed       = "dispute.closed"
)

Event kinds, normalized. Every event names what it's about; billing re-reads that and writes what it finds, so the order events arrive in, and repeats, don't matter.

const (
	ProrateNow        = "now"         // charge or credit the difference now
	ProrateNextPeriod = "next_period" // the difference on the next invoice
	ProrateNone       = "none"        // no proration: the new amount from the next period
)

Proration says how a quantity or plan change is billed.

const (
	RefundPending = "pending" // the processor has to approve it
	RefundDone    = "done"
)

Refund states.

Variables

var Contract = extkit.NewKeyedContract[Processor]("payments/v1", func(v Processor) string { return v.Name() })

Contract is payments/v1.

var ErrBadSignature = &extkit.Error{Code: "bad_signature", Message: "missing or wrong webhook signature", Status: 401}

ErrBadSignature: a webhook call's signature is missing or wrong.

var ErrNotConfigured = &extkit.Error{Code: "not_configured", Message: "this payment processor isn't set up", Status: 503}

ErrNotConfigured: the processor's keys aren't set.

var ErrUnsupported = &extkit.Error{Code: "unsupported", Message: "this payment processor can't do that", Status: 501}

ErrUnsupported: the processor can't do this (Creem refunds only in full; LS has no proration choice).

Types

CancelInput

type CancelInput struct {
	ID          string `json:"id"`
	AtPeriodEnd bool   `json:"atPeriodEnd"`
}

CancelInput cancels a subscription.

Checkout

type Checkout struct {
	ID   string `json:"id"` // the processor's checkout/session/transaction id
	URL  string `json:"url,omitempty"`
	Page string `json:"page,omitempty"` // HTML
}

Checkout is where the buyer goes: URL, or Page to serve when the processor's checkout needs a page of the app's.

CheckoutInput

type CheckoutInput struct {
	Price      string            `json:"price"`               // the processor's price (Stripe price, Paddle pri_, Creem product, LS variant)
	Quantity   int               `json:"quantity"`            // 0 means 1
	Reference  string            `json:"reference"`           // billing's checkout id; comes back on its events
	Email      string            `json:"email,omitempty"`     // prefill
	Customer   string            `json:"customer,omitempty"`  // the processor's customer id, when known
	Metadata   map[string]string `json:"metadata,omitempty"`  // copied onto the purchase where the processor allows
	SuccessURL string            `json:"successUrl"`          //
	CancelURL  string            `json:"cancelUrl,omitempty"` //
	TrialDays  int               `json:"trialDays,omitempty"` //
	Discount   string            `json:"discount,omitempty"`  // a discount or promotion code
	Recurring  bool              `json:"recurring"`           // what billing thinks the price is; providers may check
}

CheckoutInput starts a checkout.

Event

type Event struct {
	ID        string    `json:"id"`   // the processor's event id, for the log (not unique: a manual resend may get a new one)
	Kind      string    `json:"kind"` // CheckoutCompleted ...
	About     Ref       `json:"about"`
	Customer  string    `json:"customer,omitempty"`
	Email     string    `json:"email,omitempty"`
	Reference string    `json:"reference,omitempty"`
	At        time.Time `json:"at"`
	Type      string    `json:"type"` // the processor's own event type, for the log
}

Event is one normalized webhook event.

Events

type Events struct {
	Events []Event `json:"events"`
}

Events are what one webhook call reported.

Info

type Info struct {
	Name             string `json:"name"`
	Title            string `json:"title"`            // "Stripe"
	MerchantOfRecord bool   `json:"merchantOfRecord"` // the processor sells, collects tax and handles disputes
	Sandbox          bool   `json:"sandbox"`          // test mode, test keys
	Configured       bool   `json:"configured"`       // has the keys it needs
}

Info describes a configured processor.

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

Link is a URL.

Money

type Money struct {
	Amount   int64  `json:"amount"`
	Currency string `json:"currency"`
}

Money is an amount in minor units (cents) and an ISO 4217 currency, as the processor reports it.

Order

type Order struct {
	ID        string            `json:"id"`
	Customer  string            `json:"customer"`
	Email     string            `json:"email,omitempty"`
	Price     string            `json:"price"`
	Quantity  int               `json:"quantity"`
	Status    string            `json:"status"` // Paid ... Disputed
	Amount    Money             `json:"amount"`
	CreatedAt time.Time         `json:"createdAt"`
	Reference string            `json:"reference,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	Raw       json.RawMessage   `json:"raw,omitempty"`
}

Order is a one-time purchase's state at the processor.

PlanInput

type PlanInput struct {
	ID        string `json:"id"`
	Price     string `json:"price"`
	Proration string `json:"proration"`
}

PlanInput moves a subscription to another price.

PortalInput

type PortalInput struct {
	Customer      string   `json:"customer"`                // the processor's customer id
	Subscriptions []string `json:"subscriptions,omitempty"` // focus these, where the processor allows
	ReturnURL     string   `json:"returnUrl,omitempty"`
}

PortalInput asks for a customer portal link.

Price

type Price struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Recurring bool   `json:"recurring"`
	Interval  string `json:"interval,omitempty"` // month, year
	Amount    Money  `json:"amount"`
	Active    bool   `json:"active"`
}

Price is a price at the processor.

PriceRef

type PriceRef struct {
	Price string `json:"price"`
}

PriceRef names a price at the processor.

Processor

type Processor interface {
	// Name is the processor's key ("stripe"), stored on every item it sold and used in its webhook URL.
	Name() string

	// Info describes the processor as configured: its title, whether it is the merchant of record, sandbox or live.
	Info(ctx context.Context) (Info, error)

	// Checkout starts a hosted checkout for one price and a quantity. It returns a URL, or a Page (HTML) for
	// processors whose checkout must run on a page of the app's (Paddle); billing serves that page.
	Checkout(ctx context.Context, in CheckoutInput) (Checkout, error)

	// Portal returns a link to the processor's own customer portal (cards, invoices, receipts). Links are short-lived:
	// make one per request, never store it.
	Portal(ctx context.Context, in PortalInput) (Link, error)

	// Subscription re-reads a subscription's current state from the processor.
	Subscription(ctx context.Context, in Ref) (Subscription, error)

	// Order re-reads a one-time purchase's current state from the processor.
	Order(ctx context.Context, in Ref) (Order, error)

	// Cancel ends a subscription now, or at the end of the period it's paid for.
	Cancel(ctx context.Context, in CancelInput) (Subscription, error)

	// Resume undoes a cancel scheduled for the end of the period. An ended subscription can't be resumed.
	Resume(ctx context.Context, in Ref) (Subscription, error)

	// SetQuantity changes how many units a subscription bills for.
	SetQuantity(ctx context.Context, in QuantityInput) (Subscription, error)

	// ChangePlan moves a subscription to another price.
	ChangePlan(ctx context.Context, in PlanInput) (Subscription, error)

	// Refund asks the processor to refund a payment. Merchant-of-record processors may approve it later (Pending);
	// the item changes when the refund's event arrives.
	Refund(ctx context.Context, in RefundInput) (Refund, error)

	// ParseWebhook verifies a webhook call's signature and turns it into normalized events. An event billing doesn't
	// need comes back as none (acknowledged, not retried). A bad signature is ErrBadSignature.
	ParseWebhook(ctx context.Context, in extkit.RawIn) (Events, error)

	// Price looks up a price at the processor, so an admin can check the ids they typed.
	Price(ctx context.Context, in PriceRef) (Price, error)

	// DashboardURL links to a subscription, order or customer in the processor's own dashboard ("" when it has none).
	DashboardURL(ctx context.Context, in Ref) (Link, error)
}

Processor is one payment processor.

QuantityInput

type QuantityInput struct {
	ID        string `json:"id"`
	Quantity  int    `json:"quantity"`
	Proration string `json:"proration"` // ProrateNow, ProrateNextPeriod, ProrateNone
}

QuantityInput changes a subscription's quantity.

Ref

type Ref struct {
	Kind string `json:"kind"` // KindSubscription, KindOrder, KindCustomer
	ID   string `json:"id"`
}

Ref names a subscription, order or customer at the processor.

Refund

type Refund struct {
	ID     string `json:"id"`
	Status string `json:"status"` // RefundPending or RefundDone
}

Refund is a refund's state.

RefundInput

type RefundInput struct {
	Ref    Ref    `json:"ref"`
	Amount *Money `json:"amount,omitempty"` // nil: in full (some processors only refund in full)
	Reason string `json:"reason,omitempty"`
}

RefundInput refunds an order, or a subscription's latest payment.

Subscription

type Subscription struct {
	ID        string            `json:"id"`
	Customer  string            `json:"customer"`
	Email     string            `json:"email,omitempty"`
	Price     string            `json:"price"`
	Quantity  int               `json:"quantity"`
	Status    string            `json:"status"` // Trialing ... Ended
	RenewsAt  *time.Time        `json:"renewsAt,omitempty"`
	EndsAt    *time.Time        `json:"endsAt,omitempty"` // when Cancelling or Ended
	CreatedAt time.Time         `json:"createdAt"`
	Reference string            `json:"reference,omitempty"` // the checkout's Reference, when the processor kept it
	Metadata  map[string]string `json:"metadata,omitempty"`
	Raw       json.RawMessage   `json:"raw,omitempty"` // the processor's own object, kept for support
}

Subscription is a subscription's state at the processor.