payment

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package payment defines provider-neutral checkout, payment, refund, and subscription operations. Client adds portable validation and telemetry to a Driver; applications retain ownership of routes, webhooks, persistence, and fulfillment policy.

A checkout is an approval flow, not proof of payment. Pending does not mean succeeded, and an active subscription does not establish that an invoice was paid. Inspect PaymentStatus and provider observations before fulfillment. NativeStatus preserves information outside the portable status vocabulary. PreparePayment initializes an SDK authorization, order, or session without confirmation or hosted completion. Its required concrete ClientAction selects the SDK protocol. Financial and hosted references are optional observations: a session-only response need not identify any financial resource. There is no universal preparation lookup; reconcile only resources actually observed. Action, Preparation, and variant fmt/slog diagnostics redact handoff data; their JSON intentionally exposes secrets only for authorized client delivery. Applications must authorize callback destinations and protect handoff secrets. Get operations are pure reads. Only CompleteCheckout explicitly completes an approved flow; reads never hide completion. Successful mutations describe their response, not later hydration. A preflight lifecycle read may guard a mutation, and a documented no-effect state conflict may allow one bounded reconciliation read. Neither permits automatic polling or retry after an ambiguous dispatch.

Idempotency keys are caller-owned, provider-scoped, and bounded by each provider's retention window. Reuse a key only for the same operation and request. ErrOutcomeUnknown means a dispatched mutation may have succeeded; reconcile or retry with the same key within provider guarantees, never assume it failed. Cancellation is immediate and does not imply a refund or proration.

Example:

client := payment.New(driver)
request := payment.NewCheckoutRequest(payment.Money{Amount: 2500, Currency: "USD"},
	"https://shop.example/paid", "order-123")
checkout, err := client.CreateCheckout(ctx, request)
if err != nil {
	return err
}
_ = checkout.ApprovalURL

Requests are immutable values published by New*Request constructors. Optional builders run once, in order, even for invalid required inputs; nil callback entries panic. Err reports sticky first input errors without a context, while Validate checks context first. Money inputs/getters are copied. JSON validates before encoding and decodes temporary state, replacing only on success. NewMoney validates integer minor units without changing Money's record fields. Hosted return URLs still require HTTPS or loopback HTTP; preparation callbacks additionally allow custom native URI syntax. Applications own the allowlist: syntax validation cannot establish native scheme registration or ownership.

Valid calls emit one "payment <operation>" client span and the arkoren.payment.operations and arkoren.payment.operation.duration metrics. Only operation and error class are recorded: never IDs, amounts, URLs, references, native errors, or credentials. Invalid requests and already canceled contexts fail before telemetry or driver effects. Telemetry reports ErrOutcomeUnknown ahead of any joined transport or context cause; the returned error still preserves those causes for errors.Is. Nil telemetry follows telemetry.Default per call. Unsupported operations return ErrUnsupported rather than using optional capability interfaces. Preparation uses "payment prepare_payment" and the same payload-free metrics.

Builder.Events optionally selects an in-process event bus. OperationCompleted and OperationFailed report one driver-returned API-call result after telemetry ends, including reads, unsupported operations, and idempotent replays. Rejected preflight calls emit nothing. Payloads contain only fixed operation/error classes; ErrOutcomeUnknown outranks joined causes and never means failed money movement. Listener errors and panics cannot change the API result. Listeners run synchronously with the operation context; nil disables notifications. These best-effort observations are not durable reconciliation or fulfillment triggers. Provider webhooks and application-owned state persistence remain separate; no event asserts settlement or an authoritative state transition.

Example:

bus := event.New()
client := payment.New(driver, func(checkout *payment.Builder) {
	checkout.Events(bus)
})
result, err := client.GetPayment(ctx, payment.ID("pi_example"))
if err != nil {
	return err
}
_ = result.Status

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidRequest means portable input validation failed before dispatch.
	// Inspect with errors.Is; the accompanying text identifies a field, not its value.
	//
	// Example:
	//	if errors.Is(err, payment.ErrInvalidRequest) { return err }
	ErrInvalidRequest = errors.New("invalid payment request")

	// ErrInvalidState means the operation is not allowed in the resource's state.
	// A fresh read may help reconcile the state; do not blindly repeat mutations.
	//
	// Example:
	//	if errors.Is(err, payment.ErrInvalidState) { return err }
	ErrInvalidState = errors.New("invalid payment state")

	// ErrNotFound means the requested provider resource does not exist or is hidden.
	// It does not identify whether a previous ambiguous mutation succeeded.
	//
	// Example:
	//	if errors.Is(err, payment.ErrNotFound) { return err }
	ErrNotFound = errors.New("payment resource not found")

	// ErrUnsupported means a currency or operation is outside supported behavior.
	// Drivers may support fewer currencies or operations than the portable contract.
	//
	// Example:
	//	if errors.Is(err, payment.ErrUnsupported) { return err }
	ErrUnsupported = errors.New("unsupported payment operation")

	// ErrUnauthorized means provider authentication failed, not customer approval.
	// Correct credentials before retrying the operation.
	//
	// Example:
	//	if errors.Is(err, payment.ErrUnauthorized) { return err }
	ErrUnauthorized = errors.New("payment provider unauthorized")

	// ErrForbidden means authenticated credentials lack permission for the operation.
	// Changing customer checkout state will not fix provider authorization.
	//
	// Example:
	//	if errors.Is(err, payment.ErrForbidden) { return err }
	ErrForbidden = errors.New("payment provider forbidden")

	// ErrDeclined means the provider explicitly rejected the payment attempt.
	// This is a known rejection, unlike ErrOutcomeUnknown.
	//
	// Example:
	//	if errors.Is(err, payment.ErrDeclined) { return err }
	ErrDeclined = errors.New("payment declined")

	// ErrRateLimited means the provider rejected work because of a rate limit.
	// Honor provider retry policy and preserve mutation idempotency keys.
	//
	// Example:
	//	if errors.Is(err, payment.ErrRateLimited) { return err }
	ErrRateLimited = errors.New("payment provider rate limited")

	// ErrUnavailable means the provider could not serve the request with a known
	// failure. Ambiguous dispatched mutations use ErrOutcomeUnknown instead.
	//
	// Example:
	//	if errors.Is(err, payment.ErrUnavailable) { return err }
	ErrUnavailable = errors.New("payment provider unavailable")

	// ErrOutcomeUnknown means a dispatched mutation has an uncertain outcome.
	// Reconcile or retry within provider idempotency guarantees using the same key.
	//
	// Example:
	//	if errors.Is(err, payment.ErrOutcomeUnknown) { return err }
	ErrOutcomeUnknown = errors.New("payment outcome unknown")
)
View Source
var (
	// OperationCompleted reports a nil driver error after one facade call.
	// Reads, pending responses, and idempotent replays also complete; this is not
	// a payment-succeeded, refund-completed, or subscription-activated event.
	//
	// Example:
	//
	//	stop, err := bus.Listen(payment.OperationCompleted, func(ctx context.Context, observed payment.OperationEvent) error {
	//		fmt.Println(observed.Operation)
	//		return nil
	//	})
	//	if err != nil {
	//		return err
	//	}
	//	defer stop()
	OperationCompleted = event.NewTopic[OperationEvent]("payment.operation.completed")

	// OperationFailed reports a non-nil driver error, not failed money movement.
	// ErrorType payment.ErrOutcomeUnknown means the provider may have applied a
	// mutation. Reconcile using application-owned state and provider guarantees;
	// never infer that retrying with a new key is safe from this notification.
	// Validation, missing drivers, and pre-canceled calls emit neither topic.
	//
	// Example:
	//
	//	stop, err := bus.Listen(payment.OperationFailed, func(ctx context.Context, observed payment.OperationEvent) error {
	//		fmt.Println(observed.Operation, observed.ErrorType)
	//		return nil
	//	})
	//	if err != nil {
	//		return err
	//	}
	//	defer stop()
	OperationFailed = event.NewTopic[OperationEvent]("payment.operation.failed")
)

Functions

func CheckContext

func CheckContext(ctx context.Context) error

CheckContext rejects nil contexts and preserves cancellation before dispatch. Direct drivers use it, or the request/ID Validate methods which call it, before SDK calls and side effects. Nil wraps ErrInvalidRequest; canceled contexts return ctx.Err without converting it to an uncertain mutation outcome.

Example:

if err := payment.CheckContext(ctx); err != nil { return err }

func CurrencyExponent

func CurrencyExponent(currency string) (int, error)

CurrencyExponent returns the reviewed currency's number of decimal places. Unknown codes, including lowercase codes, wrap ErrUnsupported. There is no default exponent: adding a currency requires an explicit reviewed entry.

Example:

exponent, err := payment.CurrencyExponent("JPY")
if err != nil { return err }
_ = exponent // 0

Types

type Builder

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

Builder is a construction-only draft for Client observation settings. New copies it before publication; retaining a draft cannot reconfigure a client.

Example:

client := payment.New(driver, func(checkout *payment.Builder) {
	checkout.Telemetry(nil)
})
_ = client.Driver()

func (*Builder) Events

func (checkout *Builder) Events(events *event.Bus) *Builder

Events selects the shared bus for best-effort operation-result notifications. Nil disables notifications. Later calls replace earlier settings and return the same draft; changing a retained draft cannot reconfigure a published Client. Listeners observe API-call results, not settlement or authoritative provider state. Listener errors and panics cannot change the returned result or error.

Example:

bus := event.New()
client := payment.New(driver, func(checkout *payment.Builder) {
	checkout.Events(bus)
})
_ = client.Driver()

func (*Builder) Telemetry

func (checkout *Builder) Telemetry(instrumentation *telemetry.Telemetry) *Builder

Telemetry selects the shared observability service without recording payloads. Nil follows telemetry.Default on every operation, including later changes. Later calls replace earlier settings and return the same construction draft.

Example:

client := payment.New(driver, func(checkout *payment.Builder) {
	checkout.Telemetry(nil)
})
_ = client.Driver()

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc is a synchronous construction callback accepted by New. Callbacks share one fresh draft; supplied nil entries panic by design.

Example:

policy := payment.BuilderFunc(func(checkout *payment.Builder) {
	checkout.Telemetry(nil)
})
_ = payment.New(driver, policy)

type CancelSubscriptionRequest

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

CancelSubscriptionRequest requests immediate cancellation without refunds or proration. Construct it explicitly; the zero request is invalid.

Example:

request := payment.NewCancelSubscriptionRequest("sub_example")
if err := request.Err(); err != nil { return err }

func NewCancelSubscriptionRequest

func NewCancelSubscriptionRequest(id SubscriptionID, configure ...CancelSubscriptionRequestBuilderFunc) CancelSubscriptionRequest

NewCancelSubscriptionRequest snapshots an immediate-cancellation request. Callbacks run directly once in order even on invalid identity; nil entries panic and expanded nil/empty slices omit optional edits. No I/O occurs.

Example:

request := payment.NewCancelSubscriptionRequest("sub_example")
if err := request.Err(); err != nil { return err }

func (CancelSubscriptionRequest) Err

func (cancelSubscriptionRequest CancelSubscriptionRequest) Err() error

Err checks identity and sticky reason validation without context or I/O. It does not infer lifecycle, calculate proration, or issue refunds.

