commerce

package module
v1.41.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 34 Imported by: 0

README

Hanzo Build status

Hanzo is a scalable DX platform designed to power next-gen internet companies.

Development

Getting started

You can use make to setup your development enviroment. Running:

$ make deps

...will download the Go App Engine SDK and unzip it into sdk/. When hacking on things you'll want to ensure $GOROOT and $GOPATH point to their respective directories inside sdk/.

You can source the provided .env file to set these variables, or use autoenv to set them automatically whenever you cd into the project directory.

Installing Go tools

You can install the common Go command line tools and configure gocode to work with App Engine by running:

$ make tools
Development server

You can then use make serve to run the local development server and make test to run tests.

You can create a local config.json file containing configuration variables to customize settings locally (for instance to disable the auto fixture loading).

This Makefile is used to build, test, and deploy a Go application running on Google App Engine, with dependencies managed through a combination of Go tools, Python SDK scripts, and Node.js for asset compilation. Here's a detailed breakdown of how it works and the general flow of operations:

Key Concepts
  • Google App Engine: This is the platform used for deploying and managing the application.
  • Go SDK and App Engine SDK: Go is the language used, and the App Engine SDK is required for running the app locally and deploying it to the cloud.
  • Node.js Assets: JavaScript and CSS assets are handled using tools like requisite, uglifyjs, and stylus.
  • Staging and Production Environments: Different configurations are used for deploying to development, staging, and production environments.
How the Makefile Works
1. System Variables
  • os: Detects the operating system (linux or darwin) and converts it to lowercase for uniformity.
  • pwd: Stores the current directory path.
  • platform: Constructs the platform string based on the OS and architecture.
  • sdk: Defines the specific App Engine SDK version to be used.
  • sdk_path, goroot, gopath: Defines paths where the Go SDK and Go environment will be installed.
2. SDK Installation

The SDK is downloaded if it doesn’t exist. The following steps are performed:

  • .sdk target: Downloads the App Engine SDK as a zip file and unzips it into a .sdk folder.

    • It also performs extra setup (e.g., downloading mtime_file_watcher.py to monitor file changes).
  • .sdk/go: Creates a wrapper script to use the goapp command from the SDK.

  • .sdk/gpm: Downloads gpm, a Go dependency manager, to the .sdk directory.

3. Dependency Management
  • deps target: Ensures all Go and JS/CSS dependencies are installed.
    • deps-assets: Runs npm update to update JS/CSS dependencies.
    • deps-go: Installs Go dependencies using gpm from the Godeps file.
4. Environment Configuration
  • The gae_development, gae_staging, gae_production, and gae_sandbox variables hold different configurations (YAML files) for deploying the app to various environments.

  • project_env, project_id, gae_config: Select the appropriate environment based on Makefile options (production, sandbox, etc.).

5. Building the Project
  • build target: Builds the Go modules listed under modules using goapp from the App Engine SDK.

  • install target: Installs the Go application and all dependencies.

6. Asset Compilation
  • JavaScript: Files are compiled and minified using requisite, coffee, and uglifyjs.

    • compile-js: Compiles CoffeeScript files and aggregates JavaScript with requisite.
    • compile-js-min: Minifies the compiled JavaScript files.
  • CSS: Files are compiled and autoprefixed using stylus and autoprefixer.

    • compile-css: Compiles Stylus files into CSS.
    • compile-css-min: Minifies CSS and applies prefixes for cross-browser compatibility.
7. Testing and Linting
  • test target: Runs unit tests using ginkgo, with options for verbose and focused tests.

  • bench target: Runs benchmark tests.

  • test-watch: Watches the files and runs the tests on changes.

8. Running the Development Server
  • serve target: Starts the App Engine development server using the dev_appserver.py command from the SDK.
    • serve-clear-datastore: Clears the local datastore before starting the server.
    • serve-public: Starts the server with a public-facing IP (0.0.0.0).
9. Deployment
  • deploy target: Deploys the app to the selected environment (staging, production, etc.).

    • rollback target: Rolls back the deployment if needed.
  • deploy-app target: Updates the environment configuration and deploys each module using appcfg.py (App Engine deployment tool).

  • datastore-export, datastore-import: Commands for exporting and importing Google Cloud Datastore data.

Local Setup Steps
  1. Download Dependencies: Run make deps to install all Go, JS, and CSS dependencies.
  2. Build the Project: Use make build to build the Go application.
  3. Run Development Server: Use make serve to start the local App Engine server.
