stripe

package
v0.0.0-...-963cf5d Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Package stripe is the Stripe payment module (see CWUP/tasks/courses.md): hosted Stripe Checkout, webhook verification and a registry through which other modules (courses, shop) learn that a payment went through.

No SDK: Stripe's API takes form-encoded requests and answers JSON. JSON is only the external wire protocol here; everything ForgeCMS stores is SML. The secret keys live in <data>/<domain>/stripe.sml on the server, never in app.sml (which is in a public Git repo).

Index

Constants

View Source
const (
	MetaPurpose = "forgecms_purpose"
	MetaRef     = "forgecms_ref"
)

Metadata keys set on every session: which module and which of its records the payment belongs to.

View Source
const (
	ModeTest = "test"
	ModeLive = "live"
)

Modes.

View Source
const DefaultAPI = "https://api.stripe.com"

DefaultAPI is Stripe's API base URL.

View Source
const WebhookTolerance = 5 * time.Minute

WebhookTolerance is how old a signed webhook may be.

Variables

View Source
var ErrNotConfigured = errors.New("stripe: no secret key for the active mode")

ErrNotConfigured is returned when the active mode has no secret key.

View Source
var ErrSignature = errors.New("stripe: invalid webhook signature")

ErrSignature is returned for webhooks that are not signed by Stripe.

Functions

func FormatSettings

func FormatSettings(s Settings) (string, error)

FormatSettings writes s as stripe.sml.

func Mask

func Mask(key string) string

Mask shows only the start and end of a key.

func SessionLive

func SessionLive(id string) bool

SessionLive reports whether a session ID belongs to live mode.

func Sign

func Sign(payload []byte, secret string, t time.Time) string

Sign builds a Stripe-Signature header; used by tests.

func VerifySignature

func VerifySignature(payload []byte, header string, secrets []string, tolerance time.Duration, now time.Time) error

VerifySignature checks a Stripe-Signature header ("t=…,v1=…,v1=…") against any of secrets.

Types

type APIError

type APIError struct {
	Status  int
	Type    string `json:"type"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

APIError is an error answer of Stripe.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	BaseURL string // DefaultAPI; tests point it at a fake server
	HTTP    *http.Client
}

Client talks to the Stripe API.

func NewClient

func NewClient() *Client

NewClient returns a client for the real API.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, key, idempotencyKey string, p SessionParams) (*Session, error)

CreateSession creates a Checkout Session. idempotencyKey makes a retry of the same purchase return the same session.

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, key, id string) (*Session, error)

GetSession retrieves a Checkout Session.

type Event

type Event struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Livemode bool   `json:"livemode"`
	Data     struct {
		Object json.RawMessage `json:"object"`
	} `json:"data"`
}

Event is a webhook event.

type Keys

type Keys struct {
	SecretKey     string // sk_test_… / sk_live_… or a restricted rk_… key
	WebhookSecret string // whsec_…
}

Keys are the credentials of one mode.

type LineItem

type LineItem struct {
	Name     string
	Amount   int64 // cents
	Quantity int
}

LineItem is one position of a checkout.

type Receiver

type Receiver interface {
	// Paid is called when the session's money arrived.
	Paid(ref string, s *Session) error
	// Failed is called when a delayed payment (SEPA) failed.
	Failed(ref string, s *Session) error
	// Refunded is called when the payment was refunded in full.
	Refunded(ref string, paymentIntent string, live bool) error
}

Receiver is a module that sells through Stripe. All calls must be idempotent: the same payment may arrive via the success page and the webhook, and Stripe retries webhooks.

type Service

type Service struct {
	Client   *Client
	Settings *SettingsFile
	Methods  []string // payment_method_types; empty = dashboard settings
	Now      func() time.Time
	// contains filtered or unexported fields
}

Service is the per-site Stripe module.

func NewService

func NewService(settings *SettingsFile, methods []string) *Service

NewService prepares the module with the keys in settings.

func (*Service) Checkout

func (s *Service) Checkout(ctx context.Context, purpose, ref string, p SessionParams) (*Session, error)

Checkout creates a session in the active mode for a record ref of the module purpose and returns it (redirect the buyer to its URL).

func (*Service) Confirm

func (s *Service) Confirm(ctx context.Context, id string) (*Session, error)

Confirm retrieves session id (from the success page) and, when it is paid, tells its module. It returns the session.

func (*Service) HandleWebhook

func (s *Service) HandleWebhook(payload []byte, sigHeader string) error

HandleWebhook verifies and processes one webhook delivery. An error makes the HTTP handler answer 4xx/5xx, so Stripe retries later.

func (*Service) Mode

func (s *Service) Mode() string

Mode returns the active mode ("test" / "live").

func (*Service) Ready

func (s *Service) Ready() bool

Ready reports whether the active mode has a secret key.

func (*Service) Register

func (s *Service) Register(purpose string, r Receiver)

Register makes r receive the payments created with purpose.

type Session

type Session struct {
	ID            string            `json:"id"`
	URL           string            `json:"url"`
	Status        string            `json:"status"`         // open, complete, expired
	PaymentStatus string            `json:"payment_status"` // paid, unpaid, no_payment_required
	Reference     string            `json:"client_reference_id"`
	Metadata      map[string]string `json:"metadata"`
	AmountTotal   int64             `json:"amount_total"`
	Currency      string            `json:"currency"`
	Livemode      bool              `json:"livemode"`
	PaymentIntent string            `json:"-"`
	Email         string            `json:"-"`

	RawPaymentIntent json.RawMessage `json:"payment_intent"`
	CustomerDetails  *struct {
		Email string `json:"email"`
	} `json:"customer_details"`
}

Session is the part of a Checkout Session ForgeCMS uses.

func (*Session) Paid

func (s *Session) Paid() bool

Paid reports whether the money is there (card at once, SEPA later).

type SessionParams

type SessionParams struct {
	Currency      string // "eur"
	Items         []LineItem
	CustomerEmail string
	Reference     string // client_reference_id: the module's order/purchase ID
	Metadata      map[string]string
	SuccessURL    string // may contain {CHECKOUT_SESSION_ID}
	CancelURL     string
	Locale        string   // "de", "en", … or "" = auto
	Methods       []string // payment_method_types; empty = dashboard settings
	ExpiresAfter  time.Duration
}

SessionParams describes a Checkout Session to create.

type Settings

type Settings struct {
	Mode string // ModeTest or ModeLive
	Test Keys
	Live Keys
}

Settings is the content of stripe.sml.

func ParseSettings

func ParseSettings(source string) (Settings, error)

ParseSettings reads stripe.sml.

func (Settings) Active

func (s Settings) Active() Keys

Active returns the keys of the current mode.

func (Settings) KeysFor

func (s Settings) KeysFor(live bool) Keys

KeysFor returns the keys of mode.

type SettingsFile

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

SettingsFile is stripe.sml; it is re-read when it changes on disk, so keys and mode can be edited without a restart.

func OpenSettings

func OpenSettings(path string) (*SettingsFile, error)

OpenSettings opens (and creates from a template, mode 0600) stripe.sml.

func (*SettingsFile) Get

func (f *SettingsFile) Get() (Settings, error)

Get returns the current settings, re-reading the file when it changed.

func (*SettingsFile) Path

func (f *SettingsFile) Path() string

Path is the file's location.

func (*SettingsFile) SetMode

func (f *SettingsFile) SetMode(mode string) error

SetMode switches between test and live and writes the file.

Jump to

Keyboard shortcuts

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