Example:

if err := request.Err(); err != nil { return err }

func (CancelSubscriptionRequest) MarshalJSON

func (cancelSubscriptionRequest CancelSubscriptionRequest) MarshalJSON() ([]byte, error)

MarshalJSON preserves cancellation tags and omits empty reason. Any remembered construction error prevents encoding, even after a later valid replacement.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (CancelSubscriptionRequest) Reason

func (cancelSubscriptionRequest CancelSubscriptionRequest) Reason() string

Reason returns optional provider-visible cancellation text verbatim. Empty means omitted; no default explanation is fabricated.

Example:

_ = request.Reason()

func (CancelSubscriptionRequest) SubscriptionID

func (cancelSubscriptionRequest CancelSubscriptionRequest) SubscriptionID() SubscriptionID

SubscriptionID returns the opaque subscription identity without a lookup. It is not a plan reference or proof that cancellation is currently allowed.

Example:

_ = request.SubscriptionID()

func (*CancelSubscriptionRequest) UnmarshalJSON

func (cancelSubscriptionRequest *CancelSubscriptionRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON validates a fresh temporary value before replacing the receiver. A failure leaves its previous payload and validation state untouched.

Example:

if err := json.Unmarshal(data, &request); err != nil { return err }

func (CancelSubscriptionRequest) Validate

func (cancelSubscriptionRequest CancelSubscriptionRequest) Validate(ctx context.Context) error

Validate checks context first, then Err. An expired operation never reaches the driver even if the request also contains invalid input.

Example:

if err := request.Validate(ctx); err != nil { return err }

type CancelSubscriptionRequestBuilder

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

CancelSubscriptionRequestBuilder edits a fresh cancellation draft. Publication copies it, so later edits through a retained draft cannot change requests.

Example:

request := payment.NewCancelSubscriptionRequest("sub_example", func(details *payment.CancelSubscriptionRequestBuilder) {
	details.Reason("Customer request")
})
_ = request.Reason()

func (*CancelSubscriptionRequestBuilder) Reason

Reason replaces optional provider-visible text, at most 128 runes with no controls. Invalid settings remain errors even after a valid replacement.

Example:

var configure payment.CancelSubscriptionRequestBuilderFunc = func(details *payment.CancelSubscriptionRequestBuilder) {
	details.Reason("Customer request")
}
_ = configure

type CancelSubscriptionRequestBuilderFunc

type CancelSubscriptionRequestBuilderFunc = func(*CancelSubscriptionRequestBuilder)

CancelSubscriptionRequestBuilderFunc edits cancellation synchronously. All callbacks run once in order even on invalid input; nil entries panic.

Example:

var configure payment.CancelSubscriptionRequestBuilderFunc = func(details *payment.CancelSubscriptionRequestBuilder) {
	details.Reason("Customer request")
}
_ = configure

type Checkout

type Checkout struct {
	// ID identifies the provider checkout for reads. Preserve it verbatim.
	//
	// Example: _ = payment.Checkout{ID: "cs_example"}
	ID CheckoutID `json:"id"`

	// Kind distinguishes payment and subscription flows. Zero means unknown.
	//
	// Example: _ = payment.Checkout{Kind: payment.CheckoutKindPayment}
	Kind CheckoutKind `json:"kind,omitzero"`

	// Status describes approval, not payment success. Unknown preserves unmapped states.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusOpen}
	Status CheckoutStatus `json:"status,omitzero"`

	// NativeStatus preserves the provider status token, never a response or error payload.
	//
	// Example: _ = payment.Checkout{NativeStatus: "CREATED"}
	NativeStatus string `json:"native_status,omitzero"`

	// ApprovalURL is the optional customer approval location. Never log or instrument it.
	//
	// Example: _ = payment.Checkout{ApprovalURL: "https://pay.example/approve"}
	ApprovalURL string `json:"approval_url,omitzero"`

	// NeedsCompletion requires explicit CompleteCheckout. False does not imply payment success.
	//
	// Example: _ = payment.Checkout{NeedsCompletion: true}
	NeedsCompletion bool `json:"needs_completion,omitzero"`

	// PaymentID identifies an observed payment. Unknown stays empty without hidden hydration.
	//
	// Example: _ = payment.Checkout{PaymentID: "pi_example"}
	PaymentID ID `json:"payment_id,omitzero"`

	// SubscriptionID identifies an observed subscription. Unknown stays empty.
	//
	// Example: _ = payment.Checkout{SubscriptionID: "sub_example"}
	SubscriptionID SubscriptionID `json:"subscription_id,omitzero"`

	// PaymentStatus describes money, not approval. NotRequired permits trials and free flows.
	//
	// Example: _ = payment.Checkout{PaymentStatus: payment.StatusPending}
	PaymentStatus Status `json:"payment_status,omitzero"`

	// Amount reports observed minor units. Nil means unknown; the caller owns the pointer.
	//
	// Example: _ = payment.Checkout{Amount: &payment.Money{Amount: 2500, Currency: "USD"}}
	Amount *Money `json:"amount,omitzero"`

	// Reference correlates application data. It is optional, not an ID or idempotency key.
	//
	// Example: _ = payment.Checkout{Reference: "order-123"}
	Reference string `json:"reference,omitzero"`
}

Checkout is a snapshot of an approval flow, not proof that money moved. Optional relationships and amounts remain absent until observed. Drivers return detached records; callers own optional pointers in returned snapshots.

Example:

checkout := payment.Checkout{ID: "cs_example", Status: payment.CheckoutStatusOpen}
_ = checkout.PaymentStatus // unknown, not succeeded

type CheckoutID

type CheckoutID string

CheckoutID is an opaque provider checkout identity, scoped to its driver. Preserve it verbatim; it is not an application order ID or approval URL.

Example: id := payment.CheckoutID("cs_example"); _ = id

func (CheckoutID) Validate

func (checkoutID CheckoutID) Validate(ctx context.Context) error

Validate checks ctx before the portable checkout identifier syntax. Nil contexts and invalid IDs wrap ErrInvalidRequest; cancellation is preserved.

Example:

if err := payment.CheckoutID("cs_example").Validate(ctx); err != nil { return err }

type CheckoutKind

type CheckoutKind string

CheckoutKind distinguishes one-time payment and subscription approval flows. Its zero value is unknown, not a payment flow.

Example:

checkout := payment.Checkout{Kind: payment.CheckoutKindPayment}
_ = checkout.Kind
const (
	// CheckoutKindUnknown preserves a missing or unrecognized checkout kind.
	// Do not infer a payment from this zero value.
	//
	// Example: _ = payment.Checkout{Kind: payment.CheckoutKindUnknown}
	CheckoutKindUnknown CheckoutKind = ""
	// CheckoutKindPayment identifies a one-time payment approval flow.
	// Completion is distinct from money movement.
	//
	// Example: _ = payment.Checkout{Kind: payment.CheckoutKindPayment}
	CheckoutKindPayment CheckoutKind = "payment"
	// CheckoutKindSubscription identifies a subscription approval flow.
	// Its completion need not imply that an invoice has been paid.
	//
	// Example: _ = payment.Checkout{Kind: payment.CheckoutKindSubscription}
	CheckoutKindSubscription CheckoutKind = "subscription"
)

type CheckoutRequest

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

CheckoutRequest is an immutable hosted approval request. Its zero value is invalid; JSON preserves the hosted wire shape and rejects invalid values.

Example:

request := payment.NewCheckoutRequest(amount, "https://shop.example/paid", "order-1")
if err := request.Err(); err != nil { return err }

func NewCheckoutRequest

func NewCheckoutRequest(amount Money, returnURL, key string, configure ...CheckoutRequestBuilderFunc) CheckoutRequest

NewCheckoutRequest publishes a detached hosted request without I/O. Required input errors precede optional errors. Callbacks run once synchronously in order even on invalid input; nil entries panic and empty callback slices omit edits.

Example:

request := payment.NewCheckoutRequest(payment.Money{Amount: 2500, Currency: "USD"},
	"https://shop.example/paid", "order-1")
if err := request.Err(); err != nil { return err }

func (CheckoutRequest) Amount

func (checkoutRequest CheckoutRequest) Amount() Money

Amount returns a Money copy. Changing that copy cannot mutate the request. Currency and amount remain exactly as supplied, without normalization.

Example:

amount := request.Amount()
_ = amount.Currency

func (CheckoutRequest) CancelURL

func (checkoutRequest CheckoutRequest) CancelURL() string

CancelURL returns the optional cancellation location. Empty means omitted; individual providers can require a nonempty value.

Example:

_ = request.CancelURL()

func (CheckoutRequest) Description

func (checkoutRequest CheckoutRequest) Description() string

Description returns optional provider-visible text verbatim. Empty means no description was supplied, not a provider-generated description.

Example:

_ = request.Description()

func (CheckoutRequest) Err

func (checkoutRequest CheckoutRequest) Err() error

Err reports the first invalid construction input or invalid zero value. Unsupported currencies wrap ErrUnsupported; other portable validation failures wrap ErrInvalidRequest. Diagnostics disclose no input values and require no context or I/O. The original error stays sticky after later builder edits.

Example:

request := payment.NewCheckoutRequest(payment.Money{Amount: 100, Currency: "XYZ"},
	"https://shop.example/paid", "order-1")
if err := request.Err(); err != nil {
	if errors.Is(err, payment.ErrUnsupported) {
		return fmt.Errorf("select a supported currency: %w", err)
	}
	return err
}

func (CheckoutRequest) IdempotencyKey

func (checkoutRequest CheckoutRequest) IdempotencyKey() string

IdempotencyKey returns the mutation key verbatim. Reuse only for the same payload within the provider's account scope and retention period.

Example:

_ = request.IdempotencyKey()

func (CheckoutRequest) MarshalJSON

func (checkoutRequest CheckoutRequest) MarshalJSON() ([]byte, error)

MarshalJSON emits the existing snake_case hosted shape only when valid. Invalid construction errors are returned rather than serialized.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (CheckoutRequest) Reference

func (checkoutRequest CheckoutRequest) Reference() string

Reference returns application correlation text, not provider resource identity. Its presence never implies authorization or a successful lookup.

Example:

_ = request.Reference()

func (CheckoutRequest) ReturnURL

func (checkoutRequest CheckoutRequest) ReturnURL() string

ReturnURL returns the hosted return location verbatim, preserving the literal {CHECKOUT_SESSION_ID} placeholder supported by hosted providers.

Example:

_ = request.ReturnURL()

func (*CheckoutRequest) UnmarshalJSON

func (checkoutRequest *CheckoutRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON validates fresh state and replaces the receiver only on success. A failed decode preserves the previous value, including any remembered error.

Example:

var request payment.CheckoutRequest
if err := json.Unmarshal(data, &request); err != nil { return err }

func (CheckoutRequest) Validate

func (checkoutRequest CheckoutRequest) Validate(ctx context.Context) error

Validate checks context before Err, preserving cancellation before domain errors or dispatch. It performs no provider or lifecycle lookup.

Example:

if err := request.Validate(ctx); err != nil { return err }

type CheckoutRequestBuilder

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

CheckoutRequestBuilder edits one fresh hosted request draft. Retaining it cannot change published requests; invalid settings remain sticky.

Example:

request := payment.NewCheckoutRequest(amount, "https://shop.example/paid", "order-1",
	func(details *payment.CheckoutRequestBuilder) {
		details.Description("Book")
	})
_ = request.Description()

func (*CheckoutRequestBuilder) CancelURL

func (details *CheckoutRequestBuilder) CancelURL(value string) *CheckoutRequestBuilder

CancelURL replaces the optional hosted cancellation location. Empty omits it; nonempty input requires HTTPS or loopback HTTP, never native schemes.

Example:

var cancel payment.CheckoutRequestBuilderFunc = func(details *payment.CheckoutRequestBuilder) {
	details.CancelURL("https://shop.example/cart")
}
_ = cancel

func (*CheckoutRequestBuilder) Description

func (details *CheckoutRequestBuilder) Description(value string) *CheckoutRequestBuilder

Description replaces optional text, limited to 127 runes without controls. Invalid input remains an error even if another call replaces the value.

Example:

var describe payment.CheckoutRequestBuilderFunc = func(details *payment.CheckoutRequestBuilder) {
	details.Description("Book order")
}
_ = describe

func (*CheckoutRequestBuilder) Reference

func (details *CheckoutRequestBuilder) Reference(value string) *CheckoutRequestBuilder

Reference replaces optional application correlation text, at most 127 runes. It must contain no controls or secrets and is not an idempotency key.

Example:

var correlate payment.CheckoutRequestBuilderFunc = func(details *payment.CheckoutRequestBuilder) {
	details.Reference("order-123")
}
_ = correlate

type CheckoutRequestBuilderFunc

type CheckoutRequestBuilderFunc = func(*CheckoutRequestBuilder)

CheckoutRequestBuilderFunc edits a hosted request synchronously. Callbacks run once in order, including invalid declarations; supplied nil entries panic.

Example:

var describe payment.CheckoutRequestBuilderFunc = func(details *payment.CheckoutRequestBuilder) {
	details.Description("Book")
}
_ = payment.NewCheckoutRequest(amount, "https://shop.example/paid", "order-1", describe)

type CheckoutStatus

type CheckoutStatus string

CheckoutStatus describes the approval flow, not the payment's success. Preserve NativeStatus when a provider state cannot be represented.

Example: _ = payment.Checkout{Status: payment.CheckoutStatusOpen}

const (
	// CheckoutStatusUnknown preserves an absent or unmapped provider state.
	// It provides no evidence of approval or payment.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusUnknown}
	CheckoutStatusUnknown CheckoutStatus = ""
	// CheckoutStatusOpen means the customer can still approve the checkout.
	// It is not evidence that a payment attempt succeeded.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusOpen}
	CheckoutStatusOpen CheckoutStatus = "open"
	// CheckoutStatusApproved means customer approval has been observed.
	// NeedsCompletion determines whether explicit completion remains necessary.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusApproved}
	CheckoutStatusApproved CheckoutStatus = "approved"
	// CheckoutStatusComplete means the approval flow has completed.
	// Inspect PaymentStatus separately before fulfilling an order.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusComplete}
	CheckoutStatusComplete CheckoutStatus = "complete"
	// CheckoutStatusExpired means the provider's approval window ended.
	// It does not describe an independently observed payment's status.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusExpired}
	CheckoutStatusExpired CheckoutStatus = "expired"
	// CheckoutStatusCanceled means the approval flow was canceled.
	// It does not imply a refund of previously moved funds.
	//
	// Example: _ = payment.Checkout{Status: payment.CheckoutStatusCanceled}
	CheckoutStatusCanceled CheckoutStatus = "canceled"
)

type Client

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

Client validates portable inputs and instruments a concurrency-safe Driver. It owns no lifecycle, webhook handling, retry policy, or fulfillment state. Construct it with New; its settings are immutable after publication.

Example:

client := payment.New(driver)
checkout, err := client.GetCheckout(ctx, payment.CheckoutID("cs_example"))
if err != nil { return err }
_ = checkout.Status

func New

func New(driver Driver, configure ...BuilderFunc) *Client

New creates a Client without I/O. Callbacks run directly once, synchronously in order on one fresh draft. Nil entries panic; expanded nil/empty slices omit edits. Completed settings are copied; driver, telemetry, and event bus stay shared. A nil driver is rejected on use with ErrInvalidRequest before telemetry. Optional events report API-call results, not settlement; see OperationEvent.

Example:

client := payment.New(driver, func(checkout *payment.Builder) {
	checkout.Telemetry(nil)
})
_ = client.Driver()

func (*Client) CancelSubscription

func (client *Client) CancelSubscription(ctx context.Context, request CancelSubscriptionRequest) error

CancelSubscription immediately cancels without a refund or proration. It neither schedules a future cancellation nor reads after mutation. An uncertain dispatched outcome preserves ErrOutcomeUnknown for reconciliation.

Example:

if err := client.CancelSubscription(ctx, request); err != nil { return err }

func (*Client) CompleteCheckout

func (client *Client) CompleteCheckout(ctx context.Context, request CompleteCheckoutRequest) (Checkout, error)

CompleteCheckout explicitly completes provider-required approval using its own idempotency key. Provider-completed flows are observed without another charge; successful mutations are not followed by hydration reads.

Example:

checkout, err := client.CompleteCheckout(ctx, request)
if err != nil { return err }
_ = checkout.PaymentStatus

func (*Client) CreateCheckout

func (client *Client) CreateCheckout(ctx context.Context, request CheckoutRequest) (Checkout, error)

CreateCheckout validates a positive amount and starts customer approval. It never completes checkout, retries mutations, or performs a follow-up read. Errors preserve provider sentinel identity under an operation-name wrapper.

Example:

checkout, err := client.CreateCheckout(ctx, request)
if err != nil { return err }
_ = checkout.ApprovalURL

func (*Client) CreateSubscriptionCheckout

func (client *Client) CreateSubscriptionCheckout(
	ctx context.Context, request SubscriptionCheckoutRequest,
) (Checkout, error)

CreateSubscriptionCheckout validates and starts approval of an existing plan. No catalog, invoice, entitlement, or post-mutation read is created implicitly. Errors preserve provider sentinel identity under an operation-name wrapper.

Example:

checkout, err := client.CreateSubscriptionCheckout(ctx, request)
if err != nil { return err }
_ = checkout.ApprovalURL

func (*Client) Driver

func (client *Client) Driver() Driver

Driver returns the originally supplied backend, including any wrapping driver. Using it directly bypasses facade telemetry and operation notifications, not the driver's validation duties.

Example:

client := payment.New(driver)
backend := client.Driver()
_ = backend

func (*Client) DriverAs

func (client *Client) DriverAs[T any]() (T, bool)

DriverAs finds the first backend of type T through Unwrap() Driver wrappers. It returns T's zero value and false when no matching backend exists.

Example:

backend, ok := payment.New(driver).DriverAs[payment.Driver]()
if ok { _ = backend }

func (*Client) GetCheckout

func (client *Client) GetCheckout(ctx context.Context, id CheckoutID) (Checkout, error)

GetCheckout validates the identity and observes approval and payment status. It never captures funds, activates a subscription, or completes approval.

Example:

checkout, err := client.GetCheckout(ctx, payment.CheckoutID("cs_example"))
if err != nil { return err }
_ = checkout.NeedsCompletion

func (*Client) GetPayment

func (client *Client) GetPayment(ctx context.Context, id ID) (Payment, error)

GetPayment observes an individual payment without initiating money movement. Pending never counts as success, and refunds remain separate resources.

Example:

result, err := client.GetPayment(ctx, payment.ID("pi_example"))
if err != nil { return err }
_ = result.Status

func (*Client) GetRefund

func (client *Client) GetRefund(ctx context.Context, id RefundID) (Refund, error)

GetRefund reads the refund's own progress without resubmitting it. Pending or RequiresAction must not be interpreted as successful returned funds.

Example:

refund, err := client.GetRefund(ctx, payment.RefundID("re_example"))
if err != nil { return err }
_ = refund.Status

func (*Client) GetSubscription

func (client *Client) GetSubscription(ctx context.Context, id SubscriptionID) (Subscription, error)

GetSubscription reads lifecycle without activation or invoice settlement. Active and NextBillingAt must not be interpreted as paid-through evidence.

Example:

subscription, err := client.GetSubscription(ctx, payment.SubscriptionID("sub_example"))
if err != nil { return err }
_ = subscription.Status

func (*Client) PreparePayment

func (client *Client) PreparePayment(ctx context.Context, request PreparePaymentRequest) (Preparation, error)

PreparePayment validates and initializes a client-side payment handoff. It never confirms, completes hosted checkout, retries, or hydrates a successful response. Action secrets are excluded from telemetry. Optional resource IDs remain absent when the provider returns only a session or client order.

Example:

prepared, err := client.PreparePayment(ctx, payment.NewPreparePaymentRequest(amount, "order-1"))
if err != nil { return err }
_ = prepared.Action.Kind()

func (*Client) RefundPayment

func (client *Client) RefundPayment(ctx context.Context, request RefundRequest) (Refund, error)

RefundPayment requests a positive explicit amount without a hidden balance lookup. Submission may produce a pending refund rather than immediate success.

Example:

refund, err := client.RefundPayment(ctx, request)
if err != nil { return err }
_ = refund.Status

type ClientAction

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

ClientAction is a concrete immutable, privately tagged handoff union. Only one variant can be constructed; Err rejects zero, unknown tags, or mixed JSON variants. Typed accessors return scalar copies. Diagnostics redact handoff values, while JSON deliberately includes them for the authorized client.

Example:

action := payment.NewClientOrder("paypal.order", "ORDER-1")
if err := action.Err(); err != nil { return err }
order, ok := action.Order()
_ = order; _ = ok

func NewClientAuthorization

func NewClientAuthorization(protocol ClientProtocol, token string) ClientAction

NewClientAuthorization copies a provider authorization token into an immutable action. Invalid protocol or empty/control-bearing token fails Err and encoding. No SDK call, confirmation, or funds movement occurs.

Example:

action := payment.NewClientAuthorization("stripe.payment_intent", "client-secret")
if err := action.Err(); err != nil { return err }

func NewClientOrder

func NewClientOrder(protocol ClientProtocol, orderID string) ClientAction

NewClientOrder copies an opaque client order identity into an immutable action. Err rejects invalid protocol or identity syntax; it never treats the order as a captured payment or queries the provider.

Example:

action := payment.NewClientOrder("paypal.order", "ORDER-1")
if err := action.Err(); err != nil { return err }

func NewClientSession

func NewClientSession(protocol ClientProtocol, sessionID SessionID, data string) ClientAction

NewClientSession copies an opaque session identity and SDK data string. Financial references need not exist. Err rejects invalid identity/protocol or empty/control-bearing data; no arbitrary JSON interpretation occurs.

Example:

action := payment.NewClientSession("vendor.session", "session-1", "opaque-sdk-data")
if err := action.Err(); err != nil { return err }

func (ClientAction) Authorization

func (clientAction ClientAction) Authorization() (ClientAuthorization, bool)

Authorization returns a detached token record only for the authorization variant; a different kind returns zero and false. Handle Token as a credential.

Example:

if authorization, ok := action.Authorization(); ok { _ = authorization.Token }

func (ClientAction) Err

func (clientAction ClientAction) Err() error

Err validates the discriminant, protocol syntax, and required variant fields. Constructors and decoding enforce exclusivity; diagnostics wrap ErrInvalidRequest without exposing handoff values.

Example:

if err := action.Err(); err != nil { return err }

func (ClientAction) GoString

func (clientAction ClientAction) GoString() string

GoString redacts handoff fields under fmt's Go-syntax formatting as well. It never prints protocol, identifiers, token, or session data.

Example:

_ = fmt.Sprintf("%#v", action)

func (ClientAction) Kind

func (clientAction ClientAction) Kind() ClientActionKind

Kind returns the discriminant without inferring settlement or initialization success. Use Err before consuming values obtained outside trusted code.

Example:

_ = action.Kind()

func (ClientAction) LogValue

func (clientAction ClientAction) LogValue() slog.Value

LogValue supplies a redacted slog value, independent of the handler format. It must not be replaced by JSON marshaling in a diagnostic handler.

Example:

slog.Info("prepared", "action", action)

func (ClientAction) MarshalJSON

func (clientAction ClientAction) MarshalJSON() ([]byte, error)

MarshalJSON intentionally exposes a valid tagged action to an authorized client. Do not use JSON serialization for diagnostics or telemetry.

Example:

data, err := json.Marshal(action)
if err != nil { return err }
_ = data // authorized client delivery only

func (ClientAction) Order

func (clientAction ClientAction) Order() (ClientOrder, bool)

Order returns the client-order record only for the order variant. A different kind returns zero and false; OrderID is never promoted to financial identity.

Example:

if order, ok := action.Order(); ok { _ = order.OrderID }

func (ClientAction) Protocol

func (clientAction ClientAction) Protocol() ClientProtocol

Protocol returns the SDK handoff protocol verbatim. Unknown valid identifiers are allowed for third-party adapters, not silently normalized or registered.

Example:

_ = action.Protocol()

func (ClientAction) Session

func (clientAction ClientAction) Session() (ClientSession, bool)

Session returns a copied session record only for the session variant. A different kind returns zero and false; no financial reference is fabricated.

Example:

if session, ok := action.Session(); ok { _ = session.SessionID }

func (ClientAction) String

func (clientAction ClientAction) String() string

String redacts every handoff field in ordinary fmt diagnostics. JSON remains intentionally credential-bearing and must not be used as a logging substitute.

Example:

_ = fmt.Sprint(action) // ClientAction{REDACTED}

func (*ClientAction) UnmarshalJSON

func (clientAction *ClientAction) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects unknown members, tags, and mixed variants before replacing the receiver. A failure leaves any existing handoff value unchanged.

Example:

if err := json.Unmarshal(data, &action); err != nil { return err }

type ClientActionKind

type ClientActionKind string

ClientActionKind is the discriminant for the concrete immutable ClientAction. Unknown or empty kinds are invalid rather than an unspecified success.

Example:

if action.Kind() == payment.ClientActionKindAuthorization { _, _ = action.Authorization() }
const (
	// ClientActionKindAuthorization selects the authorization-token variant.
	// Example: _ = action.Kind() == payment.ClientActionKindAuthorization
	ClientActionKindAuthorization ClientActionKind = "authorization"
	// ClientActionKindOrder selects the client-order variant, not a paid payment.
	// Example: _ = action.Kind() == payment.ClientActionKindOrder
	ClientActionKindOrder ClientActionKind = "order"
	// ClientActionKindSession selects the opaque client-session variant.
	// Example: _ = action.Kind() == payment.ClientActionKindSession
	ClientActionKindSession ClientActionKind = "session"
)

type ClientAuthorization

type ClientAuthorization struct {
	// Protocol identifies the SDK protocol that must consume Token.
	// Example: if authorization, ok := action.Authorization(); ok { _ = authorization.Protocol }
	Protocol ClientProtocol `json:"protocol"`
	// Token is secret handoff material, not a payment status or authentication key.
	// Example: if authorization, ok := action.Authorization(); ok { _ = authorization.Token }
	Token string `json:"token"`
}

ClientAuthorization is an authorized client handoff record, never evidence of settlement. Diagnostics redact all fields; JSON intentionally exposes the token for delivery only to the authorized client. Treat copies as credentials.

Example:

if authorization, ok := action.Authorization(); ok { _ = authorization.Token }

func (ClientAuthorization) GoString

func (clientAuthorization ClientAuthorization) GoString() string

GoString also redacts Go-syntax authorization formatting. It does not expose secrets even when the record is nested in another diagnostic value.

Example:

_ = fmt.Sprintf("%#v", authorization)

func (ClientAuthorization) LogValue

func (clientAuthorization ClientAuthorization) LogValue() slog.Value

LogValue redacts authorization fields for structured logging. JSON is a separate, intentional credential-bearing client transport.

Example:

slog.Info("handoff", "authorization", authorization)

func (ClientAuthorization) String

func (clientAuthorization ClientAuthorization) String() string

String redacts the authorization record, including its token and protocol. Use typed fields only when intentionally handing data to an authorized client.

Example:

_ = fmt.Sprint(authorization)

type ClientChannel

type ClientChannel string

ClientChannel describes the intended client platform, not a payment method. Empty is valid and means unspecified; other values must be known constants.

Example:

var channel payment.ClientChannel = payment.ClientChannelIOS
_ = channel
const (
	// ClientChannelWeb identifies a browser handoff, without promising a redirect.
	// Example: details.Channel(payment.ClientChannelWeb)
	ClientChannelWeb ClientChannel = "web"
	// ClientChannelIOS identifies an iOS SDK handoff, not Apple Pay acceptance.
	// Example: details.Channel(payment.ClientChannelIOS)
	ClientChannelIOS ClientChannel = "ios"
	// ClientChannelAndroid identifies an Android SDK handoff, not Google Pay acceptance.
	// Example: details.Channel(payment.ClientChannelAndroid)
	ClientChannelAndroid ClientChannel = "android"
)

type ClientOrder

type ClientOrder struct {
	// Protocol identifies the SDK protocol that understands OrderID.
	// Example: if order, ok := action.Order(); ok { _ = order.Protocol }
	Protocol ClientProtocol `json:"protocol"`
	// OrderID is the provider's client order, not payment.ID or proof of capture.
	// Example: if order, ok := action.Order(); ok { _ = order.OrderID }
	OrderID string `json:"order_id"`
}

ClientOrder is an SDK order handoff, not a financial payment observation. Diagnostics are redacted; JSON is intentionally client-visible and must be delivered only after application authorization.

Example:

if order, ok := action.Order(); ok { _ = order.OrderID }

func (ClientOrder) GoString

func (clientOrder ClientOrder) GoString() string

GoString redacts Go-syntax order formatting as well. It must not reveal an order identity merely because diagnostics request expanded formatting.

Example:

_ = fmt.Sprintf("%#v", order)

func (ClientOrder) LogValue

func (clientOrder ClientOrder) LogValue() slog.Value

LogValue returns a redacted structured order value. It intentionally does not reuse JSON, which is reserved for authorized client delivery.

Example:

slog.Info("handoff", "order", order)

func (ClientOrder) String

func (clientOrder ClientOrder) String() string

String redacts the order identity and protocol in ordinary diagnostics. The order remains available through its fields for authorized SDK handoff.

Example:

_ = fmt.Sprint(order)

type ClientProtocol

type ClientProtocol string

ClientProtocol names an actual provider/client handoff protocol, not a generic payment method. Lowercase identifiers with optional dot-separated components up to 255 bytes are accepted; underscores and hyphens are permitted in each component after its initial letter. Empty components are invalid. Third-party adapters can define their own identifiers without registration.

Example:

action := payment.NewClientAuthorization(payment.ClientProtocol("stripe.payment_intent"), "client-secret")
if err := action.Err(); err != nil { return err }
const (
	// ClientProtocolStripePaymentIntent identifies a Stripe PaymentIntent secret.
	// Example: action := payment.NewClientAuthorization(payment.ClientProtocolStripePaymentIntent, "secret"); _ = action
	ClientProtocolStripePaymentIntent ClientProtocol = "stripe.payment_intent"
	// ClientProtocolPayPalOrder identifies a PayPal client order handoff.
	// Example: action := payment.NewClientOrder(payment.ClientProtocolPayPalOrder, "ORDER-1"); _ = action
	ClientProtocolPayPalOrder ClientProtocol = "paypal.order"
	// ClientProtocolMemoryAuthorization identifies an inert simulator token.
	// Example: action := payment.NewClientAuthorization(payment.ClientProtocolMemoryAuthorization, "simulated-1"); _ = action
	ClientProtocolMemoryAuthorization ClientProtocol = "memory.authorization"
)

type ClientSession

type ClientSession struct {
	// Protocol identifies the SDK protocol that must consume the session.
	// Example: if session, ok := action.Session(); ok { _ = session.Protocol }
	Protocol ClientProtocol `json:"protocol"`
	// SessionID is client-session identity, never financial payment identity.
	// Example: if session, ok := action.Session(); ok { _ = session.SessionID }
	SessionID SessionID `json:"session_id"`
	// Data is an opaque SDK string, not a toolkit-interpreted JSON object.
	// Example: if session, ok := action.Session(); ok { _ = session.Data }
	Data string `json:"data"`
}

ClientSession contains an opaque SDK session, not an arbitrary JSON metadata bag. Session data may be secret; diagnostics redact it while JSON intentionally exposes it to an authorized client. No financial resource need exist yet.

Example:

if session, ok := action.Session(); ok { _ = session.Data }

func (ClientSession) GoString

func (clientSession ClientSession) GoString() string

GoString redacts Go-syntax session formatting. Session data must never become visible through expanded diagnostic formatting.

Example:

_ = fmt.Sprintf("%#v", session)

func (ClientSession) LogValue

func (clientSession ClientSession) LogValue() slog.Value

LogValue supplies only a redacted session string to structured handlers. Authorized JSON serialization remains separate and intentionally exposes Data.

Example:

slog.Info("handoff", "session", session)

func (ClientSession) String

func (clientSession ClientSession) String() string

String redacts opaque session data and identity in ordinary fmt diagnostics. Access fields explicitly only for authorized client handoff.

Example:

_ = fmt.Sprint(session)

type CompleteCheckoutRequest

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

CompleteCheckoutRequest immutably identifies an explicit completion attempt. It cannot establish approval; the zero request is invalid.

Example:

request := payment.NewCompleteCheckoutRequest("cs_example", "capture-1")
if err := request.Err(); err != nil { return err }

func NewCompleteCheckoutRequest

func NewCompleteCheckoutRequest(id CheckoutID, key string) CompleteCheckoutRequest

NewCompleteCheckoutRequest snapshots completion identity and key without I/O. Invalid values remain observable through Err and fail validation or JSON.

Example:

request := payment.NewCompleteCheckoutRequest("cs_example", "capture-1")
if err := request.Err(); err != nil { return err }

func (CompleteCheckoutRequest) CheckoutID

func (completeCheckoutRequest CompleteCheckoutRequest) CheckoutID() CheckoutID

CheckoutID returns the opaque hosted identity verbatim. It is not a payment identity and must not be used to infer financial success.

Example:

_ = request.CheckoutID()

func (CompleteCheckoutRequest) Err

func (completeCheckoutRequest CompleteCheckoutRequest) Err() error

Err validates identity and key without requiring a context. It reports domain errors under ErrInvalidRequest and performs no approval-state lookup.

Example:

if err := request.Err(); err != nil { return err }

func (CompleteCheckoutRequest) IdempotencyKey

func (completeCheckoutRequest CompleteCheckoutRequest) IdempotencyKey() string

IdempotencyKey returns this completion attempt's key without normalization. Reuse it only for the same request within provider retention limits.

Example:

_ = request.IdempotencyKey()

func (CompleteCheckoutRequest) MarshalJSON

func (completeCheckoutRequest CompleteCheckoutRequest) MarshalJSON() ([]byte, error)

MarshalJSON encodes only valid completion requests with the existing tags. Encoding an invalid zero value returns its domain validation error.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (*CompleteCheckoutRequest) UnmarshalJSON

func (completeCheckoutRequest *CompleteCheckoutRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON validates temporary state before replacing the request. Failed input never partially overwrites a previously valid completion request.

Example:

if err := json.Unmarshal(data, &request); err != nil { return err }

func (CompleteCheckoutRequest) Validate

func (completeCheckoutRequest CompleteCheckoutRequest) Validate(ctx context.Context) error

Validate checks context first, then Err. Provider approval requirements remain the driver's responsibility after this pure preflight check.

Example:

if err := request.Validate(ctx); err != nil { return err }

type Driver

type Driver interface {
	// PreparePayment initializes a client authorization, order, or session for a
	// positive explicit amount. It does not confirm, capture, or complete hosted
	// checkout. Returned references are optional: a session-only response need
	// not identify any financial resource and there is no universal preparation
	// lookup. Return only provider-observed references and a valid required Action.
	// Validate context/request before I/O, never hydrate a successful mutation,
	// and preserve ErrOutcomeUnknown after an ambiguous dispatch. Unsupported
	// drivers validate first and return ErrUnsupported without effects.
	//
	// Example:
	//	prepared, err := backend.PreparePayment(ctx, request)
	//	if err != nil { return err }
	//	_ = prepared.Action.Kind()
	PreparePayment(context.Context, PreparePaymentRequest) (Preparation, error)

	// CreateCheckout starts one-time approval for a positive explicit amount.
	// It does not complete the checkout or read another resource afterwards.
	//
	// Example:
	//	checkout, err := backend.CreateCheckout(ctx, request)
	//	if err != nil { return err }
	//	_ = checkout.ApprovalURL
	CreateCheckout(context.Context, CheckoutRequest) (Checkout, error)

	// CreateSubscriptionCheckout starts approval of an existing provider plan.
	// It does not create catalog entries or infer successful invoice payment.
	//
	// Example:
	//	checkout, err := backend.CreateSubscriptionCheckout(ctx, request)
	//	if err != nil { return err }
	//	_ = checkout.ApprovalURL
	CreateSubscriptionCheckout(context.Context, SubscriptionCheckoutRequest) (Checkout, error)

	// GetCheckout observes a checkout without capture, activation, or completion.
	// Approval and payment status remain separate; missing fields stay absent.
	//
	// Example:
	//	checkout, err := backend.GetCheckout(ctx, payment.CheckoutID("cs_example"))
	//	if err != nil { return err }
	//	_ = checkout.NeedsCompletion
	GetCheckout(context.Context, CheckoutID) (Checkout, error)

	// CompleteCheckout explicitly performs provider-required completion after
	// approval. Unsupported or invalid-state flows return the matching sentinel.
	//
	// Example:
	//	checkout, err := backend.CompleteCheckout(ctx, request)
	//	if err != nil { return err }
	//	_ = checkout.PaymentStatus
	CompleteCheckout(context.Context, CompleteCheckoutRequest) (Checkout, error)

	// GetPayment reads one provider payment without initiating money movement.
	// Pending is not success; NotRequired is reserved for checkout observations.
	//
	// Example:
	//	result, err := backend.GetPayment(ctx, payment.ID("pi_example"))
	//	if err != nil { return err }
	//	_ = result.Status
	GetPayment(context.Context, ID) (Payment, error)

	// RefundPayment requests a positive explicit refund without implicit balance
	// lookup. Providers enforce currency, available balance, and idempotency.
	//
	// Example:
	//	refund, err := backend.RefundPayment(ctx, request)
	//	if err != nil { return err }
	//	_ = refund.ID
	RefundPayment(context.Context, RefundRequest) (Refund, error)

	// GetRefund reads the refund's own progress without resubmitting it.
	// A pending refund is not a successful returned-funds observation.
	//
	// Example:
	//	refund, err := backend.GetRefund(ctx, payment.RefundID("re_example"))
	//	if err != nil { return err }
	//	_ = refund.Status
	GetRefund(context.Context, RefundID) (Refund, error)

	// GetSubscription observes lifecycle without activation or invoice settlement.
	// Active and NextBillingAt do not imply a paid-through date.
	//
	// Example:
	//	subscription, err := backend.GetSubscription(ctx, payment.SubscriptionID("sub_example"))
	//	if err != nil { return err }
	//	_ = subscription.Status
	GetSubscription(context.Context, SubscriptionID) (Subscription, error)

	// CancelSubscription immediately cancels without refunds or proration.
	// It performs no post-success read and no scheduled end-of-period change.
	// A preflight lifecycle check or one documented no-effect conflict read is
	// allowed; an ambiguous dispatch must not trigger a read or replay.
	//
	// Example:
	//	if err := backend.CancelSubscription(ctx, request); err != nil { return err }
	CancelSubscription(context.Context, CancelSubscriptionRequest) error
}

Driver supplies the full portable payment surface. Unsupported operations return ErrUnsupported, not optional interfaces. Implementations are safe for concurrent use, validate requests and ctx before effects, preserve native statuses, and return detached snapshots. GET operations are pure reads. Successful mutations use their own response, never post-success hydration. A preflight lifecycle read may guard an invalid mutation; a documented no-effect state conflict may permit one reconciliation read. Neither permits polling or replaying a mutation after an ambiguous result.

Map provider failures to package sentinels while preserving errors.Is. A dispatched mutation with an ambiguous result returns ErrOutcomeUnknown, including transport cancellation after dispatch when success is uncertain. Before dispatch, cancellation remains context.Canceled or DeadlineExceeded. Error text must not expose credentials, payloads, approval URLs, or references. Idempotency remains provider-scoped and retention-bounded, not exactly once.

Example:

var backend payment.Driver = driver
client := payment.New(backend)
_ = client.Driver()

type ID

type ID string

ID is an opaque provider money-movement identity, scoped to its driver. It is not interchangeable with CheckoutID or a provider customer ID.

Example: id := payment.ID("pi_example"); _ = id

func (ID) Validate

func (id ID) Validate(ctx context.Context) error

Validate checks ctx before the portable payment identifier syntax. Nil contexts and invalid IDs wrap ErrInvalidRequest; cancellation is preserved.

Example:

if err := payment.ID("pi_example").Validate(ctx); err != nil { return err }

type Money

type Money struct {
	// Amount is the number of minor units, in [0, math.MaxInt64].
	// Conversion methods reject negative values instead of interpreting a debit.
	//
	// Example:
	//	price := payment.Money{Amount: 1250, Currency: "USD"}
	//	_ = price.Amount // 1250 cents
	Amount int64 `json:"amount"`

	// Currency is the uppercase code accepted by CurrencyExponent.
	// Providers may impose a stricter currency subset.
	//
	// Example:
	//	price := payment.Money{Amount: 1250, Currency: "USD"}
	//	_ = price.Currency // "USD"
	Currency string `json:"currency"`
}

Money represents a nonnegative amount in integer currency minor units. Zero is valid for observations; checkout creation and refunds require positive amounts. Currency is a supported uppercase ISO code, never inferred or rounded.

Example:

price := payment.Money{Amount: 1250, Currency: "USD"}
decimal, err := price.Decimal()
if err != nil { return err }
_ = decimal // "12.50"

func NewMoney

func NewMoney(currency string, minor int64) (Money, error)

NewMoney validates an exact integer minor-unit amount without rounding or floating-point conversion. Zero is valid; negatives return ErrInvalidRequest and unknown currencies return ErrUnsupported. On failure it returns zero Money.

Example:

amount, err := payment.NewMoney("USD", 1250)
if err != nil { return err }
_ = amount.Amount // 1250 cents

func ParseMoney

func ParseMoney(currency, value string) (Money, error)

ParseMoney converts unsigned decimal notation to exact integer minor units. Missing fractional places are padded; excess places, signs, exponent notation, whitespace, and int64 overflow return ErrInvalidRequest. Unknown currencies return ErrUnsupported. No rounding or floating-point conversion occurs.

Example:

price, err := payment.ParseMoney("USD", "12.5")
if err != nil { return err }
_ = price.Amount // 1250

func (Money) Decimal

func (money Money) Decimal() (string, error)

Decimal formats minor units as exact unsigned decimal notation, retaining the currency's full precision. Invalid amounts return ErrInvalidRequest; unsupported currencies return ErrUnsupported. It never uses floating point.

Example:

value, err := (payment.Money{Amount: 1234, Currency: "KWD"}).Decimal()
if err != nil { return err }
_ = value // "1.234"

func (Money) Validate

func (money Money) Validate() error

Validate checks nonnegative minor units and the explicit currency vocabulary. It does not require a positive amount or validate provider-specific limits.

Example:

if err := (payment.Money{Amount: 0, Currency: "USD"}).Validate(); err != nil {
	return err
}

type Observation

type Observation struct {
	// Kind is the portable observation meaning, or unknown if unmapped.
	// Do not infer payment success from approval or lifecycle changes.
	//
	// Example: _ = payment.Observation{Kind: payment.PaymentSucceeded}
	Kind ObservationKind `json:"kind,omitzero"`

	// OccurredAt is the provider event instant, not local receipt time.
	// Zero means the provider did not supply a trustworthy instant.
	//
	// Example: _ = payment.Observation{OccurredAt: time.Unix(1700000000, 0)}
	OccurredAt time.Time `json:"occurred_at,omitzero"`

	// CheckoutID is the related provider checkout, if present in the event.
	// Empty means absent, not permission to infer it from another ID.
	//
	// Example: _ = payment.Observation{CheckoutID: "cs_example"}
	CheckoutID CheckoutID `json:"checkout_id,omitzero"`

	// PaymentID is the related provider payment, if supplied by the event.
	// No network hydration occurs solely to populate it.
	//
	// Example: _ = payment.Observation{PaymentID: "pi_example"}
	PaymentID ID `json:"payment_id,omitzero"`

	// RefundID is the related provider refund, if supplied by the event.
	// It remains distinct from the original payment identity.
	//
	// Example: _ = payment.Observation{RefundID: "re_example"}
	RefundID RefundID `json:"refund_id,omitzero"`

	// SubscriptionID identifies the related subscription, when observed.
	// Its presence does not establish an invoice's settlement status.
	//
	// Example: _ = payment.Observation{SubscriptionID: "sub_example"}
	SubscriptionID SubscriptionID `json:"subscription_id,omitzero"`

	// InvoiceID is a provider invoice identity, when present in the event.
	// There is no invoice lookup or invoice management contract here.
	//
	// Example: _ = payment.Observation{InvoiceID: "in_example"}
	InvoiceID string `json:"invoice_id,omitzero"`

	// Amount optionally reports observed money, with nil meaning unknown.
	// Adapters detach the pointer; callers own the returned observation.
	//
	// Example: _ = payment.Observation{Amount: &payment.Money{Amount: 2500, Currency: "USD"}}
	Amount *Money `json:"amount,omitzero"`

	// NativeStatus is an optional provider resource status token.
	// It is not the provider event type or the entire event payload.
	//
	// Example: _ = payment.Observation{NativeStatus: "succeeded"}
	NativeStatus string `json:"native_status,omitzero"`
}

Observation is a small credential-free notification DTO for optional provider adapters. It contains no delivery ID or native event type: the webhook delivery owns that envelope. Events may be duplicated or out of order; this package performs no deduplication, verification, queueing, or fulfillment.

Example: _ = payment.Observation{Kind: payment.PaymentSucceeded, PaymentID: "pi_example"}

type ObservationKind

type ObservationKind string

ObservationKind identifies a portable provider notification meaning. Observations are data only; applications bind delivery and fulfillment policy.

Example: _ = payment.Observation{Kind: payment.PaymentSucceeded}

const (
	// ObservationKindUnknown preserves an unmapped notification meaning.
	// It must not be treated as evidence of successful money movement.
	//
	// Example: _ = payment.Observation{Kind: payment.ObservationKindUnknown}
	ObservationKindUnknown ObservationKind = ""
	// CheckoutApproved reports approval, not completed capture or payment.
	// Use explicit completion where the provider requires it.
	//
	// Example: _ = payment.Observation{Kind: payment.CheckoutApproved}
	CheckoutApproved ObservationKind = "checkout_approved"
	// CheckoutCompleted reports completion of the approval flow only.
	// Payment success remains a separate observation.
	//
	// Example: _ = payment.Observation{Kind: payment.CheckoutCompleted}
	CheckoutCompleted ObservationKind = "checkout_completed"
	// PaymentSucceeded reports a successful individual payment attempt.
	// Keep application fulfillment idempotent across duplicate deliveries.
	//
	// Example: _ = payment.Observation{Kind: payment.PaymentSucceeded}
	PaymentSucceeded ObservationKind = "payment_succeeded"
	// PaymentFailed reports a known unsuccessful individual payment attempt.
	// It does not imply that every attempt for an order failed.
	//
	// Example: _ = payment.Observation{Kind: payment.PaymentFailed}
	PaymentFailed ObservationKind = "payment_failed"
	// RefundUpdated reports a refund status change, not necessarily success.
	// NativeStatus carries provider detail for application interpretation.
	//
	// Example: _ = payment.Observation{Kind: payment.RefundUpdated}
	RefundUpdated ObservationKind = "refund_updated"
	// SubscriptionUpdated reports lifecycle change, not invoice settlement.
	// Active subscriptions must not be assumed paid from this event alone.
	//
	// Example: _ = payment.Observation{Kind: payment.SubscriptionUpdated}
	SubscriptionUpdated ObservationKind = "subscription_updated"
	// InvoicePaid reports the provider's paid-invoice observation.
	// It may represent a zero or externally settled invoice, not a new payment.
	//
	// Example: _ = payment.Observation{Kind: payment.InvoicePaid}
	InvoicePaid ObservationKind = "invoice_paid"
	// InvoicePaymentFailed reports a failed invoice-associated payment attempt.
	// Keep InvoiceID to correlate retries without inferring lifecycle status.
	//
	// Example: _ = payment.Observation{Kind: payment.InvoicePaymentFailed}
	InvoicePaymentFailed ObservationKind = "invoice_payment_failed"
	// InvoicePaymentPaid reports a provider invoice-payment settlement event.
	// Preserve its distinction from the invoice's aggregate paid state.
	//
	// Example: _ = payment.Observation{Kind: payment.InvoicePaymentPaid}
	InvoicePaymentPaid ObservationKind = "invoice_payment_paid"
)

type OperationEvent

type OperationEvent struct {
	// Operation is the fixed snake_case facade operation, such as get_payment
	// or refund_payment. It never incorporates request or provider values.
	//
	// Example:
	//
	//	fmt.Println(observed.Operation) // "get_payment" for Client.GetPayment.
	Operation string

	// ErrorType is empty for completion; otherwise it is a payment sentinel name,
	// context.Canceled, context.DeadlineExceeded, or "unknown". ErrOutcomeUnknown
	// takes precedence over all joined causes and does not mean failed movement.
	// No arbitrary Go type names, error messages, or native statuses are copied.
	//
	// Example:
	//
	//	if observed.ErrorType == "payment.ErrOutcomeUnknown" {
	//		fmt.Println("reconciliation remains application-owned")
	//	}
	ErrorType string
}

OperationEvent reports the observed result of one validated facade call that reached the driver. It contains only bounded operation and error classes, not resource identities, amounts, requests, handoff secrets, or native error text. Completion includes reads and idempotent replays; neither topic proves money movement, settlement, or fulfillment eligibility. These synchronous in-process observations are best effort, not durable reconciliation or fulfillment triggers.

Example:

bus := event.New()
stop, err := bus.Listen(payment.OperationCompleted, func(ctx context.Context, observed payment.OperationEvent) error {
	fmt.Println(observed.Operation)
	return nil
})
if err != nil {
	return err
}
defer stop()

type Payment

type Payment struct {
	// ID identifies the payment for reads and refunds. It is not a checkout identity.
	//
	// Example: _ = payment.Payment{ID: "pi_example"}
	ID ID `json:"id"`

	// Status describes the payment outcome. Pending and Unknown do not establish success.
	//
	// Example: _ = payment.Payment{Status: payment.StatusSucceeded}
	Status Status `json:"status,omitzero"`

	// NativeStatus preserves the provider status token, never a response or error payload.
	//
	// Example: _ = payment.Payment{NativeStatus: "succeeded"}
	NativeStatus string `json:"native_status,omitzero"`

	// Amount reports integer minor units. Records permit zero, unlike mutation requests.
	//
	// Example: _ = payment.Payment{Amount: payment.Money{Amount: 2500, Currency: "USD"}}
	Amount Money `json:"amount"`

	// SubscriptionID identifies a related subscription. It does not establish invoice payment.
	//
	// Example: _ = payment.Payment{SubscriptionID: "sub_example"}
	SubscriptionID SubscriptionID `json:"subscription_id,omitzero"`
}

Payment is a provider money-movement snapshot, independent of checkout state. Refunds are separate resources; NotRequired is not a valid actual payment state.

Example: _ = payment.Payment{ID: "pi_example", Status: payment.StatusSucceeded}

type Preparation

type Preparation struct {
	// PaymentID is optional observed financial identity, never a session alias.
	// Example: if prepared.PaymentID != "" { _ = prepared.PaymentID }
	PaymentID ID `json:"payment_id,omitzero"`
	// CheckoutID is optional observed checkout/order identity; preparation does
	// not imply a hosted page exists or that completion is currently required.
	// Example: if prepared.CheckoutID != "" { _ = prepared.CheckoutID }
	CheckoutID CheckoutID `json:"checkout_id,omitzero"`
	// SessionID is optional observed SDK-session identity, not a payment identity.
	// Example: if prepared.SessionID != "" { _ = prepared.SessionID }
	SessionID SessionID `json:"session_id,omitzero"`
	// Action is the required concrete handoff for an authorized client. It never
	// establishes successful payment and must not be logged as JSON.
	// Example: if authorization, ok := prepared.Action.Authorization(); ok { _ = authorization.Token }
	Action ClientAction `json:"action"`
}

Preparation is an observed client initialization response, not a settled payment or proof of authorization. Action is required; all resource references are optional and remain absent when the provider returns only a session/order. No status, amount, or financial identity is fabricated. Diagnostics redact the whole record; JSON intentionally carries secrets to an authorized client.

Example:

prepared := payment.Preparation{Action: payment.NewClientSession("vendor.session", "session-1", "sdk-data")}
if err := prepared.Err(); err != nil { return err }

func (Preparation) Err

func (preparation Preparation) Err() error

Err requires a valid action and validates only references actually present. Session-only handoffs are valid; no financial reference is mandatory.

Example:

if err := prepared.Err(); err != nil { return err }

func (Preparation) GoString

func (preparation Preparation) GoString() string

GoString redacts the observation under expanded Go-syntax formatting too. It never exposes an action token or SDK session data.

Example:

_ = fmt.Sprintf("%#v", prepared)

func (Preparation) LogValue

func (preparation Preparation) LogValue() slog.Value

LogValue supplies a redacted slog value independently of handler encoding. Do not replace it with credential-bearing JSON in diagnostic handlers.

Example:

slog.Info("prepared", "result", prepared)

func (Preparation) MarshalJSON

func (preparation Preparation) MarshalJSON() ([]byte, error)

MarshalJSON intentionally exposes valid action secrets to an authorized client. Invalid action or reference syntax fails before encoding.

Example:

data, err := json.Marshal(prepared)
if err != nil { return err }
_ = data // authorized delivery, not logging

func (Preparation) String

func (preparation Preparation) String() string

String redacts the complete observation, including optional references. Client transport JSON is intentionally separate from diagnostic formatting.

Example:

_ = fmt.Sprint(prepared)

func (*Preparation) UnmarshalJSON

func (preparation *Preparation) UnmarshalJSON(data []byte) error

UnmarshalJSON validates temporary state before replacing the observation. Missing financial references stay absent, and invalid input leaves it intact.

Example:

if err := json.Unmarshal(data, &prepared); err != nil { return err }

type PreparePaymentRequest

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

PreparePaymentRequest immutably requests client-side initialization for a positive explicit amount. It is separate from hosted checkout and completion. Its zero value is invalid; no result or financial state is inferred from it.

Example:

request := payment.NewPreparePaymentRequest(payment.Money{Amount: 1200, Currency: "USD"}, "order-1")
if err := request.Err(); err != nil { return err }

func NewPreparePaymentRequest

func NewPreparePaymentRequest(amount Money, key string, configure ...PreparePaymentRequestBuilderFunc) PreparePaymentRequest

NewPreparePaymentRequest copies a positive amount and required key, then runs callbacks directly once in order, including invalid declarations. Nil entries panic; expanded nil/empty slices omit edits. No I/O or confirmation occurs.

Example:

request := payment.NewPreparePaymentRequest(payment.Money{Amount: 1200, Currency: "USD"}, "order-1")
if err := request.Err(); err != nil { return err }

func (PreparePaymentRequest) Amount

func (preparePaymentRequest PreparePaymentRequest) Amount() Money

Amount returns a detached Money copy. Mutating it does not change this request or imply that initialization has authorized or transferred any funds.

Example:

_ = request.Amount().Currency

func (PreparePaymentRequest) Channel

func (preparePaymentRequest PreparePaymentRequest) Channel() ClientChannel

Channel returns the optional intended client platform. It does not guarantee that a provider enables any particular wallet or payment method.

Example:

_ = request.Channel()

func (PreparePaymentRequest) Description

func (preparePaymentRequest PreparePaymentRequest) Description() string

Description returns optional provider-visible text without normalization. Empty means omitted rather than an inferred product description.

Example:

_ = request.Description()

func (PreparePaymentRequest) DeviceReference

func (preparePaymentRequest PreparePaymentRequest) DeviceReference() string

DeviceReference returns optional opaque provider risk correlation. It is not financial identity and should be excluded from ordinary logs and telemetry.

Example:

_ = request.DeviceReference()

func (PreparePaymentRequest) Err

func (preparePaymentRequest PreparePaymentRequest) Err() error

Err reports the first construction error or invalid zero value without I/O. Required amount/key validation precedes optional settings; values are not echoed.

Example:

if err := request.Err(); err != nil { return err }

func (PreparePaymentRequest) IdempotencyKey

func (preparePaymentRequest PreparePaymentRequest) IdempotencyKey() string

IdempotencyKey returns this preparation's required mutation key verbatim. Deduplication is provider-scoped and bounded by provider retention.

Example:

_ = request.IdempotencyKey()

func (PreparePaymentRequest) MarshalJSON

func (preparePaymentRequest PreparePaymentRequest) MarshalJSON() ([]byte, error)

MarshalJSON emits the private snake_case payload only when valid. Remembered invalid settings cannot be erased by serializing their later replacements.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (PreparePaymentRequest) Reference

func (preparePaymentRequest PreparePaymentRequest) Reference() string

Reference returns optional application correlation, not a resource identity. No provider lookup or authorization is implied by a nonempty value.

Example:

_ = request.Reference()

func (PreparePaymentRequest) ReturnURL

func (preparePaymentRequest PreparePaymentRequest) ReturnURL() string

ReturnURL returns the optional client callback URI verbatim. The application owns its allowlist and must not treat syntax validation as destination trust.

Example:

_ = request.ReturnURL()

func (*PreparePaymentRequest) UnmarshalJSON

func (preparePaymentRequest *PreparePaymentRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON validates fresh temporary state and commits only on success. Errors preserve the receiver's prior payload and validation state.

Example:

if err := json.Unmarshal(data, &request); err != nil { return err }

func (PreparePaymentRequest) Validate

func (preparePaymentRequest PreparePaymentRequest) Validate(ctx context.Context) error

Validate checks context before Err. Cancellation never becomes an uncertain mutation outcome before dispatch, even when the request is also invalid.

Example:

if err := request.Validate(ctx); err != nil { return err }

type PreparePaymentRequestBuilder

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

PreparePaymentRequestBuilder edits one fresh preparation draft. Invalid input is sticky; publication detaches the resulting scalar values from this draft.

Example:

request := payment.NewPreparePaymentRequest(amount, "order-1", func(details *payment.PreparePaymentRequestBuilder) {
	details.Channel(payment.ClientChannelIOS).ReturnURL("com.example.shop:/payment")
})
_ = request.Channel()

func (*PreparePaymentRequestBuilder) Channel

Channel replaces the optional client platform. Empty means unspecified; unknown values are sticky errors rather than provider-specific escape hatches.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.Channel(payment.ClientChannelAndroid)
}
_ = configure

func (*PreparePaymentRequestBuilder) Description

Description replaces optional provider-visible text, limited to 127 runes. Controls and malformed UTF-8 produce a sticky error; do not put secrets here.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.Description("Book order")
}
_ = configure

func (*PreparePaymentRequestBuilder) DeviceReference

func (details *PreparePaymentRequestBuilder) DeviceReference(value string) *PreparePaymentRequestBuilder

DeviceReference sets optional opaque provider risk correlation, at most 255 bytes without whitespace, controls, or malformed UTF-8. Empty omits it. This value is not a general metadata bag, authorization, or payment instrument.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.DeviceReference("device-session-123")
}
_ = configure

func (*PreparePaymentRequestBuilder) Reference

Reference replaces optional application correlation text, at most 127 runes. It is not authorization or idempotency and must contain no controls or secrets.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.Reference("order-1")
}
_ = configure

