processor

package
v1.37.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 5 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrProcessorNotFound is returned when a processor is not registered
	ErrProcessorNotFound = errors.New("payment processor not found")

	// ErrProcessorNotAvailable is returned when a processor is not available
	ErrProcessorNotAvailable = errors.New("payment processor not available")

	// ErrProcessorDisabled is returned when a processor is disabled
	ErrProcessorDisabled = errors.New("payment processor is disabled")

	// ErrCurrencyNotSupported is returned when a currency is not supported
	ErrCurrencyNotSupported = errors.New("currency not supported by processor")

	// ErrInvalidPaymentRequest is returned when a payment request is invalid
	ErrInvalidPaymentRequest = errors.New("invalid payment request")

	// ErrInsufficientFunds is returned when there are insufficient funds
	ErrInsufficientFunds = errors.New("insufficient funds")

	// ErrPaymentDeclined is returned when a payment is declined
	ErrPaymentDeclined = errors.New("payment declined")

	// ErrPaymentFailed is returned when a payment fails
	ErrPaymentFailed = errors.New("payment failed")

	// ErrRefundFailed is returned when a refund fails
	ErrRefundFailed = errors.New("refund failed")

	// ErrTransactionNotFound is returned when a transaction is not found
	ErrTransactionNotFound = errors.New("transaction not found")

	// ErrWebhookValidationFailed is returned when webhook validation fails
	ErrWebhookValidationFailed = errors.New("webhook validation failed")

	// ErrSubscriptionNotSupported is returned when subscriptions are not supported
	ErrSubscriptionNotSupported = errors.New("subscriptions not supported by processor")

	// ErrCryptoNotSupported is returned when crypto operations are not supported
	ErrCryptoNotSupported = errors.New("crypto operations not supported by processor")

	// ErrCustomerNotSupported is returned when customer operations are not supported
	ErrCustomerNotSupported = errors.New("customer management not supported by processor")

	// ErrThresholdNotMet is returned when MPC threshold is not met
	ErrThresholdNotMet = errors.New("signing threshold not met")

	// ErrSigningFailed is returned when MPC signing fails
	ErrSigningFailed = errors.New("signing ceremony failed")
)
View Source
var CryptoCurrencies = map[currency.Type]bool{
	currency.BTC: true,
	currency.ETH: true,
	currency.XBT: true,
	"sol":        true,
	"usdc":       true,
	"usdt":       true,
	"matic":      true,
	"avax":       true,
	"lux":        true,
}

