payments

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: AGPL-3.0 Imports: 5 Imported by: 0

README

Payments

A Go library for handling payment processing, currently with Stripe integration, developed for the International Combat Archery Alliance.

Features

  • Generic Payment Interface: Extensible design allowing for multiple payment providers
  • Stripe Integration: Complete implementation for Stripe checkout sessions and webhook verification
  • Type-Safe Money Handling: Uses go-money library for precise currency handling
  • Webhook Validation: Secure webhook signature verification
  • Comprehensive Error Handling: Structured error types with detailed context

Installation

go get github.com/International-Combat-Archery-Alliance/payments

Usage

Basic Setup
import (
    "github.com/International-Combat-Archery-Alliance/payments"
    "github.com/International-Combat-Archery-Alliance/payments/stripe"
    "github.com/Rhymond/go-money"
)

// Initialize Stripe client
client := stripe.NewClient("sk_test_...", "whsec_...")
Creating a Checkout Session
params := payments.CheckoutParams{
    ReturnURL: "https://yoursite.com/success",
    Items: []payments.Item{
        {
            Name:  "Tournament Registration",
            Price: money.New(2500, money.USD), // $25.00
        },
    },
    Metadata: map[string]string{
        "user_id": "12345",
        "event_id": "tournament_2024",
    },
    AllowAdaptivePricing: true,
}

checkoutInfo, err := client.CreateCheckout(ctx, params)
if err != nil {
    // Handle error
}

// Use checkoutInfo.ClientSecret for frontend integration
Handling Webhooks
func handleWebhook(w http.ResponseWriter, r *http.Request) {
    payload, _ := ioutil.ReadAll(r.Body)
    signature := r.Header.Get("Stripe-Signature")
    
    metadata, err := client.ConfirmCheckout(ctx, payload, signature)
    if err != nil {
        // Handle webhook verification error
        return
    }
    
    // Process successful payment using metadata
}

Error Handling

The library provides structured error types with specific reasons:

  • ErrorReasonSignatureValidation: Webhook signature validation failed
  • ErrorReasonFailedToCreateCheckoutSession: Checkout session creation failed
  • ErrorReasonInvalidWebhookEventData: Invalid webhook event data
  • ErrorReasonNotCheckoutConfirmedEvent: Event is not a checkout completion
  • ErrorReasonNotPaid: Payment status is not paid

Dependencies

License

Licensed under the terms specified in the LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Address added in v0.6.0

type Address struct {
	City       string
	Country    string
	Line1      string
	Line2      string
	PostalCode string
	State      string
}

type BillingDetails added in v0.6.0

type BillingDetails struct {
	Name    string
	Email   string
	Phone   string
	Address *Address
}

type ChargeListPaginatedParams added in v0.7.0

type ChargeListPaginatedParams struct {
	CreatedAfter   *time.Time
	CreatedBefore  *time.Time
	Status         string
	MetadataFilter map[string]string
	Limit          int    // max items per page. Defaults to 10 if not set.
	Cursor         string // ID of last item from previous page (empty for first page)
}

type ChargeListParams added in v0.6.0

type ChargeListParams struct {
	CreatedAfter   *time.Time
	CreatedBefore  *time.Time
	Status         string
	MetadataFilter map[string]string
}

type ChargesPage added in v0.7.0

type ChargesPage struct {
	Payments   []Payment
	HasMore    bool
	NextCursor string // ID to use for next page request (empty if HasMore=false)
}

type CheckoutInfo

type CheckoutInfo struct {
	ClientSecret string
	SessionId    string
}

type CheckoutManager

type CheckoutManager interface {
	CreateCheckout(ctx context.Context, params CheckoutParams) (CheckoutInfo, error)
	// Confirms that a checkout was sucessful based on event data.
	//
	// Note that this can still return metadata even if err != nil, in the event that the
	// checkout was expired, since the caller may still want to know checkout information.
	ConfirmCheckout(ctx context.Context, payload []byte, signature string) (map[string]string, error)
}

type CheckoutParams

type CheckoutParams struct {
	ReturnURL string
	Items     []Item
	Metadata  map[string]string
	// How long to keep the checkout session alive.
	// Check payment operator for allowed values.
	SessionAliveDuration *time.Duration
	// If the payment processor has an adaptive pricing feature (i.e. auto converting currencies),
	// enable or disable it.
	AllowAdaptivePricing bool
	CustomerEmail        *string
	// Email address where the payment provider should send the payment receipt.
	ReceiptEmail *string
}

type Error

type Error struct {
	Message string
	Reason  Reason
	Cause   error
}

func NewCheckoutExpiredError added in v0.3.0

func NewCheckoutExpiredError(message string) *Error

func NewFailedToCreateCheckoutSessionError

func NewFailedToCreateCheckoutSessionError(message string, cause error) *Error

func NewInvalidWebhookEventDataError

func NewInvalidWebhookEventDataError(message string, cause error) *Error

func NewNotCheckoutConfirmedEventError

func NewNotCheckoutConfirmedEventError(message string) *Error

func NewNotPaidError

func NewNotPaidError(message string) *Error

func NewSignatureValidationError

func NewSignatureValidationError(message string, cause error) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Item

type Item struct {
	Name     string
	Price    *money.Money
	Quantity int
}

type Payment added in v0.6.0

type Payment struct {
	ID                string
	Amount            *money.Money
	Created           time.Time
	Status            string
	Metadata          map[string]string
	Description       string
	BillingDetails    *BillingDetails
	CheckoutSessionID string
}

type PaymentQuerier added in v0.6.0

type PaymentQuerier interface {
	ListCharges(ctx context.Context, params ChargeListParams) iter.Seq2[Payment, error]
	ListChargesPaginated(ctx context.Context, params ChargeListPaginatedParams) (ChargesPage, error)
}

type Reason

type Reason string
const (
	ErrorReasonSignatureValidation           Reason = "SignatureValidationError"
	ErrorReasonFailedToCreateCheckoutSession Reason = "FailedToCreateCheckoutSession"
	ErrorReasonInvalidWebhookEventData       Reason = "InvalidWebhookEventData"
	ErrorReasonCheckoutExpired               Reason = "CheckoutExpired"
	ErrorReasonNotCheckoutConfirmedEvent     Reason = "NotCheckoutConfirmedEvent"
	ErrorReasonNotPaid                       Reason = "PaymentStatusIsNotPaid"
)

Directories

Path Synopsis
Example program demonstrating how to use the payments library to query and aggregate charges.
Example program demonstrating how to use the payments library to query and aggregate charges.

Jump to

Keyboard shortcuts

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