func (*PreparePaymentRequestBuilder) ReturnURL

ReturnURL sets an optional HTTPS, loopback HTTP, or syntactically valid custom native callback URI. Dangerous schemes, controls, and credentials are rejected. The application MUST authorize its own scheme/host allowlist before construction; syntax validation cannot establish scheme registration or application ownership. Hosted checkout's stricter redirect policy is unchanged.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.ReturnURL("com.example.shop:/payment")
}
_ = configure

type PreparePaymentRequestBuilderFunc

type PreparePaymentRequestBuilderFunc = func(*PreparePaymentRequestBuilder)

PreparePaymentRequestBuilderFunc supplies a synchronous preparation edit. Callbacks run once in order even on invalid input; nil entries panic.

Example:

var configure payment.PreparePaymentRequestBuilderFunc = func(details *payment.PreparePaymentRequestBuilder) {
	details.Reference("order-1")
}
_ = configure

type Refund

type Refund struct {
	// ID identifies the refund for reconciliation. It is distinct from the payment ID.
	//
	// Example: _ = payment.Refund{ID: "re_example"}
	ID RefundID `json:"id"`

	// PaymentID identifies the original payment if observed. Preserve provider-family prefixes.
	//
	// Example: _ = payment.Refund{PaymentID: "pi_example"}
	PaymentID ID `json:"payment_id,omitzero"`

	// Status describes this refund, not the payment. Only Succeeded establishes success.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusSucceeded}
	Status RefundStatus `json:"status,omitzero"`

	// NativeStatus preserves the provider status token, never a response or error payload.
	//
	// Example: _ = payment.Refund{NativeStatus: "PENDING"}
	NativeStatus string `json:"native_status,omitzero"`

	// Amount reports refund minor units. Negative values never represent a debit.
	//
	// Example: _ = payment.Refund{Amount: payment.Money{Amount: 500, Currency: "USD"}}
	Amount Money `json:"amount"`
}