CryptoCurrencies supported by MPC (extend beyond what's in currency.IsCrypto)

Functions

func CommonCryptoCurrencies

func CommonCryptoCurrencies() []currency.Type

CommonCryptoCurrencies returns common crypto currencies

func CommonFiatCurrencies

func CommonFiatCurrencies() []currency.Type

CommonFiatCurrencies returns common fiat currencies

func IsCryptoCurrency

func IsCryptoCurrency(c currency.Type) bool

IsCryptoCurrency checks if a currency is a cryptocurrency

func Register

func Register(p PaymentProcessor)

Register adds a processor to the global registry

func SupportsCurrency

func SupportsCurrency(p PaymentProcessor, c currency.Type) bool

SupportsCurrency checks if a processor supports a currency

func ValidateRequest

func ValidateRequest(req PaymentRequest) error

ValidateRequest validates a payment request

Types

type Balance

type Balance struct {
	Available currency.Cents `json:"available"`
	Pending   currency.Cents `json:"pending"`
	Currency  currency.Type  `json:"currency"`
}

Balance represents a wallet balance

type BaseProcessor

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

BaseProcessor provides common functionality for all processors

func NewBaseProcessor

func NewBaseProcessor(t ProcessorType, currencies []currency.Type) *BaseProcessor

NewBaseProcessor creates a new base processor

func (*BaseProcessor) Authorize

func (b *BaseProcessor) Authorize(ctx context.Context, req PaymentRequest) (*PaymentResult, error)

Authorize provides a default implementation that calls Charge Processors that support auth/capture should override this

func (*BaseProcessor) Capture

func (b *BaseProcessor) Capture(ctx context.Context, transactionID string, amount currency.Cents) (*PaymentResult, error)

Capture provides a default implementation Processors that support auth/capture should override this

func (*BaseProcessor) IsAvailable

func (b *BaseProcessor) IsAvailable(ctx context.Context) bool

IsAvailable returns whether the processor is available

func (*BaseProcessor) SetConfigured

func (b *BaseProcessor) SetConfigured(configured bool)

SetConfigured marks the processor as configured

func (*BaseProcessor) SupportedCurrencies

func (b *BaseProcessor) SupportedCurrencies() []currency.Type

SupportedCurrencies returns the supported currencies

func (*BaseProcessor) Type

func (b *BaseProcessor) Type() ProcessorType

Type returns the processor type

type CryptoProcessor

type CryptoProcessor interface {
	PaymentProcessor

	// GenerateAddress creates a new payment address for a customer
	GenerateAddress(ctx context.Context, customerID string, chain string) (string, error)

	// GetBalance returns the balance for an address
	GetBalance(ctx context.Context, address string, chain string) (*Balance, error)

	// EstimateFee estimates transaction fees for a payment
	EstimateFee(ctx context.Context, req PaymentRequest) (currency.Cents, error)

	// SupportedChains returns the list of supported blockchain networks
	SupportedChains() []string
}

CryptoProcessor extends PaymentProcessor with crypto-specific methods

type CustomerProcessor

type CustomerProcessor interface {
	PaymentProcessor

	// CreateCustomer creates a customer in the processor
	CreateCustomer(ctx context.Context, email, name string, metadata map[string]interface{}) (string, error)

	// GetCustomer retrieves customer details
	GetCustomer(ctx context.Context, customerID string) (map[string]interface{}, error)

	// UpdateCustomer updates customer details
	UpdateCustomer(ctx context.Context, customerID string, updates map[string]interface{}) error

	// DeleteCustomer removes a customer
	DeleteCustomer(ctx context.Context, customerID string) error

	// AddPaymentMethod adds a payment method to a customer
	AddPaymentMethod(ctx context.Context, customerID, token string) (string, error)

	// RemovePaymentMethod removes a payment method
	RemovePaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
}

CustomerProcessor extends PaymentProcessor with customer management

type PaymentError

type PaymentError struct {
	Processor ProcessorType
	Code      string
	Message   string
	Err       error
}

PaymentError wraps a processor error with additional context

func NewPaymentError

func NewPaymentError(processor ProcessorType, code, message string, err error) *PaymentError

NewPaymentError creates a new payment error

func (*PaymentError) Error

func (e *PaymentError) Error() string

func (*PaymentError) Unwrap

func (e *PaymentError) Unwrap() error

type PaymentProcessor

type PaymentProcessor interface {
	// Type returns the processor type
	Type() ProcessorType

	// Charge processes a payment
	Charge(ctx context.Context, req PaymentRequest) (*PaymentResult, error)

	// Authorize authorizes a payment without capturing
	Authorize(ctx context.Context, req PaymentRequest) (*PaymentResult, error)

	// Capture captures a previously authorized payment
	Capture(ctx context.Context, transactionID string, amount currency.Cents) (*PaymentResult, error)

	// Refund processes a refund
	Refund(ctx context.Context, req RefundRequest) (*RefundResult, error)

	// GetTransaction retrieves transaction details
	GetTransaction(ctx context.Context, txID string) (*Transaction, error)

	// ValidateWebhook validates an incoming webhook
	ValidateWebhook(ctx context.Context, payload []byte, signature string) (*WebhookEvent, error)

	// SupportedCurrencies returns currencies this processor supports
	SupportedCurrencies() []currency.Type

	// IsAvailable checks if processor is configured and available
	IsAvailable(ctx context.Context) bool
}

PaymentProcessor is the interface all payment processors must implement

func Get

Get retrieves a processor from the global registry

func SelectProcessor

func SelectProcessor(ctx context.Context, req PaymentRequest) (PaymentProcessor, error)

SelectProcessor selects a processor from the global registry

type PaymentRequest

type PaymentRequest struct {
	Amount      currency.Cents         `json:"amount"`
	Currency    currency.Type          `json:"currency"`
	Description string                 `json:"description,omitempty"`
	CustomerID  string                 `json:"customerId,omitempty"`
	OrderID     string                 `json:"orderId,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`

	// Processor-specific options
	Options map[string]interface{} `json:"options,omitempty"`

	// For card payments
	Token string `json:"token,omitempty"`

	// For crypto payments
	Address string `json:"address,omitempty"`
	Chain   string `json:"chain,omitempty"`
}

PaymentRequest represents a payment to be processed

type PaymentResult

type PaymentResult struct {
	Success       bool                   `json:"success"`
	TransactionID string                 `json:"transactionId"`
	ProcessorRef  string                 `json:"processorRef"`
	Fee           currency.Cents         `json:"fee"`
	Error         error                  `json:"-"`
	ErrorMessage  string                 `json:"error,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
	Status        string                 `json:"status"`
}

PaymentResult represents the outcome of a payment

type ProcessorType

type ProcessorType string

ProcessorType identifies the payment processor

const (
	Stripe           ProcessorType = "stripe"
	Square           ProcessorType = "square"
	PayPal           ProcessorType = "paypal"
	Adyen            ProcessorType = "adyen"
	Braintree        ProcessorType = "braintree"
	Recurly          ProcessorType = "recurly"
	LemonSqueezy     ProcessorType = "lemonsqueezy"
	BitPay           ProcessorType = "bitpay"
	CoinbaseCommerce ProcessorType = "coinbase_commerce"
	OpenNode         ProcessorType = "opennode"
	Bitcoin          ProcessorType = "bitcoin"
	Ethereum         ProcessorType = "ethereum"
	MPC              ProcessorType = "mpc"
	Wire             ProcessorType = "wire"
	SolanaPay        ProcessorType = "solanapay"
	Circle           ProcessorType = "circle"
	MoonPay          ProcessorType = "moonpay"
)

type RefundRequest

type RefundRequest struct {
	TransactionID string                 `json:"transactionId"`
	Amount        currency.Cents         `json:"amount"`
	Reason        string                 `json:"reason,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

RefundRequest represents a refund to be processed

type RefundResult

type RefundResult struct {
	Success      bool   `json:"success"`
	RefundID     string `json:"refundId"`
	ProcessorRef string `json:"processorRef"`
	Error        error  `json:"-"`
	ErrorMessage string `json:"error,omitempty"`
}

RefundResult represents the outcome of a refund

type Registry

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

Registry manages available payment processors

func Global

func Global() *Registry

Global returns the global registry instance

func NewRegistry

func NewRegistry(config *RegistryConfig) *Registry

NewRegistry creates a new processor registry

func (*Registry) Available

func (r *Registry) Available(ctx context.Context) []PaymentProcessor

Available returns all available processors

func (*Registry) DisableProcessor

func (r *Registry) DisableProcessor(t ProcessorType)

DisableProcessor disables a processor

func (*Registry) EnableProcessor

func (r *Registry) EnableProcessor(t ProcessorType)

EnableProcessor enables a processor

func (*Registry) Get

Get retrieves a processor by type

func (*Registry) GetCrypto

func (r *Registry) GetCrypto(t ProcessorType) (CryptoProcessor, error)

GetCrypto retrieves a crypto processor

func (*Registry) GetCustomer

func (r *Registry) GetCustomer(t ProcessorType) (CustomerProcessor, error)

GetCustomer retrieves a customer processor

func (*Registry) GetSubscription

func (r *Registry) GetSubscription(t ProcessorType) (SubscriptionProcessor, error)

GetSubscription retrieves a subscription processor

func (*Registry) ListTypes

func (r *Registry) ListTypes() []ProcessorType

ListTypes returns all registered processor types

func (*Registry) Register

func (r *Registry) Register(p PaymentProcessor)

Register adds a processor to the registry

func (*Registry) SelectProcessor

func (r *Registry) SelectProcessor(ctx context.Context, req PaymentRequest) (PaymentProcessor, error)

SelectProcessor chooses the best processor for the payment

func (*Registry) SelectSubscriptionProcessor

func (r *Registry) SelectSubscriptionProcessor(ctx context.Context, req PaymentRequest) (SubscriptionProcessor, error)

SelectSubscriptionProcessor chooses a processor that supports subscriptions

func (*Registry) SetConfig

func (r *Registry) SetConfig(config *RegistryConfig)

SetConfig updates the registry configuration

func (*Registry) Unregister

func (r *Registry) Unregister(t ProcessorType)

Unregister removes a processor from the registry

type RegistryConfig

type RegistryConfig struct {
	// DefaultFiatProcessor is the default for fiat currencies
	DefaultFiatProcessor ProcessorType

	// DefaultCryptoProcessor is the default for crypto currencies
	DefaultCryptoProcessor ProcessorType

	// ProcessorPriority defines the order to try processors
	ProcessorPriority []ProcessorType

	// DisabledProcessors lists processors that should not be used
	DisabledProcessors map[ProcessorType]bool
}

RegistryConfig holds configuration for processor selection

func DefaultConfig

func DefaultConfig() *RegistryConfig

DefaultConfig returns the default registry configuration

type Subscription

type Subscription struct {
	ID                 string                 `json:"id"`
	CustomerID         string                 `json:"customerId"`
	PlanID             string                 `json:"planId"`
	Status             string                 `json:"status"` // active, canceled, past_due, trialing
	CurrentPeriodStart int64                  `json:"currentPeriodStart"`
	CurrentPeriodEnd   int64                  `json:"currentPeriodEnd"`
	CancelAtPeriodEnd  bool                   `json:"cancelAtPeriodEnd"`
	Metadata           map[string]interface{} `json:"metadata,omitempty"`
}

Subscription represents an active subscription

type SubscriptionProcessor

type SubscriptionProcessor interface {
	PaymentProcessor

	// CreateSubscription creates a recurring subscription
	CreateSubscription(ctx context.Context, req SubscriptionRequest) (*Subscription, error)

	// GetSubscription retrieves subscription details
	GetSubscription(ctx context.Context, subscriptionID string) (*Subscription, error)

	// CancelSubscription cancels a subscription
	CancelSubscription(ctx context.Context, subscriptionID string, immediately bool) error

	// UpdateSubscription modifies a subscription
	UpdateSubscription(ctx context.Context, subscriptionID string, req SubscriptionUpdate) (*Subscription, error)

	// ListSubscriptions lists subscriptions for a customer
	ListSubscriptions(ctx context.Context, customerID string) ([]*Subscription, error)
}

SubscriptionProcessor extends PaymentProcessor with subscription methods

type SubscriptionRequest

type SubscriptionRequest struct {
	CustomerID   string                 `json:"customerId"`
	PlanID       string                 `json:"planId"`
	Quantity     int                    `json:"quantity"`
	TrialDays    int                    `json:"trialDays,omitempty"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	PaymentToken string                 `json:"paymentToken,omitempty"`
}

SubscriptionRequest represents a subscription creation request

type SubscriptionUpdate

type SubscriptionUpdate struct {
	PlanID            string `json:"planId,omitempty"`
	Quantity          int    `json:"quantity,omitempty"`
	CancelAtPeriodEnd *bool  `json:"cancelAtPeriodEnd,omitempty"`
}

SubscriptionUpdate represents subscription modification

type Transaction

type Transaction struct {
	ID           string                 `json:"id"`
	ProcessorRef string                 `json:"processorRef"`
	Type         string                 `json:"type"` // charge, refund, transfer
	Amount       currency.Cents         `json:"amount"`
	Currency     currency.Type          `json:"currency"`
	Status       string                 `json:"status"`
	Fee          currency.Cents         `json:"fee"`
	CustomerID   string                 `json:"customerId,omitempty"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt    int64                  `json:"createdAt"`
	UpdatedAt    int64                  `json:"updatedAt"`
}

Transaction represents a stored transaction

type WebhookEvent

type WebhookEvent struct {
	ID        string                 `json:"id"`
	Type      string                 `json:"type"`
	Processor ProcessorType          `json:"processor"`
	Data      map[string]interface{} `json:"data"`
	Timestamp int64                  `json:"timestamp"`
}

WebhookEvent represents an incoming webhook from a processor

Jump to

Keyboard shortcuts

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