Staging and Production Setup
  1. Staging: Run make deploy to deploy the app to the staging environment.

    • Make sure the environment variables are set to the correct staging project ID (project_id).
  2. Production: Set the production=1 flag when calling make deploy to deploy to the production environment.

  3. Rolling Back: Use make rollback to revert to a previous version if needed.

Tools

Various Go tools are included in the tools target to assist with development (linting, formatting, etc.). These tools are installed using the goapp get and goapp install commands.

Documentation

Overview

Package commerce provides the main application framework for Hanzo Commerce.

Commerce is a multi-tenant e-commerce platform that runs as a standalone binary with embedded SQLite for per-user/org data and optional analytics via ClickHouse.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                     Commerce App                            │
├─────────────────────────────────────────────────────────────┤
│  HTTP Server (Gin)  │  Hooks System  │  Background Tasks    │
├─────────────────────────────────────────────────────────────┤
│  User SQLite        │  Org SQLite    │  Analytics (CH)      │
│  + sqlite-vec       │  + sqlite-vec  │  (parallel queries)  │
└─────────────────────────────────────────────────────────────┘

Index

Constants

View Source
const Version = "1.38.0"

Version is the current version of Commerce

Variables

View Source
var (
	GitCommit = "dev"
	BuildTime = "unknown"
)

GitCommit and BuildTime are set via -ldflags at build time

Functions

This section is empty.

Types

type App

type App struct {

	// Root command
	RootCmd *cobra.Command

	// Database manager
	DB *db.Manager

	// Infrastructure manager
	Infra *infra.Manager

	// Hook system
	Hooks *hooks.Registry

	// Events client (sends to analytics-collector via HTTP)
	Events *events.Client

	// Publisher sends commerce events to NATS/JetStream
	Publisher *events.Publisher

	// KMS client for secret management
	KMS *kms.CachedClient

	// ZAP node for inter-service vector operations
	ZAP *infra.ZAPNode

	// HTTP router
	Router *gin.Engine

	// CheckoutResolver maps hostnames (pay.satschel.com, …) to Tenant
	// configs for the embedded checkout SPA. Mutable at runtime so the
	// admin can add/remove hostnames and toggle providers without a
	// restart. Legacy resolver — new code reads CommerceStore.Tenants.
	CheckoutResolver *checkout.StaticResolver

	// CommerceStore is the hanzo/base-backed persistence seam. When set it
	// provides the authoritative tenants + hostname-claims collections;
	// handlers that have migrated off the legacy resolver use this directly.
	// Initialized in Bootstrap from COMMERCE_DATA_DIR / COMMERCE_BASE_URL.
	CommerceStore *commercestore.Store
	// contains filtered or unexported fields
}

App is the main Commerce application

func New

func New() *App

New creates a new Commerce application with default configuration

func NewWithConfig

func NewWithConfig(config *Config) *App

NewWithConfig creates a new Commerce application with the given configuration

func (*App) Bootstrap

func (app *App) Bootstrap() error

Bootstrap initializes the application

func (*App) Config

func (app *App) Config() *Config

Config returns the current configuration

func (*App) DataPath

func (app *App) DataPath(subpath string) string

DataPath returns the full path within the data directory

func (*App) IsDev

func (app *App) IsDev() bool

IsDev returns true if running in development mode

func (*App) Serve

func (app *App) Serve() error

Serve starts the HTTP server

func (*App) Shutdown

func (app *App) Shutdown() error

Shutdown gracefully shuts down the application

func (*App) Start

func (app *App) Start() error

Start runs the application

type Config

type Config struct {
	// DataDir is the base directory for all data
	DataDir string

	// Dev enables development mode
	Dev bool

	// Secret for encryption and sessions
	Secret string

	// HTTP server address
	HTTPAddr string

	// HTTPS server address (optional)
	HTTPSAddr string

	// TLS certificate paths
	TLSCert string
	TLSKey  string

	// CORS allowed origins
	AllowedOrigins []string

	// Database configuration
	Database db.Config

	// Analytics collector endpoint (optional)
	AnalyticsEndpoint string

	// Analytics DSN (optional, for direct ClickHouse queries)
	DatastoreDSN string

	// Infrastructure configuration
	Infra infra.Config

	// Query timeout
	QueryTimeout time.Duration

	// KMS configuration for secret management
	KMS kms.Config

	// IAM configuration for hanzo.id JWT validation
	IAM struct {
		Enabled           bool     `json:"enabled"`
		Issuer            string   `json:"issuer"`
		ClientID          string   `json:"clientId"`
		ClientSecret      string   `json:"clientSecret"`
		AcceptedAudiences []string `json:"acceptedAudiences"`
		AcceptedIssuers   []string `json:"acceptedIssuers"`
		JwksURI           string   `json:"jwksUri"`
	} `json:"iam"`
}