Refund is a snapshot of returned-funds progress against one payment. A pending refund does not establish that funds have been returned.

Example: _ = payment.Refund{ID: "re_example", Status: payment.RefundStatusPending}

type RefundID

type RefundID string

RefundID is an opaque provider refund identity, scoped to its driver. Keep it separately from the original payment ID for reconciliation.

Example: id := payment.RefundID("re_example"); _ = id

func (RefundID) Validate

func (refundID RefundID) Validate(ctx context.Context) error

Validate checks ctx before the portable refund identifier syntax. Nil contexts and invalid IDs wrap ErrInvalidRequest; cancellation is preserved.

Example:

if err := payment.RefundID("re_example").Validate(ctx); err != nil { return err }

type RefundRequest

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

RefundRequest immutably requests a positive explicit refund. Zero never means a full refund; the provider enforces remaining balance and currency agreement.

Example:

request := payment.NewRefundRequest("pi_example", payment.Money{Amount: 500, Currency: "USD"}, "refund-1")
if err := request.Err(); err != nil { return err }

func NewRefundRequest

func NewRefundRequest(id ID, amount Money, key string) RefundRequest

NewRefundRequest copies its explicit amount and identities without I/O. Invalid inputs fail Err, dispatch validation, and JSON encoding.

Example:

