Documentation
¶
Overview ¶
Package gopay provides a unified interface for payment processing across multiple providers including Stripe, PayPal, and Razorpay.
Each provider lives in its own sub-module so that importing one provider does not pull in the dependencies of another. For example, using PayPal will not require the Stripe SDK.
Core Package ¶
This package defines the shared interfaces (Provider, CustomerProvider, PaymentMethodProvider, WebhookProvider), request/response types, sentinel errors, and the Client that wraps any provider with validation and convenience methods.
client, err := gopay.NewClient(provider) p, err := client.CreatePayment(ctx, gopay.NewPaymentRequest(gopay.USD(1999)))
Providers ¶
Install only the providers you need:
go get github.com/KARTIKrocks/gopay/stripe go get github.com/KARTIKrocks/gopay/paypal go get github.com/KARTIKrocks/gopay/razorpay
Each provider package exports a Config, a Provider (which implements Provider and optionally CustomerProvider / PaymentMethodProvider / WebhookProvider), and a NewProvider constructor.
Testing ¶
Use MockProvider for unit tests without hitting any external API:
mock := gopay.NewMockProvider() mock.WithAutoSucceed(true) client, err := gopay.NewClient(mock)
Webhooks ¶
Use WebhookProvider.VerifyWebhook to verify and parse incoming webhook events. Each provider package also exports a ParseWebhook function that parses the payload without signature verification — this is useful for debugging or when verification is handled elsewhere (e.g. by a gateway), but should not be used in production without separate verification.
The returned WebhookEvent is provider-normalized: switch on its Kind (a WebhookEventKind such as WebhookPaymentSucceeded or WebhookRefundSucceeded) and read the normalized PaymentID, OrderID, RefundID, and Amount fields instead of parsing the provider-specific Raw payload. Amount is in integer minor units across all providers (nil when absent); unmapped events have Kind WebhookUnknown with Type and Raw preserved.
Error Handling ¶
All provider-specific errors are mapped to sentinel errors defined in this package (e.g. ErrCardDeclined, ErrInsufficientFunds, ErrNotFound). Use errors.Is for matching:
if errors.Is(err, gopay.ErrCardDeclined) {
// handle declined card
}
Index ¶
- Constants
- Variables
- type Address
- type Amount
- type BillingDetails
- type CaptureMethod
- type CardDetails
- type Client
- func (c *Client) AttachPaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
- func (c *Client) CancelPayment(ctx context.Context, paymentID string) (*Payment, error)
- func (c *Client) CancelSetupIntent(ctx context.Context, setupIntentID string) (*SetupIntent, error)
- func (c *Client) CapturePayment(ctx context.Context, paymentID string, amount *Amount) (*Payment, error)
- func (c *Client) CreateCustomer(ctx context.Context, req *CustomerRequest) (*Customer, error)
- func (c *Client) CreatePayment(ctx context.Context, req *PaymentRequest) (*Payment, error)
- func (c *Client) CreateSetupIntent(ctx context.Context, req *SetupIntentRequest) (*SetupIntent, error)
- func (c *Client) DeleteCustomer(ctx context.Context, customerID string) error
- func (c *Client) DetachPaymentMethod(ctx context.Context, paymentMethodID string) error
- func (c *Client) FullRefund(ctx context.Context, paymentID string) (*Refund, error)
- func (c *Client) GetCustomer(ctx context.Context, customerID string) (*Customer, error)
- func (c *Client) GetPayment(ctx context.Context, paymentID string) (*Payment, error)
- func (c *Client) GetRefund(ctx context.Context, refundID string) (*Refund, error)
- func (c *Client) GetSetupIntent(ctx context.Context, setupIntentID string) (*SetupIntent, error)
- func (c *Client) ListCustomers(ctx context.Context, params *ListParams) (*List[*Customer], error)
- func (c *Client) ListPaymentMethods(ctx context.Context, customerID string) ([]*PaymentMethod, error)
- func (c *Client) ListPayments(ctx context.Context, params *ListParams) (*List[*Payment], error)
- func (c *Client) ListRefunds(ctx context.Context, params *ListParams) (*List[*Refund], error)
- func (c *Client) Provider() Provider
- func (c *Client) ProviderName() string
- func (c *Client) Refund(ctx context.Context, req *RefundRequest) (*Refund, error)
- func (c *Client) UpdateCustomer(ctx context.Context, customerID string, req *CustomerRequest) (*Customer, error)
- func (c *Client) VerifyWebhook(ctx context.Context, payload []byte, headers map[string]string) (*WebhookEvent, error)
- type Customer
- type CustomerProvider
- type CustomerRequest
- func (r *CustomerRequest) Validate() error
- func (r *CustomerRequest) WithDescription(desc string) *CustomerRequest
- func (r *CustomerRequest) WithMetadata(key, value string) *CustomerRequest
- func (r *CustomerRequest) WithName(name string) *CustomerRequest
- func (r *CustomerRequest) WithPhone(phone string) *CustomerRequest
- type List
- type ListParams
- type ListProvider
- type MockProvider
- func (p *MockProvider) AttachPaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
- func (p *MockProvider) CancelPayment(ctx context.Context, paymentID string) (*Payment, error)
- func (p *MockProvider) CancelSetupIntent(_ context.Context, setupIntentID string) (*SetupIntent, error)
- func (p *MockProvider) CapturePayment(ctx context.Context, paymentID string, amount *Amount) (*Payment, error)
- func (p *MockProvider) CreateCustomer(ctx context.Context, req *CustomerRequest) (*Customer, error)
- func (p *MockProvider) CreatePayment(ctx context.Context, req *PaymentRequest) (*Payment, error)
- func (p *MockProvider) CreateSetupIntent(_ context.Context, req *SetupIntentRequest) (*SetupIntent, error)
- func (p *MockProvider) Customers() map[string]*Customer
- func (p *MockProvider) DeleteCustomer(ctx context.Context, customerID string) error
- func (p *MockProvider) DetachPaymentMethod(ctx context.Context, paymentMethodID string) error
- func (p *MockProvider) GetCustomer(ctx context.Context, customerID string) (*Customer, error)
- func (p *MockProvider) GetPayment(ctx context.Context, paymentID string) (*Payment, error)
- func (p *MockProvider) GetRefund(ctx context.Context, refundID string) (*Refund, error)
- func (p *MockProvider) GetSetupIntent(_ context.Context, setupIntentID string) (*SetupIntent, error)
- func (p *MockProvider) ListCustomers(_ context.Context, params *ListParams) (*List[*Customer], error)
- func (p *MockProvider) ListPaymentMethods(ctx context.Context, customerID string) ([]*PaymentMethod, error)
- func (p *MockProvider) ListPayments(_ context.Context, params *ListParams) (*List[*Payment], error)
- func (p *MockProvider) ListRefunds(_ context.Context, params *ListParams) (*List[*Refund], error)
- func (p *MockProvider) Name() string
- func (p *MockProvider) Payments() map[string]*Payment
- func (p *MockProvider) Refund(ctx context.Context, req *RefundRequest) (*Refund, error)
- func (p *MockProvider) Refunds() map[string]*Refund
- func (p *MockProvider) Reset()
- func (p *MockProvider) SetCustomer(customer *Customer)
- func (p *MockProvider) SetPayment(payment *Payment)
- func (p *MockProvider) SetRefund(refund *Refund)
- func (p *MockProvider) SetSetupIntent(si *SetupIntent)
- func (p *MockProvider) UpdateCustomer(ctx context.Context, customerID string, req *CustomerRequest) (*Customer, error)
- func (p *MockProvider) VerifyWebhook(_ context.Context, payload []byte, _ map[string]string) (*WebhookEvent, error)
- func (p *MockProvider) WithAutoCapture(auto bool) *MockProvider
- func (p *MockProvider) WithAutoSucceed(auto bool) *MockProvider
- func (p *MockProvider) WithCaptureError(err error) *MockProvider
- func (p *MockProvider) WithCreateError(err error) *MockProvider
- func (p *MockProvider) WithRefundError(err error) *MockProvider
- func (p *MockProvider) WithSetupError(err error) *MockProvider
- func (p *MockProvider) WithWebhookError(err error) *MockProvider
- type Payment
- type PaymentMethod
- type PaymentMethodProvider
- type PaymentMethodType
- type PaymentRequest
- func (r *PaymentRequest) Validate() error
- func (r *PaymentRequest) WithCaptureMethod(method CaptureMethod) *PaymentRequest
- func (r *PaymentRequest) WithCustomer(customerID string) *PaymentRequest
- func (r *PaymentRequest) WithDescription(desc string) *PaymentRequest
- func (r *PaymentRequest) WithIdempotencyKey(key string) *PaymentRequest
- func (r *PaymentRequest) WithMetadata(key, value string) *PaymentRequest
- func (r *PaymentRequest) WithPaymentMethod(paymentMethodID string) *PaymentRequest
- func (r *PaymentRequest) WithReturnURL(url string) *PaymentRequest
- type PaymentStatus
- type Provider
- type Refund
- type RefundReason
- type RefundRequest
- func (r *RefundRequest) Validate() error
- func (r *RefundRequest) WithAmount(amount *Amount) *RefundRequest
- func (r *RefundRequest) WithIdempotencyKey(key string) *RefundRequest
- func (r *RefundRequest) WithMetadata(key, value string) *RefundRequest
- func (r *RefundRequest) WithReason(reason RefundReason) *RefundRequest
- type RefundStatus
- type SetupIntent
- type SetupIntentProvider
- type SetupIntentRequest
- func (r *SetupIntentRequest) Validate() error
- func (r *SetupIntentRequest) WithCustomer(customerID string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithDescription(desc string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithIdempotencyKey(key string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithMetadata(key, value string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithPaymentMethod(paymentMethodID string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithReturnURL(url string) *SetupIntentRequest
- func (r *SetupIntentRequest) WithUsage(usage SetupIntentUsage) *SetupIntentRequest
- type SetupIntentStatus
- type SetupIntentUsage
- type WebhookEvent
- type WebhookEventKind
- type WebhookProvider
Constants ¶
const ( DefaultListLimit = 20 MaxListLimit = 100 )
Default and maximum page sizes for list operations. When ListParams.Limit is zero or negative, DefaultListLimit is used; Limit may not exceed MaxListLimit.
Variables ¶
var ( ErrInvalidConfig = errors.New("gopay: invalid configuration") ErrInvalidAmount = errors.New("gopay: invalid amount") ErrInvalidCurrency = errors.New("gopay: invalid currency") ErrInvalidCard = errors.New("gopay: invalid card") ErrCardDeclined = errors.New("gopay: card declined") ErrInsufficientFunds = errors.New("gopay: insufficient funds") ErrExpiredCard = errors.New("gopay: expired card") ErrPaymentFailed = errors.New("gopay: payment failed") ErrRefundFailed = errors.New("gopay: refund failed") ErrSetupFailed = errors.New("gopay: setup failed") ErrNotFound = errors.New("gopay: not found") ErrAlreadyRefunded = errors.New("gopay: already refunded") ErrAlreadyCaptured = errors.New("gopay: already captured") ErrAuthenticationRequired = errors.New("gopay: authentication required") ErrProviderError = errors.New("gopay: provider error") ErrUnsupported = errors.New("gopay: operation not supported") )
Sentinel errors for payment operations.
Functions ¶
This section is empty.
Types ¶
type Address ¶
type Address struct {
Line1 string
Line2 string
City string
State string
PostalCode string
Country string
}
Address represents a physical address.
type Amount ¶
type Amount struct {
// Value is the amount in the smallest currency unit (e.g., cents).
Value int64
// Currency is the three-letter ISO currency code.
Currency string
}
Amount represents a monetary amount.
func ParseMajorUnitAmount ¶ added in v0.2.0
ParseMajorUnitAmount converts a major-unit decimal amount string (e.g. "10.00") in the given currency into a normalized minor-unit Amount (e.g. 1000 for USD, 500 for "500" JPY). Fractional digits beyond the currency's minor unit are rounded half-up.
It returns (nil, false) if the currency is unknown or the string is not a valid decimal number, so callers can leave WebhookEvent.Amount nil rather than recording a wrong value. Providers that already report integer minor units (Stripe, Razorpay) should use NewAmount directly instead.
type BillingDetails ¶
type BillingDetails struct {
// Name is the billing name.
Name string
// Email is the billing email.
Email string
// Phone is the billing phone.
Phone string
// Address is the billing address.
Address *Address
}
BillingDetails contains billing information.
type CaptureMethod ¶
type CaptureMethod string
CaptureMethod determines when funds are captured.
const ( // CaptureAutomatic captures funds immediately. CaptureAutomatic CaptureMethod = "automatic" // CaptureManual requires a separate capture call. CaptureManual CaptureMethod = "manual" )
func (CaptureMethod) String ¶
func (c CaptureMethod) String() string
String returns the string representation.
type CardDetails ¶
type CardDetails struct {
// Brand is the card brand (visa, mastercard, etc.).
Brand string
// Last4 is the last 4 digits.
Last4 string
// ExpMonth is the expiration month.
ExpMonth int
// ExpYear is the expiration year.
ExpYear int
// Funding is the funding type (credit, debit, prepaid).
Funding string
// Country is the card's country.
Country string
}
CardDetails contains card information.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main payment client.
func (*Client) AttachPaymentMethod ¶
AttachPaymentMethod attaches a payment method to a customer (if supported).
func (*Client) CancelPayment ¶
CancelPayment cancels an authorized payment.
func (*Client) CancelSetupIntent ¶ added in v0.4.0
CancelSetupIntent cancels a setup intent (if supported).
func (*Client) CapturePayment ¶
func (c *Client) CapturePayment(ctx context.Context, paymentID string, amount *Amount) (*Payment, error)
CapturePayment captures an authorized payment.
func (*Client) CreateCustomer ¶
CreateCustomer creates a customer (if supported).
func (*Client) CreatePayment ¶
CreatePayment creates a new payment.
func (*Client) CreateSetupIntent ¶ added in v0.4.0
func (c *Client) CreateSetupIntent(ctx context.Context, req *SetupIntentRequest) (*SetupIntent, error)
CreateSetupIntent sets up a payment method for future off-session charges without moving money (if supported).
func (*Client) DeleteCustomer ¶
DeleteCustomer deletes a customer (if supported).
func (*Client) DetachPaymentMethod ¶
DetachPaymentMethod detaches a payment method from a customer (if supported).
func (*Client) FullRefund ¶
FullRefund creates a full refund for a payment.
func (*Client) GetCustomer ¶
GetCustomer retrieves a customer (if supported).
func (*Client) GetPayment ¶
GetPayment retrieves a payment.
func (*Client) GetSetupIntent ¶ added in v0.4.0
GetSetupIntent retrieves a setup intent (if supported).
func (*Client) ListCustomers ¶ added in v0.3.0
ListCustomers lists customers with cursor-based pagination (if supported).
func (*Client) ListPaymentMethods ¶
func (c *Client) ListPaymentMethods(ctx context.Context, customerID string) ([]*PaymentMethod, error)
ListPaymentMethods lists payment methods for a customer (if supported).
func (*Client) ListPayments ¶ added in v0.3.0
ListPayments lists payments with cursor-based pagination (if supported).
func (*Client) ListRefunds ¶ added in v0.3.0
ListRefunds lists refunds with cursor-based pagination (if supported).
func (*Client) ProviderName ¶
ProviderName returns the provider name.
func (*Client) UpdateCustomer ¶
func (c *Client) UpdateCustomer(ctx context.Context, customerID string, req *CustomerRequest) (*Customer, error)
UpdateCustomer updates a customer (if supported).
func (*Client) VerifyWebhook ¶
func (c *Client) VerifyWebhook(ctx context.Context, payload []byte, headers map[string]string) (*WebhookEvent, error)
VerifyWebhook verifies and parses a webhook event (if supported).
type Customer ¶
type Customer struct {
// ID is the customer ID.
ID string
// Email is the customer's email.
Email string
// Name is the customer's name.
Name string
// Phone is the customer's phone.
Phone string
// Description is the description.
Description string
// DefaultPaymentMethodID is the default payment method.
DefaultPaymentMethodID string
// Metadata holds additional data.
Metadata map[string]string
// CreatedAt is the creation timestamp.
CreatedAt time.Time
// Provider is the provider name.
Provider string
// Raw contains the raw provider response.
Raw map[string]any
}
Customer represents a customer.
type CustomerProvider ¶
type CustomerProvider interface {
Provider
// CreateCustomer creates a new customer.
CreateCustomer(ctx context.Context, req *CustomerRequest) (*Customer, error)
// GetCustomer retrieves a customer by ID.
GetCustomer(ctx context.Context, customerID string) (*Customer, error)
// UpdateCustomer updates a customer.
UpdateCustomer(ctx context.Context, customerID string, req *CustomerRequest) (*Customer, error)
// DeleteCustomer deletes a customer.
DeleteCustomer(ctx context.Context, customerID string) error
}
CustomerProvider extends Provider with customer management.
type CustomerRequest ¶
type CustomerRequest struct {
// Email is the customer's email.
Email string
// Name is the customer's name.
Name string
// Phone is the customer's phone.
Phone string
// Description is an optional description.
Description string
// Metadata holds additional data.
Metadata map[string]string
}
CustomerRequest represents a customer creation/update request.
func NewCustomerRequest ¶
func NewCustomerRequest(email string) *CustomerRequest
NewCustomerRequest creates a new customer request.
func (*CustomerRequest) Validate ¶
func (r *CustomerRequest) Validate() error
Validate validates the customer request.
func (*CustomerRequest) WithDescription ¶
func (r *CustomerRequest) WithDescription(desc string) *CustomerRequest
WithDescription sets the description.
func (*CustomerRequest) WithMetadata ¶
func (r *CustomerRequest) WithMetadata(key, value string) *CustomerRequest
WithMetadata adds metadata.
func (*CustomerRequest) WithName ¶
func (r *CustomerRequest) WithName(name string) *CustomerRequest
WithName sets the name.
func (*CustomerRequest) WithPhone ¶
func (r *CustomerRequest) WithPhone(phone string) *CustomerRequest
WithPhone sets the phone.
type List ¶ added in v0.3.0
type List[T any] struct { // Items are the results on this page. Items []T // HasMore reports whether additional pages are available. HasMore bool // NextCursor is the opaque cursor for the next page; empty when HasMore is // false. NextCursor string }
List is a single page of results from a paginated list operation.
HasMore reports whether further pages exist; when true, NextCursor holds the opaque cursor to pass to the next request (via ListParams.WithCursor).
type ListParams ¶ added in v0.3.0
type ListParams struct {
// Limit is the maximum number of items to return per page. When zero or
// negative, the provider's default page size (DefaultListLimit) is used.
Limit int
// Cursor is an opaque pagination cursor returned as NextCursor by a previous
// page. Empty starts from the first page.
Cursor string
}
ListParams controls pagination for list operations.
Pagination is cursor-based: each List result carries an opaque NextCursor that is passed back via WithCursor to fetch the following page. The cursor is provider-specific and must be treated as opaque by callers.
func NewListParams ¶ added in v0.3.0
func NewListParams() *ListParams
NewListParams creates a new ListParams with default pagination.
func (*ListParams) EffectiveLimit ¶ added in v0.3.0
func (p *ListParams) EffectiveLimit() int
EffectiveLimit returns the page size to request, applying DefaultListLimit when Limit is unset (zero or negative). It is a helper for provider implementations.
func (*ListParams) Validate ¶ added in v0.3.0
func (p *ListParams) Validate() error
Validate validates the list parameters.
func (*ListParams) WithCursor ¶ added in v0.3.0
func (p *ListParams) WithCursor(cursor string) *ListParams
WithCursor sets the pagination cursor (the NextCursor from a previous page).
func (*ListParams) WithLimit ¶ added in v0.3.0
func (p *ListParams) WithLimit(limit int) *ListParams
WithLimit sets the maximum number of items per page.
type ListProvider ¶ added in v0.3.0
type ListProvider interface {
Provider
// ListPayments lists payments with cursor-based pagination.
ListPayments(ctx context.Context, params *ListParams) (*List[*Payment], error)
// ListRefunds lists refunds with cursor-based pagination.
ListRefunds(ctx context.Context, params *ListParams) (*List[*Refund], error)
// ListCustomers lists customers with cursor-based pagination.
ListCustomers(ctx context.Context, params *ListParams) (*List[*Customer], error)
}
ListProvider extends Provider with listing and pagination capabilities.
It is an optional interface: providers implement it only when their API supports listing. The Client gates each method with a runtime type assertion and returns ErrUnsupported for providers that don't implement it.
All methods must handle a nil params: use ListParams.EffectiveLimit to derive a safe page size and treat an empty cursor as "start from the first page".
type MockProvider ¶
type MockProvider struct {
// contains filtered or unexported fields
}
MockProvider is a mock payment provider for testing.
func NewMockProvider ¶
func NewMockProvider() *MockProvider
NewMockProvider creates a new mock provider.
func (*MockProvider) AttachPaymentMethod ¶
func (p *MockProvider) AttachPaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
AttachPaymentMethod attaches a payment method to a customer.
func (*MockProvider) CancelPayment ¶
CancelPayment cancels a mock payment.
func (*MockProvider) CancelSetupIntent ¶ added in v0.4.0
func (p *MockProvider) CancelSetupIntent(_ context.Context, setupIntentID string) (*SetupIntent, error)
CancelSetupIntent cancels a mock setup intent.
func (*MockProvider) CapturePayment ¶
func (p *MockProvider) CapturePayment(ctx context.Context, paymentID string, amount *Amount) (*Payment, error)
CapturePayment captures a mock payment.
func (*MockProvider) CreateCustomer ¶
func (p *MockProvider) CreateCustomer(ctx context.Context, req *CustomerRequest) (*Customer, error)
CreateCustomer creates a mock customer.
func (*MockProvider) CreatePayment ¶
func (p *MockProvider) CreatePayment(ctx context.Context, req *PaymentRequest) (*Payment, error)
CreatePayment creates a mock payment.
func (*MockProvider) CreateSetupIntent ¶ added in v0.4.0
func (p *MockProvider) CreateSetupIntent(_ context.Context, req *SetupIntentRequest) (*SetupIntent, error)
CreateSetupIntent creates a mock setup intent. When a PaymentMethodID is supplied and auto-succeed is on, the intent is marked succeeded; otherwise it awaits confirmation.
func (*MockProvider) Customers ¶
func (p *MockProvider) Customers() map[string]*Customer
Customers returns all customers.
func (*MockProvider) DeleteCustomer ¶
func (p *MockProvider) DeleteCustomer(ctx context.Context, customerID string) error
DeleteCustomer deletes a mock customer.
func (*MockProvider) DetachPaymentMethod ¶
func (p *MockProvider) DetachPaymentMethod(ctx context.Context, paymentMethodID string) error
DetachPaymentMethod detaches a payment method.
func (*MockProvider) GetCustomer ¶
GetCustomer retrieves a mock customer.
func (*MockProvider) GetPayment ¶
GetPayment retrieves a mock payment.
func (*MockProvider) GetSetupIntent ¶ added in v0.4.0
func (p *MockProvider) GetSetupIntent(_ context.Context, setupIntentID string) (*SetupIntent, error)
GetSetupIntent retrieves a mock setup intent.
func (*MockProvider) ListCustomers ¶ added in v0.3.0
func (p *MockProvider) ListCustomers(_ context.Context, params *ListParams) (*List[*Customer], error)
ListCustomers lists mock customers with cursor-based pagination.
func (*MockProvider) ListPaymentMethods ¶
func (p *MockProvider) ListPaymentMethods(ctx context.Context, customerID string) ([]*PaymentMethod, error)
ListPaymentMethods lists payment methods for a customer.
func (*MockProvider) ListPayments ¶ added in v0.3.0
func (p *MockProvider) ListPayments(_ context.Context, params *ListParams) (*List[*Payment], error)
ListPayments lists mock payments with cursor-based pagination. Results are ordered newest-first (by CreatedAt, then ID for determinism); the opaque cursor is the ID of the last item on the previous page.
func (*MockProvider) ListRefunds ¶ added in v0.3.0
func (p *MockProvider) ListRefunds(_ context.Context, params *ListParams) (*List[*Refund], error)
ListRefunds lists mock refunds with cursor-based pagination.
func (*MockProvider) Payments ¶
func (p *MockProvider) Payments() map[string]*Payment
Payments returns all payments.
func (*MockProvider) Refund ¶
func (p *MockProvider) Refund(ctx context.Context, req *RefundRequest) (*Refund, error)
Refund creates a mock refund.
func (*MockProvider) Refunds ¶
func (p *MockProvider) Refunds() map[string]*Refund
Refunds returns all refunds.
func (*MockProvider) SetCustomer ¶
func (p *MockProvider) SetCustomer(customer *Customer)
SetCustomer manually sets a customer.
func (*MockProvider) SetPayment ¶
func (p *MockProvider) SetPayment(payment *Payment)
SetPayment manually sets a payment.
func (*MockProvider) SetRefund ¶
func (p *MockProvider) SetRefund(refund *Refund)
SetRefund manually sets a refund.
func (*MockProvider) SetSetupIntent ¶ added in v0.4.0
func (p *MockProvider) SetSetupIntent(si *SetupIntent)
SetSetupIntent manually sets a setup intent.
func (*MockProvider) UpdateCustomer ¶
func (p *MockProvider) UpdateCustomer(ctx context.Context, customerID string, req *CustomerRequest) (*Customer, error)
UpdateCustomer updates a mock customer.
func (*MockProvider) VerifyWebhook ¶
func (p *MockProvider) VerifyWebhook(_ context.Context, payload []byte, _ map[string]string) (*WebhookEvent, error)
VerifyWebhook verifies and parses a mock webhook event. It simply parses the payload as JSON and returns it as a WebhookEvent. Use WithWebhookError to simulate verification failures.
func (*MockProvider) WithAutoCapture ¶
func (p *MockProvider) WithAutoCapture(auto bool) *MockProvider
WithAutoCapture sets whether payments are auto-captured.
func (*MockProvider) WithAutoSucceed ¶
func (p *MockProvider) WithAutoSucceed(auto bool) *MockProvider
WithAutoSucceed sets whether payments auto-succeed.
func (*MockProvider) WithCaptureError ¶
func (p *MockProvider) WithCaptureError(err error) *MockProvider
WithCaptureError sets the error to return on CapturePayment.
func (*MockProvider) WithCreateError ¶
func (p *MockProvider) WithCreateError(err error) *MockProvider
WithCreateError sets the error to return on CreatePayment.
func (*MockProvider) WithRefundError ¶
func (p *MockProvider) WithRefundError(err error) *MockProvider
WithRefundError sets the error to return on Refund.
func (*MockProvider) WithSetupError ¶ added in v0.4.0
func (p *MockProvider) WithSetupError(err error) *MockProvider
WithSetupError sets the error to return on CreateSetupIntent.
func (*MockProvider) WithWebhookError ¶
func (p *MockProvider) WithWebhookError(err error) *MockProvider
WithWebhookError sets the error to return on VerifyWebhook.
type Payment ¶
type Payment struct {
// ID is the payment ID.
ID string
// Amount is the payment amount.
Amount *Amount
// Status is the payment status.
Status PaymentStatus
// Description is the payment description.
Description string
// CustomerID is the associated customer ID.
CustomerID string
// PaymentMethodID is the payment method used.
PaymentMethodID string
// CaptureMethod is the capture method.
CaptureMethod CaptureMethod
// AmountCaptured is the amount captured.
AmountCaptured int64
// AmountRefunded is the amount refunded.
AmountRefunded int64
// FailureCode is the failure code if failed.
FailureCode string
// FailureMessage is the failure message if failed.
FailureMessage string
// ClientSecret is the client secret (for frontend).
ClientSecret string
// RedirectURL is the URL for 3DS redirect.
RedirectURL string
// Metadata holds additional data.
Metadata map[string]string
// CreatedAt is the creation timestamp.
CreatedAt time.Time
// Provider is the provider name.
Provider string
// Raw contains the raw provider response.
Raw map[string]any
}
Payment represents a payment.
func (*Payment) IsCaptured ¶
IsCaptured returns true if the payment was captured.
func (*Payment) IsSuccessful ¶
IsSuccessful returns true if the payment was successful.
func (*Payment) RequiresAction ¶
RequiresAction returns true if the payment requires additional action.
type PaymentMethod ¶
type PaymentMethod struct {
// ID is the payment method ID.
ID string
// Type is the payment method type.
Type PaymentMethodType
// CustomerID is the associated customer ID.
CustomerID string
// Card contains card details (if type is card).
Card *CardDetails
// BillingDetails contains billing information.
BillingDetails *BillingDetails
// CreatedAt is the creation timestamp.
CreatedAt time.Time
// Provider is the provider name.
Provider string
// Raw contains the raw provider response.
Raw map[string]any
}
PaymentMethod represents a payment method.
type PaymentMethodProvider ¶
type PaymentMethodProvider interface {
Provider
// AttachPaymentMethod attaches a payment method to a customer.
AttachPaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
// DetachPaymentMethod detaches a payment method from a customer.
DetachPaymentMethod(ctx context.Context, paymentMethodID string) error
// ListPaymentMethods lists payment methods for a customer.
ListPaymentMethods(ctx context.Context, customerID string) ([]*PaymentMethod, error)
}
PaymentMethodProvider extends Provider with payment method management.
type PaymentMethodType ¶
type PaymentMethodType string
PaymentMethodType represents the type of payment method.
const ( PaymentMethodCard PaymentMethodType = "card" PaymentMethodBankAccount PaymentMethodType = "bank_account" PaymentMethodWallet PaymentMethodType = "wallet" PaymentMethodUPI PaymentMethodType = "upi" PaymentMethodNetBanking PaymentMethodType = "netbanking" )
Payment method type values.
func (PaymentMethodType) String ¶
func (t PaymentMethodType) String() string
String returns the string representation.
type PaymentRequest ¶
type PaymentRequest struct {
// Amount is the payment amount.
Amount *Amount
// Description is an optional description.
Description string
// CustomerID is the customer ID (optional).
CustomerID string
// PaymentMethodID is the payment method ID (optional).
PaymentMethodID string
// ReturnURL is the URL to redirect after payment (for 3DS).
ReturnURL string
// CaptureMethod determines when to capture funds.
CaptureMethod CaptureMethod
// Metadata holds additional data.
Metadata map[string]string
// IdempotencyKey for idempotent requests.
IdempotencyKey string
}
PaymentRequest represents a payment creation request.
func NewPaymentRequest ¶
func NewPaymentRequest(amount *Amount) *PaymentRequest
NewPaymentRequest creates a new payment request.
func (*PaymentRequest) Validate ¶
func (r *PaymentRequest) Validate() error
Validate validates the payment request.
func (*PaymentRequest) WithCaptureMethod ¶
func (r *PaymentRequest) WithCaptureMethod(method CaptureMethod) *PaymentRequest
WithCaptureMethod sets the capture method.
func (*PaymentRequest) WithCustomer ¶
func (r *PaymentRequest) WithCustomer(customerID string) *PaymentRequest
WithCustomer sets the customer ID.
func (*PaymentRequest) WithDescription ¶
func (r *PaymentRequest) WithDescription(desc string) *PaymentRequest
WithDescription sets the description.
func (*PaymentRequest) WithIdempotencyKey ¶
func (r *PaymentRequest) WithIdempotencyKey(key string) *PaymentRequest
WithIdempotencyKey sets the idempotency key.
func (*PaymentRequest) WithMetadata ¶
func (r *PaymentRequest) WithMetadata(key, value string) *PaymentRequest
WithMetadata adds metadata.
func (*PaymentRequest) WithPaymentMethod ¶
func (r *PaymentRequest) WithPaymentMethod(paymentMethodID string) *PaymentRequest
WithPaymentMethod sets the payment method ID.
func (*PaymentRequest) WithReturnURL ¶
func (r *PaymentRequest) WithReturnURL(url string) *PaymentRequest
WithReturnURL sets the return URL.
type PaymentStatus ¶
type PaymentStatus string
PaymentStatus represents the status of a payment.
const ( PaymentStatusPending PaymentStatus = "pending" PaymentStatusRequiresAction PaymentStatus = "requires_action" PaymentStatusProcessing PaymentStatus = "processing" PaymentStatusSucceeded PaymentStatus = "succeeded" PaymentStatusFailed PaymentStatus = "failed" PaymentStatusCanceled PaymentStatus = "canceled" PaymentStatusRequiresCapture PaymentStatus = "requires_capture" )
Payment status values.
func (PaymentStatus) String ¶
func (s PaymentStatus) String() string
String returns the string representation.
type Provider ¶
type Provider interface {
// Name returns the provider name.
Name() string
// CreatePayment creates a new payment.
CreatePayment(ctx context.Context, req *PaymentRequest) (*Payment, error)
// GetPayment retrieves a payment by ID.
GetPayment(ctx context.Context, paymentID string) (*Payment, error)
// CapturePayment captures an authorized payment.
CapturePayment(ctx context.Context, paymentID string, amount *Amount) (*Payment, error)
// CancelPayment cancels an authorized payment.
CancelPayment(ctx context.Context, paymentID string) (*Payment, error)
// Refund creates a refund for a payment.
Refund(ctx context.Context, req *RefundRequest) (*Refund, error)
// GetRefund retrieves a refund by ID.
GetRefund(ctx context.Context, refundID string) (*Refund, error)
}
Provider represents a payment provider.
type Refund ¶
type Refund struct {
// ID is the refund ID.
ID string
// PaymentID is the refunded payment ID.
PaymentID string
// Amount is the refund amount.
Amount *Amount
// Status is the refund status.
Status RefundStatus
// Reason is the refund reason.
Reason RefundReason
// FailureReason is the failure reason if failed.
FailureReason string
// Metadata holds additional data.
Metadata map[string]string
// CreatedAt is the creation timestamp.
CreatedAt time.Time
// Provider is the provider name.
Provider string
// Raw contains the raw provider response.
Raw map[string]any
}
Refund represents a refund.
func (*Refund) IsSuccessful ¶
IsSuccessful returns true if the refund was successful.
type RefundReason ¶
type RefundReason string
RefundReason represents the reason for a refund.
const ( RefundReasonDuplicate RefundReason = "duplicate" RefundReasonFraudulent RefundReason = "fraudulent" RefundReasonRequestedByCustomer RefundReason = "requested_by_customer" RefundReasonOther RefundReason = "other" )
Refund reason values.
func (RefundReason) String ¶
func (r RefundReason) String() string
String returns the string representation.
type RefundRequest ¶
type RefundRequest struct {
// PaymentID is the payment to refund.
PaymentID string
// Amount is the refund amount (nil for full refund).
Amount *Amount
// Reason is the refund reason.
Reason RefundReason
// Metadata holds additional data.
Metadata map[string]string
// IdempotencyKey for idempotent requests.
IdempotencyKey string
}
RefundRequest represents a refund request.
func NewRefundRequest ¶
func NewRefundRequest(paymentID string) *RefundRequest
NewRefundRequest creates a new refund request.
func (*RefundRequest) Validate ¶
func (r *RefundRequest) Validate() error
Validate validates the refund request.
func (*RefundRequest) WithAmount ¶
func (r *RefundRequest) WithAmount(amount *Amount) *RefundRequest
WithAmount sets the refund amount.
func (*RefundRequest) WithIdempotencyKey ¶
func (r *RefundRequest) WithIdempotencyKey(key string) *RefundRequest
WithIdempotencyKey sets the idempotency key.
func (*RefundRequest) WithMetadata ¶
func (r *RefundRequest) WithMetadata(key, value string) *RefundRequest
WithMetadata adds metadata.
func (*RefundRequest) WithReason ¶
func (r *RefundRequest) WithReason(reason RefundReason) *RefundRequest
WithReason sets the refund reason.
type RefundStatus ¶
type RefundStatus string
RefundStatus represents the status of a refund.
const ( RefundStatusPending RefundStatus = "pending" RefundStatusSucceeded RefundStatus = "succeeded" RefundStatusFailed RefundStatus = "failed" RefundStatusCanceled RefundStatus = "canceled" )
Refund status values.
func (RefundStatus) String ¶
func (s RefundStatus) String() string
String returns the string representation.
type SetupIntent ¶ added in v0.4.0
type SetupIntent struct {
// ID is the setup intent ID.
ID string
// Status is the setup intent status.
Status SetupIntentStatus
// CustomerID is the associated customer ID.
CustomerID string
// PaymentMethodID is the payment method being set up (set once collected).
PaymentMethodID string
// Usage indicates how the stored method will be charged later.
Usage SetupIntentUsage
// Description is the setup intent description.
Description string
// ClientSecret is the client secret used to confirm the intent from a
// frontend.
ClientSecret string
// RedirectURL is the URL for a 3DS / next-action redirect.
RedirectURL string
// FailureCode is the failure code if setup failed.
FailureCode string
// FailureMessage is the failure message if setup failed.
FailureMessage string
// Metadata holds additional data.
Metadata map[string]string
// CreatedAt is the creation timestamp.
CreatedAt time.Time
// Provider is the provider name.
Provider string
// Raw contains the raw provider response.
Raw map[string]any
}
SetupIntent represents the setup of a payment method for future off-session charges.
func (*SetupIntent) IsSucceeded ¶ added in v0.4.0
func (s *SetupIntent) IsSucceeded() bool
IsSucceeded returns true if the payment method was successfully set up.
func (*SetupIntent) RequiresAction ¶ added in v0.4.0
func (s *SetupIntent) RequiresAction() bool
RequiresAction returns true if the setup intent requires additional action (e.g. 3DS authentication).
type SetupIntentProvider ¶ added in v0.4.0
type SetupIntentProvider interface {
Provider
// CreateSetupIntent creates a setup intent. When the request carries a
// PaymentMethodID, the provider confirms it immediately (mirroring how
// CreatePayment confirms an inline payment method); otherwise the intent is
// returned awaiting client-side confirmation via its ClientSecret.
CreateSetupIntent(ctx context.Context, req *SetupIntentRequest) (*SetupIntent, error)
// GetSetupIntent retrieves a setup intent by ID.
GetSetupIntent(ctx context.Context, setupIntentID string) (*SetupIntent, error)
// CancelSetupIntent cancels a setup intent.
CancelSetupIntent(ctx context.Context, setupIntentID string) (*SetupIntent, error)
}
SetupIntentProvider extends Provider with the ability to set up (tokenize and store) a payment method for future off-session charges without moving money.
It is an optional interface: providers implement it only when their API supports a save-card-without-charging flow. The Client gates each method with a runtime type assertion and returns ErrUnsupported for providers that don't implement it. SetupIntents are the standard primitive underpinning subscriptions and one-click checkout, where a stored mandate is charged later.
type SetupIntentRequest ¶ added in v0.4.0
type SetupIntentRequest struct {
// CustomerID is the customer the payment method will be saved to. Optional,
// but required by most providers for the stored method to be reusable
// off-session.
CustomerID string
// PaymentMethodID is an existing payment method to attach and confirm
// immediately. Optional; when empty the intent awaits client-side
// confirmation via its ClientSecret.
PaymentMethodID string
// Usage indicates how the stored method will be charged later. Defaults to
// SetupIntentUsageOffSession.
Usage SetupIntentUsage
// Description is an optional description.
Description string
// ReturnURL is the URL to redirect to after authentication (for 3DS).
ReturnURL string
// Metadata holds additional data.
Metadata map[string]string
// IdempotencyKey for idempotent requests.
IdempotencyKey string
}
SetupIntentRequest represents a setup-intent creation request.
func NewSetupIntentRequest ¶ added in v0.4.0
func NewSetupIntentRequest() *SetupIntentRequest
NewSetupIntentRequest creates a new setup-intent request defaulting to off-session usage.
func (*SetupIntentRequest) Validate ¶ added in v0.4.0
func (r *SetupIntentRequest) Validate() error
Validate validates the setup-intent request.
func (*SetupIntentRequest) WithCustomer ¶ added in v0.4.0
func (r *SetupIntentRequest) WithCustomer(customerID string) *SetupIntentRequest
WithCustomer sets the customer ID.
func (*SetupIntentRequest) WithDescription ¶ added in v0.4.0
func (r *SetupIntentRequest) WithDescription(desc string) *SetupIntentRequest
WithDescription sets the description.
func (*SetupIntentRequest) WithIdempotencyKey ¶ added in v0.4.0
func (r *SetupIntentRequest) WithIdempotencyKey(key string) *SetupIntentRequest
WithIdempotencyKey sets the idempotency key.
func (*SetupIntentRequest) WithMetadata ¶ added in v0.4.0
func (r *SetupIntentRequest) WithMetadata(key, value string) *SetupIntentRequest
WithMetadata adds metadata.
func (*SetupIntentRequest) WithPaymentMethod ¶ added in v0.4.0
func (r *SetupIntentRequest) WithPaymentMethod(paymentMethodID string) *SetupIntentRequest
WithPaymentMethod sets the payment method ID to attach and confirm.
func (*SetupIntentRequest) WithReturnURL ¶ added in v0.4.0
func (r *SetupIntentRequest) WithReturnURL(url string) *SetupIntentRequest
WithReturnURL sets the return URL.
func (*SetupIntentRequest) WithUsage ¶ added in v0.4.0
func (r *SetupIntentRequest) WithUsage(usage SetupIntentUsage) *SetupIntentRequest
WithUsage sets the intended usage.
type SetupIntentStatus ¶ added in v0.4.0
type SetupIntentStatus string
SetupIntentStatus represents the status of a setup intent.
const ( SetupIntentStatusRequiresPaymentMethod SetupIntentStatus = "requires_payment_method" SetupIntentStatusRequiresConfirmation SetupIntentStatus = "requires_confirmation" SetupIntentStatusRequiresAction SetupIntentStatus = "requires_action" SetupIntentStatusProcessing SetupIntentStatus = "processing" SetupIntentStatusSucceeded SetupIntentStatus = "succeeded" SetupIntentStatusCanceled SetupIntentStatus = "canceled" )
Setup intent status values.
func (SetupIntentStatus) String ¶ added in v0.4.0
func (s SetupIntentStatus) String() string
String returns the string representation.
type SetupIntentUsage ¶ added in v0.4.0
type SetupIntentUsage string
SetupIntentUsage indicates how the stored payment method is intended to be charged later.
const ( // SetupIntentUsageOffSession sets up a payment method to be charged when the // customer is not present (e.g. recurring subscription billing). This is the // default. SetupIntentUsageOffSession SetupIntentUsage = "off_session" // SetupIntentUsageOnSession sets up a payment method to be charged while the // customer is present (e.g. one-click checkout). SetupIntentUsageOnSession SetupIntentUsage = "on_session" )
func (SetupIntentUsage) String ¶ added in v0.4.0
func (u SetupIntentUsage) String() string
String returns the string representation.
type WebhookEvent ¶
type WebhookEvent struct {
// ID is the event ID.
ID string
// Type is the raw provider event type, e.g. "payment_intent.succeeded".
Type string
// Provider is the provider name.
Provider string
// Raw contains the raw event payload.
Raw []byte
// Kind is the provider-normalized event category; WebhookUnknown for
// events that don't map to a normalized category.
Kind WebhookEventKind
// PaymentID is the provider payment identifier, when the event concerns a
// payment; empty otherwise.
PaymentID string
// OrderID is the provider order identifier, when present; empty otherwise.
OrderID string
// RefundID is the provider refund identifier, when the event concerns a
// refund; empty otherwise.
RefundID string
// SetupIntentID is the provider setup-intent identifier, when the event
// concerns a payment-method setup; empty otherwise.
SetupIntentID string
// Amount is the normalized amount in minor units; nil when the event
// carries no amount or the amount could not be parsed.
Amount *Amount
}
WebhookEvent represents a parsed webhook event.
In addition to the raw fields (Type, Raw), it carries provider-normalized fields (Kind, PaymentID, OrderID, RefundID, Amount) so callers can act on an event without hand-parsing the provider-specific Raw payload. Normalized fields are zero-valued ("" or nil) when they don't apply to the event.
type WebhookEventKind ¶ added in v0.2.0
type WebhookEventKind string
WebhookEventKind is a provider-normalized webhook event category. It lets callers switch on a unified set of event meanings regardless of provider, instead of parsing each provider's raw event-type string.
const ( WebhookUnknown WebhookEventKind = "" // unmapped/unsupported event WebhookPaymentCreated WebhookEventKind = "payment.created" // a payment was created/initiated WebhookPaymentSucceeded WebhookEventKind = "payment.succeeded" // payment captured/paid/completed WebhookPaymentFailed WebhookEventKind = "payment.failed" // payment attempt failed/denied WebhookPaymentCanceled WebhookEventKind = "payment.canceled" // payment canceled/voided WebhookRefundSucceeded WebhookEventKind = "refund.succeeded" // refund completed WebhookRefundFailed WebhookEventKind = "refund.failed" // refund failed WebhookSetupSucceeded WebhookEventKind = "setup.succeeded" // payment method setup completed WebhookSetupFailed WebhookEventKind = "setup.failed" // payment method setup failed )
Webhook event kinds. WebhookUnknown is used for events that don't map to a normalized category; callers can still inspect WebhookEvent.Type and Raw.
func (WebhookEventKind) String ¶ added in v0.2.0
func (k WebhookEventKind) String() string
String returns the string representation.
type WebhookProvider ¶
type WebhookProvider interface {
// VerifyWebhook verifies and parses a webhook event.
// The headers map should contain the relevant signature headers from the HTTP request.
VerifyWebhook(ctx context.Context, payload []byte, headers map[string]string) (*WebhookEvent, error)
}
WebhookProvider extends Provider with webhook verification.