Config holds application configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration

Directories

Path Synopsis
Package ai provides AI-powered product recommendations and embeddings via Hanzo Cloud-Backend (Rust inference API) and Hanzo Cloud (Go API).
Package ai provides AI-powered product recommendations and embeddings via Hanzo Cloud-Backend (Rust inference API) and Hanzo Cloud (Go API).
api
account
Package account — login deprecated.
Package account — login deprecated.
cdn
dashv2
Package dashv2 — login deprecated.
Package dashv2 — login deprecated.
tax
xd
Package auth provides authentication utilities including IAM OAuth2/OIDC integration.
Package auth provides authentication utilities including IAM OAuth2/OIDC integration.
Package billing embeds the Next.js-built billing admin SPA into the commerce binary.
Package billing embeds the Next.js-built billing admin SPA into the commerce binary.
credit
Package credit provides reusable starter credit logic.
Package credit provides reusable starter credit logic.
engine
Package engine provides core billing business logic: usage aggregation, payment collection, and subscription lifecycle management.
Package engine provides core billing business logic: usage aggregation, payment collection, and subscription lifecycle management.
grant
Package grant implements manual subscription grants — used for gifting Pro subscriptions, comp'ing beta users, and admin overrides.
Package grant implements manual subscription grants — used for gifting Pro subscriptions, comp'ing beta users, and admin overrides.
ledger
Package ledger implements a double-entry accounting ledger for the billing engine.
Package ledger implements a double-entry accounting ledger for the billing engine.
tier
Package tier defines the tiered credit system for Hanzo billing.
Package tier defines the tiered credit system for Hanzo billing.
workflows
Package workflows provides Temporal workflow definitions for automated recurring billing, subscription lifecycle management, and dunning retry logic.
Package workflows provides Temporal workflow definitions for automated recurring billing, subscription lifecycle management, and dunning retry logic.
Package checkout: admin API scaffolding for /_/commerce/*.
Package checkout: admin API scaffolding for /_/commerce/*.
cmd
commerce command
commerced command
grant command
Package main implements commerce-grant — a CLI for manually granting subscriptions to users (e.g.
Package main implements commerce-grant — a CLI for manually granting subscriptions to users (e.g.
sbom-scan command
Command sbom-scan clones Hanzo GitHub repos, runs git blame analysis, and produces SBOMEntry + Contributor records for OSS revenue sharing payouts.
Command sbom-scan clones Hanzo GitHub repos, runs git blame analysis, and produces SBOMEntry + Contributor records for OSS revenue sharing payouts.
development command
production command
sandbox command
staging command
test command
cron
payout/contributor
Package contributor executes the OSS contributor revenue sharing payouts.
Package contributor executes the OSS contributor revenue sharing payouts.
key
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - Hanzo Datastore (DATASTORE_URL) for deep analytics and parallel queries
Package db provides a multi-layer database abstraction supporting: - User-level SQLite with sqlite-vec for personal data and vector search - Organization-level SQLite for shared tenant data - Hanzo Datastore (DATASTORE_URL) for deep analytics and parallel queries
Package delay provides a task queue abstraction for background job execution.
Package delay provides a task queue abstraction for background job execution.
demo
Package events provides a thin HTTP client for the analytics collector.
Package events provides a thin HTTP client for the analytics collector.
Package hooks provides event types for the hook system.
Package hooks provides event types for the hook system.
Package infra provides unified infrastructure clients for Commerce.
Package infra provides unified infrastructure clients for Commerce.
log
Package middleware provides HTTP middleware for the Commerce API.
Package middleware provides HTTP middleware for the Commerce API.
iammiddleware
Package iammiddleware is the gateway-trust shim for legacy call sites.
Package iammiddleware is the gateway-trust shim for legacy call sites.
models
app
fee
order
Package order provides the Order model with support for the new db.DB interface.
Package order provides the Order model with support for the new db.DB interface.
product
Package product provides model initialization and query helpers for the v2 Product model.
Package product provides model initialization and query helpers for the v2 Product model.
user/v2
Package user provides the User model using the new db.DB interface.
Package user provides the User model using the new db.DB interface.
Package payment provides per-org payment processor configuration.
Package payment provides per-org payment processor configuration.
providers
Package providers is a convenience package that imports all payment provider packages, ensuring they are available for the processor registry.
Package providers is a convenience package that imports all payment provider packages, ensuring they are available for the processor registry.
providers/bitpay
Package bitpay implements the BitPay payment processor for Commerce.
Package bitpay implements the BitPay payment processor for Commerce.
providers/circle
Package circle implements the Circle Payments API processor for Commerce.
Package circle implements the Circle Payments API processor for Commerce.
providers/coinbase_commerce
Package coinbase_commerce implements the Coinbase Commerce payment processor for Commerce.
Package coinbase_commerce implements the Coinbase Commerce payment processor for Commerce.
providers/moonpay
Package moonpay implements the MoonPay on-ramp processor for Commerce.
Package moonpay implements the MoonPay on-ramp processor for Commerce.
providers/opennode
Package opennode implements the OpenNode (Lightning) payment processor for Commerce.
Package opennode implements the OpenNode (Lightning) payment processor for Commerce.
providers/solanapay
Package solanapay implements the Solana Pay payment processor for Commerce.
Package solanapay implements the Solana Pay payment processor for Commerce.
providers/square
Package square is the unified Square payment provider.
Package square is the unified Square payment provider.
providers/stripe
Package stripe — catalog (Products and Prices) helpers used by the plan seeder.
Package stripe — catalog (Products and Prices) helpers used by the plan seeder.
router
Package router provides an intelligent multi-processor payment routing layer.
Package router provides an intelligent multi-processor payment routing layer.
x402
Package x402 implements the x402 Payment Protocol (LP-3028) for HTTP-native crypto payments using the 402 Payment Required status code.
Package x402 implements the x402 Payment Protocol (LP-3028) for HTTP-native crypto payments using the 402 Payment Required status code.
pkg
auth
Package auth wires gateway-supplied identity headers (X-Org-Id, X-User-Id, X-User-Email) into request context.
Package auth wires gateway-supplied identity headers (X-Org-Id, X-User-Id, X-User-Email) into request context.
commerce
Package commerce (pkg/commerce) is the embedded Commerce server.
Package commerce (pkg/commerce) is the embedded Commerce server.
org
Package org provides KV-cached org resolution from gateway-supplied X-Org-Id headers.
Package org provides KV-cached org resolution from gateway-supplied X-Org-Id headers.
Package seed wires @hanzo/plans entries to payment-processor catalogs.
Package seed wires @hanzo/plans entries to payment-processor catalogs.
Package store — hanzo/base seam entry point.
Package store — hanzo/base seam entry point.
migrations
Package migrations — commerce-owned base migrations.
Package migrations — commerce-owned base migrations.
seed
Package seed — one-shot seed helpers for local dev.
Package seed — one-shot seed helpers for local dev.
test
test-integration
thirdparty
cloudflare
Package cloudflare provides a Cloudflare API v4 client for Commerce.
Package cloudflare provides a Cloudflare API v4 client for Commerce.
kms
Package kms provides a thin HTTP client for KMS (Infisical-compatible) secret management.
Package kms provides a thin HTTP client for KMS (Infisical-compatible) secret management.
mercury
Package mercury provides types and utilities for integrating with the Mercury bank API and webhook events.
Package mercury provides types and utilities for integrating with the Mercury bank API and webhook events.
mpc
paypal/ipn
Reference: https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
Reference: https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNIntro/
Package ui exposes the built admin-commerce (Hanzo GUI v7) bundle as an embedded filesystem.
Package ui exposes the built admin-commerce (Hanzo GUI v7) bundle as an embedded filesystem.
util
bit
cache
Package cache (memcache.go) provides a caching abstraction layer that can work with different backends (in-memory, Redis, etc.) to replace appengine/memcache.
Package cache (memcache.go) provides a caching abstraction layer that can work with different backends (in-memory, Redis, etc.) to replace appengine/memcache.
csv
fs
gob
jwt
nscontext
Package nscontext provides namespace context functionality that replaces google.golang.org/appengine.Namespace.
Package nscontext provides namespace context functionality that replaces google.golang.org/appengine.Namespace.
search
Package search provides a search abstraction layer with pluggable backends.
Package search provides a search abstraction layer with pluggable backends.
slug
Package slug transforms strings into a normalized form well suited for use in URLs.
Package slug transforms strings into a normalized form well suited for use in URLs.
val

Jump to

Keyboard shortcuts

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