request := payment.NewRefundRequest("pi_example", payment.Money{Amount: 500, Currency: "USD"}, "refund-1")
if err := request.Err(); err != nil { return err }

func (RefundRequest) Amount

func (refundRequest RefundRequest) Amount() Money

Amount returns a Money copy, never an alias into the request. Zero is invalid here even though it is valid in a general Money observation.

Example:

_ = request.Amount().Currency

func (RefundRequest) Err

func (refundRequest RefundRequest) Err() error

Err checks identity, positive money, and key without I/O or a context. It cannot check provider balance and never performs an implicit full refund.

Example:

if err := request.Err(); err != nil { return err }

func (RefundRequest) IdempotencyKey

func (refundRequest RefundRequest) IdempotencyKey() string

IdempotencyKey returns this refund's key verbatim. Reuse with a different amount is invalid even when the provider retains the original request.

Example:

_ = request.IdempotencyKey()

func (RefundRequest) MarshalJSON

func (refundRequest RefundRequest) MarshalJSON() ([]byte, error)

MarshalJSON preserves the refund wire shape and rejects invalid values. In particular it cannot encode an implicit zero-amount full refund.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (RefundRequest) PaymentID

func (refundRequest RefundRequest) PaymentID() ID

PaymentID returns the opaque original money-movement identity. It does not identify a checkout and does not guarantee refundable balance.

