momobase

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 12 Imported by: 0

README

Momobase

Go tests Go Reference Release

Momobase is an embeddable Go package for accepting, routing, and reconciling payments through provider adapters.

Install

go get github.com/momobasehq/momobase@latest

Start an instance

package main

import (
	"log"

	"github.com/momobasehq/momobase"
	"github.com/momobasehq/momobase/providers/dummy"
)

func main() {
	instance, err := momobase.New(
		momobase.WithProvider("dummy", dummy.New),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer instance.Close()

	log.Fatal(instance.Run())
}

At least one provider is required; the included dummy provider is deterministic and moves no money.

Configure it

Momobase reads no environment variables and no configuration files. DefaultConfig() returns a development baseline you copy and edit, and WithConfig passes it back:

cfg := momobase.DefaultConfig()
cfg.App.Env = "production"
cfg.App.PublicURL = "https://payments.example.com"
cfg.App.CORSAllowedOrigins = []string{"https://checkout.example.com"}
cfg.DB = momobase.DatabaseConfig{
	Type:     "postgres",
	Host:     "database.internal",
	Port:     "5432",
	User:     "momobase",
	Password: os.Getenv("DB_PASSWORD"),
	Name:     "momobase",
	SSLMode:  "require",
}
cfg.Security.EncryptionMasterKeyBase64 = os.Getenv("ENCRYPTION_MASTER_KEY_BASE64")
cfg.Security.AdminOAuthSecret = os.Getenv("ADMIN_OAUTH_SECRET")
cfg.Security.AppOAuthSecret = os.Getenv("APP_OAUTH_SECRET")

instance, err := momobase.New(
	momobase.WithConfig(cfg),
	momobase.WithProvider("dummy", dummy.New),
)

Where a value comes from is your application's decision: read the environment, a file, or a secret manager and assign the fields. The defaults carry placeholder credentials that startup rejects once App.Env is staging or production.

The API answers on /api/v1, /api/admin, and /webhooks, so / is yours. App.PublicDir — mb_public by default — is a directory of static files served there; a missing one leaves / unrouted, and instance.PublicDir() reports which directory, if any, is being served.

Mint the three real ones with openssl rand:

$ openssl rand -base64 32      # EncryptionMasterKeyBase64, must decode to exactly 32 bytes
hV3pR8mK2xQ7wN5tZ0cJ9bY4sL6dA1fG8eU3iO7nX2M=

$ openssl rand -hex 32         # AdminOAuthSecret
a4e91c7d5b28f036e1a7c94d0b562f83e7d15a9c3f804b6e29d7a1c58f036b4e

$ openssl rand -hex 32         # AppOAuthSecret
5d38b0e7a91c4f26d85b30a7e12f9c64b038d75a1e9f43c806b2d517a9e04f3c

Also available: WithConfigFunc for ordered overrides, WithAddr for the listen address alone, WithLogger for a slog.Logger, and WithProvider or WithProviders for adapters.

Public interface

  • DefaultConfig() returns the development configuration baseline to copy and edit.
  • New(...Option) constructs the database, HTTP API, provider runtime, workers, and hooks.
  • Serve(ctx) runs until cancellation; Run() adds interrupt and termination signal handling.
  • Close() stops workers and closes owned resources. Call it for every successful New.
  • App() exposes the Fiber application for tests, mounting, or extra routes.
  • DB() and Logger() expose the instance-owned GORM database and structured logger.
  • Migrate(ctx) applies schema migrations when your host controls migration timing.
  • SeedAdmin(ctx, email, password, name) creates the first administrator.
  • OnPaymentRequest() and OnTransactionChanged() expose typed lifecycle hooks.

Provider contracts and helpers live in providers, the safe reference adapter lives in providers/dummy, and typed lifecycle events live in hooks.

See the documentation and API reference.

Development

make quality
make coverage

Releases are ordinary semantic-version Go module tags. A release tag publishes the module, GitHub release, and release OpenAPI files.

License

MIT

Documentation

Overview

Package momobase embeds the Momobase payment orchestration server in a Go application and extends it with custom payment providers.

New constructs an instance from configuration and the registered providers, and Run or Serve starts its HTTP server and background workers:

instance, err := momobase.New(
	momobase.WithProvider("acme_pay", acme.New),
)
if err != nil {
	log.Fatal(err)
}
defer instance.Close()
log.Fatal(instance.Run())

Momobase reads no environment variables and no configuration files. New uses DefaultConfig — a development baseline of plain values — unless a host supplies its own through WithConfig. Copy the default, change what differs, and pass it:

cfg := momobase.DefaultConfig()
cfg.App.Env = "production"
cfg.App.PublicURL = "https://payments.example.com"
cfg.DB = momobase.DatabaseConfig{Type: "postgres", Host: "db.internal", ...}

instance, err := momobase.New(
	momobase.WithConfig(cfg),
	momobase.WithProvider("acme_pay", acme.New),
)

A host that configures from the environment, a file, or a secret manager reads it itself and assigns the fields, so the source of a value is the host's choice rather than this package's. [Config.Validate] rejects the default credentials and other unsafe settings when App.Env is staging or production.

The API is served from /api/v1, /api/admin, and /webhooks, which leaves / to the host. App.PublicDir names a directory of static files to serve there — a landing page, documentation, a checkout — and defaults to mb_public; a directory that is not there is not an error, it just leaves / unrouted for the host to answer.

Provider contracts and helpers live in the providers package. Register a providers.PaymentProvider factory under a provider code with WithProvider. Accounts for that code are then created, configured, and activated through the Admin API.

Momobase registers no providers on its own: a build carries exactly the providers it asks for, and New reports an error when none are registered. providers/dummy is the included reference adapter and moves no money.

@title Momobase API @version 1.0 @description Embeddable payment orchestration API for application payments and administrative operations. @BasePath / @schemes http https @securityDefinitions.apikey BearerAuth @in header @name Authorization @description Enter a bearer token using the format: Bearer {token}

Index

Constants

View Source
const (
	// DefaultEncryptionMasterKeyBase64 is the all-zero development AES key.
	DefaultEncryptionMasterKeyBase64 = bootstrap.DefaultEncryptionMasterKeyBase64
	// DefaultAdminOAuthSecret is the development administrator token secret.
	DefaultAdminOAuthSecret = bootstrap.DefaultAdminOAuthSecret
	// DefaultAppOAuthSecret is the development application token secret.
	DefaultAppOAuthSecret = bootstrap.DefaultAppOAuthSecret
)

The placeholder credentials DefaultConfig carries, exported so that a host can assert it replaced them. Config.Validate rejects all three when App.Env is staging or production.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppConfig

type AppConfig = bootstrap.AppConfig

AppConfig contains process-level application settings.

type Config

type Config = bootstrap.Config

Config contains all application configuration groups.

func DefaultConfig added in v0.2.0

func DefaultConfig() Config

DefaultConfig returns Momobase's own configuration: a development baseline of plain values that a host copies and edits. New uses it when no configuration is supplied through WithConfig.

Momobase reads no environment variables. A host that configures from the environment, a file, or a secret manager reads it itself and assigns the fields:

cfg := momobase.DefaultConfig()
cfg.App.Env = "production"
cfg.App.Addr = os.Getenv("PORT")
cfg.Security.AdminOAuthSecret = os.Getenv("ADMIN_OAUTH_SECRET")

The placeholder credentials in the returned configuration are rejected by Config.Validate when App.Env is staging or production.

type DatabaseConfig

type DatabaseConfig = bootstrap.DatabaseConfig

DatabaseConfig contains settings shared by the supported database drivers.

type FeaturesConfig

type FeaturesConfig = bootstrap.FeaturesConfig

FeaturesConfig controls optional application behavior.

type Instance

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

Instance is a configured Momobase server and the runtime dependencies it owns.

func New

func New(opts ...Option) (*Instance, error)

New builds an instance from the supplied options, opening the database and preparing the HTTP server, providers, and background workers. Configuration is DefaultConfig unless WithConfig is supplied. The caller owns the returned instance and must Close it to release its connections.

func (*Instance) Addr

func (i *Instance) Addr() string

Addr returns the address the HTTP server listens on. A configured port of 0 reads back as the port the kernel chose once Serve has bound the listener.

func (*Instance) App

func (i *Instance) App() *fiber.App

App returns the Fiber application, which may be mounted in an existing Fiber app, exercised with App().Test, or extended with additional routes instead of calling Serve or Run.

Momobase runs on fasthttp rather than net/http, so this is a *fiber.App and not an http.Handler; an application serving Momobase alongside net/http routes has to adapt at its own boundary.

func (*Instance) Close

func (i *Instance) Close() error

Close stops an active server and its workers before closing the database connection pool. It is safe to call Close more than once.

func (*Instance) DB

func (i *Instance) DB() *gorm.DB

DB returns the instance's database handle.

func (*Instance) Logger

func (i *Instance) Logger() *slog.Logger

Logger returns the instance's structured logger.

func (*Instance) Migrate

func (i *Instance) Migrate(ctx context.Context) error

Migrate applies pending schema migrations and converges the schema with the current models. It runs automatically during New unless the AutoMigrate feature is disabled, and is safe to call more than once.

func (*Instance) OnPaymentRequest

func (i *Instance) OnPaymentRequest() *hooks.Hook[hooks.PaymentRequestEvent]

OnPaymentRequest returns the blocking hook invoked for each normalized new payment request before routing and persistence. Idempotent replays skip it.

func (*Instance) OnTransactionChanged

func (i *Instance) OnTransactionChanged() *hooks.Hook[hooks.TransactionChangedEvent]

OnTransactionChanged returns the post-commit hook invoked when a transaction status is persisted from the request, webhook, or reconciliation path.

func (*Instance) PublicDir added in v0.4.0

func (i *Instance) PublicDir() string

PublicDir returns the directory of static files being served at /, or an empty string when none is. A configured directory that does not exist reads back empty, so this is what the instance serves rather than what it was asked to serve.

func (*Instance) Run

func (i *Instance) Run() error

Run serves the instance until the process receives an interrupt or termination signal, then shuts it down gracefully.

func (*Instance) SeedAdmin

func (i *Instance) SeedAdmin(ctx context.Context, email, password, name string) error

SeedAdmin creates a super administrator with the supplied credentials.

func (*Instance) Serve

func (i *Instance) Serve(ctx context.Context) error

Serve starts the provider runtimes, background workers, and HTTP server, and blocks until ctx is cancelled or the server stops. Shutting down because ctx was cancelled is not reported as an error. An instance may only be served once.

type LogConfig

type LogConfig = bootstrap.LogConfig

LogConfig contains structured logging settings.

type Option

type Option func(*options)

Option customizes the instance constructed by New.

func WithAddr

func WithAddr(addr string) Option

WithAddr overrides the address the HTTP server listens on, such as ":9090".

func WithConfig

func WithConfig(cfg Config) Option

WithConfig uses cfg instead of DefaultConfig.

func WithConfigFunc

func WithConfigFunc(fn func(*Config)) Option

WithConfigFunc applies fn to the resolved configuration before the instance is built. Functions run in the order supplied, after any WithConfig value.

func WithLogger

func WithLogger(log *slog.Logger) Option

WithLogger uses log instead of a logger derived from the configured log level.

func WithProvider

func WithProvider(code string, factory providers.Factory) Option

WithProvider registers a payment provider under code, replacing any provider previously registered under the same code. The code is the value operators select when creating a provider account through the Admin API.

Momobase registers no providers of its own, so at least one is required. The reference adapter in providers/dummy is registered the same way as any other:

momobase.New(momobase.WithProvider("acme_pay", acme.New))

func WithProviders

func WithProviders(factories map[string]providers.Factory) Option

WithProviders registers each payment provider in factories by its code.

type SecurityConfig

type SecurityConfig = bootstrap.SecurityConfig

SecurityConfig contains encryption, token, and application credential settings.

type WorkersConfig

type WorkersConfig = bootstrap.WorkersConfig

WorkersConfig controls background task activation and scheduling.

Directories

Path Synopsis
_examples
customprovider command
Package main runs a Momobase server extended with a custom payment provider.
Package main runs a Momobase server extended with a custom payment provider.
extension
Package extension demonstrates a compiled, app-scoped Momobase extension.
Package extension demonstrates a compiled, app-scoped Momobase extension.
Package hooks provides typed extension points for Momobase lifecycle events.
Package hooks provides typed extension points for Momobase lifecycle events.
internal
bootstrap
Package bootstrap constructs the application runtime from configuration and manages its database, HTTP server, workers, and lifecycle.
Package bootstrap constructs the application runtime from configuration and manages its database, HTTP server, workers, and lifecycle.
domain
Package domain defines the persistent models and shared state constants used throughout Momobase.
Package domain defines the persistent models and shared state constants used throughout Momobase.
dto
Package dto holds the request payloads the HTTP API accepts, the rules each one must satisfy, and the normalization applied before those rules are checked.
Package dto holds the request payloads the HTTP API accepts, the rules each one must satisfy, and the normalization applied before those rules are checked.
http
Package httpx assembles the application's HTTP routes and middleware stack.
Package httpx assembles the application's HTTP routes and middleware stack.
http/admin
Package admin provides HTTP handlers for authenticated administrative APIs.
Package admin provides HTTP handlers for authenticated administrative APIs.
http/apidoc
Package apidoc contains schemas used only to describe the HTTP API.
Package apidoc contains schemas used only to describe the HTTP API.
http/middleware
Package middleware provides authentication, authorization, logging, and request-safety middleware for the HTTP API.
Package middleware provides authentication, authorization, logging, and request-safety middleware for the HTTP API.
http/public
Package public provides HTTP handlers for client-facing payment APIs.
Package public provides HTTP handlers for client-facing payment APIs.
http/webhooks
Package webhooks provides HTTP handlers for incoming provider webhooks.
Package webhooks provides HTTP handlers for incoming provider webhooks.
migrations
Package migrations applies ordered schema changes that GORM's AutoMigrate cannot express.
Package migrations applies ordered schema changes that GORM's AutoMigrate cannot express.
platform
Package platform provides shared HTTP, cryptographic, token, and identifier helpers for the application.
Package platform provides shared HTTP, cryptographic, token, and identifier helpers for the application.
repository
Package repository is the only place in Momobase that reaches the database.
Package repository is the only place in Momobase that reaches the database.
service/audit
Package audit records security- and administration-relevant actions.
Package audit records security- and administration-relevant actions.
service/identity
Package services implements Momobase's application-level business workflows.
Package services implements Momobase's application-level business workflows.
service/payment
Package payment turns a validated request into a recorded transaction.
Package payment turns a validated request into a recorded transaction.
service/provider
Package provider owns the lifecycle of the payment adapters a deployment runs.
Package provider owns the lifecycle of the payment adapters a deployment runs.
service/reconciliation
Package reconciliation settles transactions the request path left unresolved.
Package reconciliation settles transactions the request path left unresolved.
service/routing
Package routing decides which provider account executes a payment.
Package routing decides which provider account executes a payment.
service/webhook
Package webhook applies provider callbacks to the transactions they describe.
Package webhook applies provider callbacks to the transactions they describe.
testsupport
Package testsupport builds a fully wired service stack backed by a throwaway in-memory database, so a test can exercise a real payment path instead of a mock.
Package testsupport builds a fully wired service stack backed by a throwaway in-memory database, so a test can exercise a real payment path instead of a mock.
utils
Package utils holds small, dependency-free helpers shared across Momobase's packages, including the provider adapters.
Package utils holds small, dependency-free helpers shared across Momobase's packages, including the provider adapters.
workers
Package workers runs named background tasks on configurable intervals and coordinates their shutdown.
Package workers runs named background tasks on configurable intervals and coordinates their shutdown.
Package providers defines payment-provider contracts and shared utilities for configuring providers, issuing requests, and normalizing provider responses.
Package providers defines payment-provider contracts and shared utilities for configuring providers, issuing requests, and normalizing provider responses.
dummy
Package dummy provides a payment provider that simulates payments entirely in memory.
Package dummy provides a payment provider that simulates payments entirely in memory.

Jump to

Keyboard shortcuts

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