Example:

_ = request.PaymentID()

func (*RefundRequest) UnmarshalJSON

func (refundRequest *RefundRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON validates fresh state and commits only on success. Malformed or invalid input leaves the original request unchanged.

Example:

if err := json.Unmarshal(data, &request); err != nil { return err }

func (RefundRequest) Validate

func (refundRequest RefundRequest) Validate(ctx context.Context) error

Validate preserves context failures before domain errors. Provider balance checks occur only after portable validation succeeds.

Example:

if err := request.Validate(ctx); err != nil { return err }

type RefundStatus

type RefundStatus string

RefundStatus describes a refund's own progress, independently of a payment. A submitted or pending refund is not a successful refund.

Example: _ = payment.Refund{Status: payment.RefundStatusPending}

const (
	// RefundStatusUnknown preserves an absent or unmapped refund state.
	// Inspect NativeStatus rather than assuming success.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusUnknown}
	RefundStatusUnknown RefundStatus = ""
	// RefundStatusPending means the provider has not finalized the refund.
	// Submission alone does not establish that funds were returned.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusPending}
	RefundStatusPending RefundStatus = "pending"
	// RefundStatusRequiresAction means further action is required to refund.
	// It must not be treated as successful funds movement.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusRequiresAction}
	RefundStatusRequiresAction RefundStatus = "requires_action"
	// RefundStatusSucceeded means the provider confirmed the refund succeeded.
	// The original Payment retains its own status and identity.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusSucceeded}
	RefundStatusSucceeded RefundStatus = "succeeded"
	// RefundStatusFailed means the refund has a known unsuccessful outcome.
	// It differs from an ambiguous mutation transport failure.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusFailed}
	RefundStatusFailed RefundStatus = "failed"
	// RefundStatusCanceled means the refund was canceled before success.
	// It does not change the original payment's success status.
	//
	// Example: _ = payment.Refund{Status: payment.RefundStatusCanceled}
	RefundStatusCanceled RefundStatus = "canceled"
)

type SessionID

type SessionID string

SessionID identifies a client SDK session, not a financial payment or hosted checkout. Preserve its opaque provider identity; it may exist without either.

Example:

id := payment.SessionID("session-1")
if err := id.Validate(ctx); err != nil { return err }

func (SessionID) Validate

func (sessionID SessionID) Validate(ctx context.Context) error

Validate checks context before opaque session identity syntax. Empty, overlong, control-bearing, whitespace-bearing, and malformed UTF-8 identities are invalid.

Example:

if err := payment.SessionID("session-1").Validate(ctx); err != nil { return err }

type Status

type Status string

Status describes a payment attempt or a checkout payment observation. Only Succeeded confirms success; Pending and RequiresAction do not.

Example: _ = payment.Payment{Status: payment.StatusPending}

const (
	// StatusUnknown preserves a missing or unmapped payment state.
	// Never interpret it as a successful payment.
	//
	// Example: _ = payment.Payment{Status: payment.StatusUnknown}
	StatusUnknown Status = ""
	// StatusPending means the payment outcome is not final.
	// Applications must wait for a successful observation before fulfillment.
	//
	// Example: _ = payment.Payment{Status: payment.StatusPending}
	StatusPending Status = "pending"
	// StatusRequiresAction means additional customer action is needed.
	// It is neither final success nor final failure.
	//
	// Example: _ = payment.Payment{Status: payment.StatusRequiresAction}
	StatusRequiresAction Status = "requires_action"
	// StatusSucceeded confirms that this payment attempt succeeded.
	// Refunds remain separate resources and do not rewrite this history.
	//
	// Example: _ = payment.Payment{Status: payment.StatusSucceeded}
	StatusSucceeded Status = "succeeded"
	// StatusFailed records a known unsuccessful payment attempt.
	// A later retry may have a distinct provider payment identity.
	//
	// Example: _ = payment.Payment{Status: payment.StatusFailed}
	StatusFailed Status = "failed"
	// StatusCanceled means this payment attempt was canceled.
	// It does not imply a refund of a different successful payment.
	//
	// Example: _ = payment.Payment{Status: payment.StatusCanceled}
	StatusCanceled Status = "canceled"
	// StatusNotRequired is a checkout observation only, for flows such
	// as trials. Drivers must not use it as an actual Payment's status.
	//
	// Example: _ = payment.Checkout{PaymentStatus: payment.StatusNotRequired}
	StatusNotRequired Status = "not_required"
)

type Subscription

type Subscription struct {
	// ID identifies the subscription for reads and cancellation. It is not a plan reference.
	//
	// Example: _ = payment.Subscription{ID: "sub_example"}
	ID SubscriptionID `json:"id"`

	// PlanReference identifies an observed provider plan or price. Empty means absent.
	//
	// Example: _ = payment.Subscription{PlanReference: "price_monthly"}
	PlanReference string `json:"plan_reference,omitzero"`

	// Status describes lifecycle, not invoice settlement. Applications own entitlement policy.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusActive}
	Status SubscriptionStatus `json:"status,omitzero"`

	// NativeStatus preserves the provider status token, never a response or error payload.
	//
	// Example: _ = payment.Subscription{NativeStatus: "ACTIVE"}
	NativeStatus string `json:"native_status,omitzero"`

	// Reference correlates application data. It is optional, not a customer ID or retry key.
	//
	// Example: _ = payment.Subscription{Reference: "signup-123"}
	Reference string `json:"reference,omitzero"`

	// NextBillingAt is the next billing instant. Nil means unknown, never paid-through time.
	//
	// Example: _ = payment.Subscription{NextBillingAt: nil}
	NextBillingAt *time.Time `json:"next_billing_at,omitzero"`
}

Subscription is a provider lifecycle snapshot, not a paid-through ledger. Active and NextBillingAt are not proof of payment. The caller owns the optional time pointer; drivers must detach it from internal state.

Example: _ = payment.Subscription{ID: "sub_example", Status: payment.SubscriptionStatusActive}

type SubscriptionCheckoutRequest

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

SubscriptionCheckoutRequest is an immutable approval request for an existing provider plan. It creates no catalog, invoice, or entitlement; zero is invalid.

Example:

request := payment.NewSubscriptionCheckoutRequest("price_monthly", "https://shop.example/account", "signup-1")
if err := request.Err(); err != nil { return err }

func NewSubscriptionCheckoutRequest

func NewSubscriptionCheckoutRequest(plan, returnURL, key string,
	configure ...SubscriptionCheckoutRequestBuilderFunc,
) SubscriptionCheckoutRequest

NewSubscriptionCheckoutRequest snapshots a request without I/O. Required validation runs first; all callbacks run once in order even on invalid input. Supplied nil callbacks panic. Retained drafts cannot change the result.

Example:

request := payment.NewSubscriptionCheckoutRequest("price_monthly", "https://shop.example/account", "signup-1")
if err := request.Err(); err != nil { return err }

func (SubscriptionCheckoutRequest) CancelURL

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) CancelURL() string

CancelURL returns the optional hosted cancellation location. Empty means omitted, not a default derived from ReturnURL.

Example:

_ = request.CancelURL()

func (SubscriptionCheckoutRequest) Err

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) Err() error

Err returns the first construction error or invalid-zero error. It performs pure validation and never checks provider plan existence.

Example:

if err := request.Err(); err != nil { return err }

func (SubscriptionCheckoutRequest) IdempotencyKey

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) IdempotencyKey() string

IdempotencyKey returns the key for this approval mutation, not cancellation. Its deduplication scope and retention remain provider-bounded.

Example:

_ = request.IdempotencyKey()

func (SubscriptionCheckoutRequest) MarshalJSON

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) MarshalJSON() ([]byte, error)

MarshalJSON preserves the hosted subscription wire shape. Invalid requests fail encoding rather than silently dropping private validation state.

Example:

data, err := json.Marshal(request)
if err != nil { return err }
_ = data

func (SubscriptionCheckoutRequest) PlanReference

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) PlanReference() string

PlanReference returns the existing provider plan identity verbatim. It is not an application plan name and does not establish that the plan exists.

Example:

_ = request.PlanReference()

func (SubscriptionCheckoutRequest) Reference

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) Reference() string

Reference returns application correlation text without lookup or authorization. The value may be empty when the caller omitted it.

Example:

_ = request.Reference()

func (SubscriptionCheckoutRequest) ReturnURL

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) ReturnURL() string

ReturnURL returns the required hosted return location without normalization. Literal checkout-session placeholders remain unchanged.

Example:

_ = request.ReturnURL()

func (*SubscriptionCheckoutRequest) UnmarshalJSON

func (subscriptionCheckoutRequest *SubscriptionCheckoutRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes and validates temporary state before publication. Errors leave the receiver unchanged, including on partial or malformed input.

Example:

if err := json.Unmarshal(data, &request); err != nil { return err }

func (SubscriptionCheckoutRequest) Validate

func (subscriptionCheckoutRequest SubscriptionCheckoutRequest) Validate(ctx context.Context) error

Validate checks context before construction validity. Cancellation wins over request errors without provider I/O or side effects.

Example:

if err := request.Validate(ctx); err != nil { return err }

type SubscriptionCheckoutRequestBuilder

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

SubscriptionCheckoutRequestBuilder edits a fresh subscription approval draft. Publication copies its values, and invalid settings cannot be repaired.

Example:

request := payment.NewSubscriptionCheckoutRequest("plan-1", "https://shop.example/account", "signup-1",
	func(details *payment.SubscriptionCheckoutRequestBuilder) {
		details.Reference("customer-order")
	})
_ = request.Reference()

func (*SubscriptionCheckoutRequestBuilder) CancelURL

CancelURL sets an optional hosted cancellation location. Empty omits it; invalid HTTPS/loopback policy input remains sticky after later replacements.

Example:

var configure payment.SubscriptionCheckoutRequestBuilderFunc = func(details *payment.SubscriptionCheckoutRequestBuilder) {
	details.CancelURL("https://shop.example/plans")
}
_ = configure

func (*SubscriptionCheckoutRequestBuilder) Reference

Reference sets optional application correlation text, at most 127 runes with no controls. Do not include credentials or sensitive customer data.

Example:

var configure payment.SubscriptionCheckoutRequestBuilderFunc = func(details *payment.SubscriptionCheckoutRequestBuilder) {
	details.Reference("signup-123")
}
_ = configure

type SubscriptionCheckoutRequestBuilderFunc

type SubscriptionCheckoutRequestBuilderFunc = func(*SubscriptionCheckoutRequestBuilder)

SubscriptionCheckoutRequestBuilderFunc supplies one ordered synchronous edit. Nil entries panic; expanded nil or empty callback slices supply no edits.

Example:

var configure payment.SubscriptionCheckoutRequestBuilderFunc = func(details *payment.SubscriptionCheckoutRequestBuilder) {
	details.CancelURL("https://shop.example/plans")
}
_ = configure

type SubscriptionID

type SubscriptionID string

SubscriptionID is an opaque provider subscription identity, scoped to its driver. It is distinct from the provider's plan or price reference.

Example: id := payment.SubscriptionID("sub_example"); _ = id

func (SubscriptionID) Validate

func (subscriptionID SubscriptionID) Validate(ctx context.Context) error

Validate checks ctx before the portable subscription identifier syntax. Nil contexts and invalid IDs wrap ErrInvalidRequest; cancellation is preserved.

Example:

if err := payment.SubscriptionID("sub_example").Validate(ctx); err != nil { return err }

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus describes subscription lifecycle, not invoice settlement. Even Active does not prove that the most recent invoice was paid.

Example: _ = payment.Subscription{Status: payment.SubscriptionStatusActive}

const (
	// SubscriptionStatusUnknown preserves an absent or unmapped lifecycle state.
	// It is not evidence that service should be provisioned.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusUnknown}
	SubscriptionStatusUnknown SubscriptionStatus = ""
	// SubscriptionStatusPending means activation is still incomplete.
	// Approval or provider processing may remain outstanding.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusPending}
	SubscriptionStatusPending SubscriptionStatus = "pending"
	// SubscriptionStatusTrialing means the provider reports a trial period.
	// A trial is not evidence of a settled payment.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusTrialing}
	SubscriptionStatusTrialing SubscriptionStatus = "trialing"
	// SubscriptionStatusActive means the provider reports active service.
	// Invoice payment must be established independently.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusActive}
	SubscriptionStatusActive SubscriptionStatus = "active"
	// SubscriptionStatusPastDue means a billing obligation is overdue.
	// The application owns grace periods and entitlement policy.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusPastDue}
	SubscriptionStatusPastDue SubscriptionStatus = "past_due"
	// SubscriptionStatusUnpaid means the provider reports an unpaid subscription.
	// It is distinct from temporary payment retry or processing states.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusUnpaid}
	SubscriptionStatusUnpaid SubscriptionStatus = "unpaid"
	// SubscriptionStatusPaused means billing or service is temporarily paused.
	// The contract does not infer an entitlement decision from this status.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusPaused}
	SubscriptionStatusPaused SubscriptionStatus = "paused"
	// SubscriptionStatusSuspended means the provider suspended the subscription.
	// Preserve NativeStatus for provider-specific causes or recovery rules.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusSuspended}
	SubscriptionStatusSuspended SubscriptionStatus = "suspended"
	// SubscriptionStatusCanceled means the subscription has been canceled.
	// Cancellation does not imply a refund or proration.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusCanceled}
	SubscriptionStatusCanceled SubscriptionStatus = "canceled"
	// SubscriptionStatusExpired means the provider reports the term ended.
	// It carries no inferred paid-through date.
	//
	// Example: _ = payment.Subscription{Status: payment.SubscriptionStatusExpired}
	SubscriptionStatusExpired SubscriptionStatus = "expired"
)

Directories

Path Synopsis
Package memorypayment simulates outbound payment operations in process.
Package memorypayment simulates outbound payment operations in process.
Package paymenttest provides a scripted outbound fake and driver conformance tests.
Package paymenttest provides a scripted outbound fake and driver conformance tests.
internal/suite
Package suite implements deterministic payment driver conformance checks.
Package suite implements deterministic payment driver conformance checks.

Jump to

Keyboard shortcuts

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