payagentic

package module
v0.1.1 Latest Latest
Warning

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

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

README

PayAgentic Go SDK

Build AI agents that buy API data using PayAgentic's programmable stablecoin wallets, spend policies and x402 payment APIs.

Package reference · Developer home · SDK documentation · Pricing · Integration support

Install

Requires Go 1.24.3 or later; see go.mod for this release's toolchain requirements.

mkdir payagentic-example
cd payagentic-example
go mod init example/payagentic
go get github.com/payagentic/payagentic-go

Pin the installed version in your application's go.mod and commit go.sum. This is a pre-1.0 SDK: review and test changes before upgrading.

Check your connection

Set PAYAGENTIC_API_KEY through your server's runtime environment or secret manager. For this example, set PAYAGENTIC_BASE_URL=https://app.payagentic.ai, the hosted production gateway. Use your own gateway origin for another deployment. The SDK also uses the hosted origin when no base URL is configured.

Save the following as main.go and run go run .. It performs a read-only wallet request and prints the HTTP status, without printing wallet data or the API key.

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    payagentic "github.com/payagentic/payagentic-go"
)

func main() {
    baseURL := os.Getenv("PAYAGENTIC_BASE_URL")
    if baseURL == "" { log.Fatal("Set PAYAGENTIC_BASE_URL") }
    client, err := payagentic.NewClient(payagentic.WithBaseURL(baseURL))
    if err != nil { log.Fatal("Check SDK configuration") }
    defer client.Close()
    result, err := client.OpenAPI.ListWalletsWithResponse(context.Background(), nil)
    if err != nil { log.Fatal("Gateway request failed") }
    fmt.Println("Gateway HTTP status:", result.StatusCode())
}

Expected output with a working gateway and authorized key:

Gateway HTTP status: 200

The same complete program is in examples/connection/main.go. From a checkout of this repository, run go run ./examples/connection.

Try the buyer and merchant workflow

The public runnable examples provides a downloadable Node.js buyer and merchant demonstration with setup instructions, expected output and tests. It illustrates the HTTP exchange for developers in any language. Payment authorization is simulated; no funds move.

For actual payments, follow the quickstart, finish wallet provisioning and configure a funded test wallet and spend policy. Merchants must register their API and endpoint and verify origin ownership to test the registered merchant transaction fee flow. An HTTP 200 response alone does not prove settlement; reconcile gateway transaction status before recording it.

Troubleshooting and compatibility

From a standalone checkout, run go vet ./..., go test -race -count=1 ./... and go build ./.... No monorepo checkout, external OpenAPI fixture or live API credential is needed. The route inventory test checks the generated transport shipped in this module. The GitHub workflow runs these same checks before release review.

  • Missing key or configuration error: make the runtime variables available to the process running the example.
  • DNS or connection failure: verify PAYAGENTIC_BASE_URL with your deployment operator.
  • HTTP 401 or 403: check the key's environment and permissions. Do not post the key in an issue or paste it into browser code.
  • Documentation mentions a method absent from your installed SDK: confirm the gateway and SDK release versions before changing your integration.

This public repository is a release mirror of the private PayAgentic monorepo. Public releases can lag source development; website examples may target newer source builds. The download guide identifies source-built examples separately from registry releases. Use this repository and pkg.go.dev to inspect the API actually installed.

The SDK uses the MIT license (see LICENSE). Platform subscriptions and transaction fees are separate; see pricing.

Documentation

Overview

Package payagentic is the official Go SDK for PayAgentic.

Example usage:

import "github.com/payagentic/payagentic-go"

client, err := payagentic.NewClient(payagentic.WithAPIKey("pa_test_…"))
if err != nil {
    log.Fatal(err)
}
ctx := context.Background()
wallets, err := client.OpenAPI.ListWalletsWithResponse(ctx, nil)
resp, err := client.X402.Fetch(ctx, "https://vendor.example.com/data")

Package payagentic provides a Go client for the PayAgentic agent payments platform.

PayAgentic enables African businesses building AI agents to manage programmable USDC wallets. Agents pay external APIs over x402, governed by operator-defined spend policies. Operators fund wallets via local fiat rails and withdraw to local bank accounts.

Quick start

client := payagentic.NewClient(
    payagentic.WithAPIKey("your-api-key"),
)

wallets, err := client.Wallets.List(ctx, nil)

Configuration from environment

client := payagentic.NewClient(payagentic.FromEnvironment())

Set PAYAGENTIC_API_KEY and PAYAGENTIC_AGENT_ID environment variables.

Index

Constants

View Source
const (
	MandateSupportedVersion = 1
	MandateSupportedAlg     = "EdDSA"
	DefaultMandateAudience  = "payagentic-mandate"
)
View Source
const DefaultBaseURL = "https://app.payagentic.ai"

DefaultBaseURL is the production gateway URL used when WithBaseURL is not set.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout is the http.Client request timeout used when WithTimeout is not set.

View Source
const Version = "0.1.0"

Version is the current SDK version.

Variables

This section is empty.

Functions

func CanonicalJSONBytes

func CanonicalJSONBytes(v any) ([]byte, error)

CanonicalJSONBytes returns the RFC 8785 canonical JSON UTF-8 bytes of v.

Procedure: serialise via encoding/json (so floats, strings, escapes match the JSON spec), then re-parse via json.Decoder with UseNumber, and re- serialise via a small hand-rolled encoder that sorts object keys and emits no whitespace. This is the simplest path that matches serde_jcs output for the integer/string/array/object payloads we use.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether the error is a 409 Conflict.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether the error is a 403 Forbidden.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether the error is a 404 Not Found.

func IsRateLimit

func IsRateLimit(err error) bool

IsRateLimit reports whether the error is a 429 Too Many Requests.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether the given error represents a transient failure that should be retried.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether the error is a 401 Unauthorized.

func IsValidation

func IsValidation(err error) bool

IsValidation reports whether the error is a 422 Unprocessable Entity.

func PresentMandate

func PresentMandate(params BuildPresentationParams, signer MandateSigner) (string, error)

PresentMandate builds and signs a presentation JWS for the given claim.

func SignJWS

func SignJWS(payload any, signer MandateSigner) (string, error)

SignJWS signs payload as a compact-form JWS with alg=EdDSA.

Types

type APIError

type APIError = middleware.APIError

APIError re-exports the base API error type.

type Agent

type Agent struct {
	ID             string    `json:"id"`
	OrganizationID string    `json:"organization_id"`
	Name           string    `json:"name"`
	Status         string    `json:"status"`
	KeyFingerprint string    `json:"key_fingerprint,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

Agent represents an AI agent registered on the platform.

type AgentResponse

type AgentResponse = openapi.AgentResponse

AgentResponse is the gateway response shape for a single agent.

type ApiKeyResponse

type ApiKeyResponse = openapi.ApiKeyResponse

ApiKeyResponse is the gateway response shape for an API key.

type Approval

type Approval struct {
	ID          string         `json:"id"`
	Type        string         `json:"type"`
	Status      ApprovalStatus `json:"status"`
	RequestedBy string         `json:"requested_by"`
	ReviewedBy  string         `json:"reviewed_by,omitempty"`
	Reason      string         `json:"reason,omitempty"`
	Payload     map[string]any `json:"payload,omitempty"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
}

Approval represents a pending approval request.

type ApprovalDecisionRequest

type ApprovalDecisionRequest struct {
	Reason string `json:"reason,omitempty"`
}

ApprovalDecisionRequest contains the fields for approving or denying a request.

type ApprovalStatus

type ApprovalStatus string

ApprovalStatus represents the status of an approval request.

const (
	ApprovalStatusPending  ApprovalStatus = "pending"
	ApprovalStatusApproved ApprovalStatus = "approved"
	ApprovalStatusDenied   ApprovalStatus = "denied"
	ApprovalStatusExpired  ApprovalStatus = "expired"
)

type AuditEntry

type AuditEntry struct {
	ID        string         `json:"id"`
	EventType string         `json:"event_type"`
	ActorID   string         `json:"actor_id"`
	ActorType string         `json:"actor_type"`
	Payload   map[string]any `json:"payload,omitempty"`
	Hash      string         `json:"hash"`
	PrevHash  string         `json:"prev_hash"`
	CreatedAt time.Time      `json:"created_at"`
}

AuditEntry represents an immutable audit log entry.

type BalanceResponse

type BalanceResponse = openapi.BalanceResponse

BalanceResponse is the gateway response shape for a wallet balance query.

type BuildPresentationParams

type BuildPresentationParams struct {
	AgentSpiffeID string
	Audience      string
	Grants        []string
	Claim         PresentationClaim
	IAT           int64 // optional; defaults to time.Now().Unix()
	Exp           int64 // optional; defaults to IAT + 300
	JTI           string
}

BuildPresentationParams configures PresentMandate.

type Client

type Client struct {

	// OpenAPI exposes the generated transport with all gateway operations
	// in the *WithResponse form (status-code-typed responses).
	OpenAPI *openapi.ClientWithResponses
	// X402 is the x402 payment helper.
	X402 *X402Client
	// contains filtered or unexported fields
}

Client is the PayAgentic API client. Use NewClient to create one.

It exposes:

  • OpenAPI: a generated *openapi.Client with one method per gateway endpoint (e.g. client.OpenAPI.ListWalletsWithResponse(ctx, nil))
  • X402: the x402 payment helper

The Client's underlying http.Client has bearer auth, retries, idempotency keys, and RFC 7807 typed errors composed via internal/middleware.NewTransport.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient builds a Client with the given options.

Resolves APIKey from PAYAGENTIC_API_KEY env, AgentID from PAYAGENTIC_AGENT_ID, and BaseURL from PAYAGENTIC_BASE_URL when not set explicitly via Options. Returns an error if no API key is resolvable.

func (*Client) Close

func (c *Client) Close() error

Close releases any resources held by the Client.

func (*Client) Mandates

func (c *Client) Mandates() *MandatesService

Mandates returns a MandatesService bound to this client.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, path string) (*EventStream, error)

Subscribe opens an SSE connection to the given event stream path. The returned EventStream must be closed when no longer needed.

type Config

type Config struct {
	// APIKey is the bearer token used for authentication.
	APIKey string
	// BaseURL is the PayAgentic API base URL.
	BaseURL string
	// AgentID is the optional agent identifier sent as a request header.
	AgentID string
	// Timeout is the per-request timeout applied to the underlying http.Client.
	Timeout time.Duration
}

Config holds the configuration for the PayAgentic client.

type ConflictError

type ConflictError = middleware.ConflictError

ConflictError re-exports the 409 typed error.

type CreateAgentRequest

type CreateAgentRequest struct {
	Name string `json:"name"`
}

CreateAgentRequest contains the fields for creating an agent.

type CreateApiKeyResponse

type CreateApiKeyResponse = openapi.CreateApiKeyResponse

CreateApiKeyResponse is the one-time-secret payload returned on key creation.

type CreateOrganizationRequest

type CreateOrganizationRequest struct {
	Name string `json:"name"`
}

CreateOrganizationRequest contains the fields for creating an organization.

type CreatePolicyRequest

type CreatePolicyRequest struct {
	Name  string      `json:"name"`
	Type  PolicyType  `json:"type"`
	Rules PolicyRules `json:"rules"`
}

CreatePolicyRequest contains the fields for creating a spend policy.

type DashboardStats

type DashboardStats = openapi.DashboardStats

DashboardStats is the dashboard summary payload.

type Event

type Event struct {
	// Type is the event type (e.g. "transaction.confirmed", "payment.settled").
	Type string `json:"type"`
	// Data is the raw JSON payload of the event.
	Data json.RawMessage `json:"data"`
}

Event represents a server-sent event from the PayAgentic streaming API.

type EventStream

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

EventStream provides an iterator over server-sent events (SSE) from the API.

func (*EventStream) Close

func (es *EventStream) Close() error

Close closes the event stream and releases resources.

func (*EventStream) Next

func (es *EventStream) Next() (*Event, error)

Next reads the next event from the stream. It blocks until an event is available, an error occurs, or the stream is closed. Returns nil, nil when the stream ends.

type FetchOption

type FetchOption func(*fetchConfig)

FetchOption configures a Fetch call.

func WithMaxAmount

func WithMaxAmount(amount string) FetchOption

WithMaxAmount sets a cap on what the walker is willing to spend during the 402 walk (decimal string, e.g. "1.00").

func WithMethod

func WithMethod(method string) FetchOption

WithMethod sets the HTTP method for the outer fetch (default GET).

type ForbiddenError

type ForbiddenError = middleware.ForbiddenError

ForbiddenError re-exports the 403 typed error.

type FundWalletRequest

type FundWalletRequest struct {
	Amount   string `json:"amount"`
	Currency string `json:"currency"`
	Source   string `json:"source"`
}

FundWalletRequest contains the fields for funding a wallet.

type HealthResponse

type HealthResponse = openapi.HealthResponse

HealthResponse is the gateway response shape for /healthz.

type IssueGrantParams

type IssueGrantParams struct {
	SubjectAgentID string         `json:"subject_agent_id"`
	Scope          map[string]any `json:"scope"`
	Exp            int64          `json:"exp"`
	NBF            *int64         `json:"nbf,omitempty"`
	MaxDepth       int            `json:"max_depth"`
	ParentJTI      string         `json:"parent_jti,omitempty"`
	IssuerKID      string         `json:"issuer_kid"`
}

IssueGrantParams configures Client.IssueGrant.

type IssuedGrant

type IssuedGrant struct {
	JTI         string `json:"jti"`
	EnvelopeJWS string `json:"envelope_jws"`
}

IssuedGrant is the response from POST /v1/mandates/issue.

type Iterator

type Iterator[T any] struct {
	// contains filtered or unexported fields
}

Iterator provides a convenient way to iterate over all pages of a paginated response.

func NewIterator

func NewIterator[T any](fetch func(cursor string) (*PaginatedResponse[T], error)) *Iterator[T]

NewIterator creates a new paginated iterator. The fetch function is called for each page with the current cursor value (empty string for the first page).

func (*Iterator[T]) Next

func (it *Iterator[T]) Next() (*PaginatedResponse[T], error)

Next returns the next page of results. It returns nil, nil when all pages have been consumed.

type ListOptions

type ListOptions struct {
	// Cursor is an opaque pagination cursor for fetching the next page.
	Cursor string `json:"cursor,omitempty"`
	// Limit is the maximum number of items to return per page.
	Limit int `json:"limit,omitempty"`
	// Filter is an optional filter expression.
	Filter string `json:"filter,omitempty"`
}

ListOptions configures paginated list requests.

type LocalMandateSigner

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

LocalMandateSigner holds an Ed25519 private key in memory and signs locally. Use for development, tests, and short-lived agent processes. Production operator signers should wrap Vault or an HSM.

func GenerateLocalMandateSigner

func GenerateLocalMandateSigner(kid string) (*LocalMandateSigner, error)

GenerateLocalMandateSigner produces a new random Ed25519 key.

func NewLocalMandateSigner

func NewLocalMandateSigner(kid string, seed []byte) (*LocalMandateSigner, error)

NewLocalMandateSigner constructs a signer from a 32-byte seed (the canonical Ed25519 "private key" representation matching the TS and Python SDKs).

func (*LocalMandateSigner) Kid

func (s *LocalMandateSigner) Kid() string

Kid implements MandateSigner.

func (*LocalMandateSigner) PublicKey

func (s *LocalMandateSigner) PublicKey() ed25519.PublicKey

PublicKey returns the 32-byte Ed25519 public key.

func (*LocalMandateSigner) Sign

func (s *LocalMandateSigner) Sign(message []byte) ([]byte, error)

Sign implements MandateSigner.

type MandateMoney

type MandateMoney struct {
	Amount   string `json:"amount"`
	Currency string `json:"currency"`
}

MandateMoney is the JSON shape for Money used in mandate payloads. Currency defaults to USDC in v1.

type MandateSigner

type MandateSigner interface {
	Kid() string
	Sign(message []byte) ([]byte, error)
}

MandateSigner produces an Ed25519 signature over a mandate signing input.

Kid is echoed in the JWS protected header so the verifier can look up the matching public key.

type MandatesService

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

MandatesService exposes operator-side issue / revoke endpoints.

Construct via Client.Mandates() — it is intentionally not auto-attached to NewClient so existing call sites keep working.

func (*MandatesService) Issue

Issue calls POST /v1/mandates/issue.

NOTE: /v1/mandates/issue and /v1/mandates/{jti}/revoke are owned by the identity service, not exposed in the gateway spec at api/openapi.json. Direct HTTP via client.do() is the only option until those endpoints are surfaced.

func (*MandatesService) Revoke

func (s *MandatesService) Revoke(ctx context.Context, jti, reason string) (*RevokedGrant, error)

Revoke calls POST /v1/mandates/{jti}/revoke. Idempotent.

NOTE: identity-service-owned (see Issue's docstring for rationale).

type MeResponse

type MeResponse = openapi.MeResponse

MeResponse is the gateway response shape for the /v1/me identity probe.

type NotFoundError

type NotFoundError = middleware.NotFoundError

NotFoundError re-exports the 404 typed error.

type Option

type Option func(*Client)

Option configures a Client.

func FromEnvironment

func FromEnvironment() Option

FromEnvironment is a no-op Option retained for backward compatibility. Environment resolution now happens automatically inside NewClient.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key sent as Bearer token.

func WithAgentID

func WithAgentID(id string) Option

WithAgentID sets the X-Agent-ID header.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the gateway URL.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient overrides the underlying http.Client. When set, the SDK uses this client as-is — middleware composition is the caller's responsibility.

func WithRetryPolicy

func WithRetryPolicy(p middleware.RetryPolicy) Option

WithRetryPolicy overrides the retry policy.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the request timeout on the underlying http.Client.

type Organization

type Organization struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Organization represents an organization on the platform.

type OrganizationResponse

type OrganizationResponse = openapi.OrganizationResponse

OrganizationResponse is the gateway response shape for an organization.

type PaginatedResponse

type PaginatedResponse[T any] struct {
	// Items contains the page of results.
	Items []T `json:"items"`
	// NextCursor is the opaque cursor for fetching the next page. Empty when there are no more pages.
	NextCursor string `json:"next_cursor,omitempty"`
	// TotalCount is the total number of items matching the query, if available.
	TotalCount int64 `json:"total_count,omitempty"`
}

PaginatedResponse wraps a paginated list of items returned by the API.

type Payment

type Payment struct {
	ID            string        `json:"id"`
	WalletID      string        `json:"wallet_id"`
	AgentID       string        `json:"agent_id"`
	Status        PaymentStatus `json:"status"`
	Amount        string        `json:"amount"`
	Currency      string        `json:"currency"`
	Recipient     string        `json:"recipient"`
	Description   string        `json:"description,omitempty"`
	TransactionID string        `json:"transaction_id,omitempty"`
	CreatedAt     time.Time     `json:"created_at"`
	UpdatedAt     time.Time     `json:"updated_at"`
}

Payment represents an x402 payment.

type PaymentIntent

type PaymentIntent = openapi.PaymentResponse

PaymentIntent is the gateway's PaymentResponse — returned by both propose and status-poll endpoints.

type PaymentResponse

type PaymentResponse = openapi.PaymentResponse

PaymentResponse is the gateway response shape for a payment intent. Also aliased as PaymentIntent in x402.go for x402-flow ergonomics.

type PaymentStatus

type PaymentStatus string

PaymentStatus represents the lifecycle status of a payment.

const (
	PaymentStatusProposed  PaymentStatus = "proposed"
	PaymentStatusApproved  PaymentStatus = "approved"
	PaymentStatusExecuting PaymentStatus = "executing"
	PaymentStatusSettled   PaymentStatus = "settled"
	PaymentStatusFailed    PaymentStatus = "failed"
	PaymentStatusRejected  PaymentStatus = "rejected"
)

type PayoutResponse

type PayoutResponse = openapi.PayoutResponse

PayoutResponse is the gateway response shape for a merchant payout.

type Policy

type Policy struct {
	ID             string      `json:"id"`
	OrganizationID string      `json:"organization_id"`
	Name           string      `json:"name"`
	Type           PolicyType  `json:"type"`
	Rules          PolicyRules `json:"rules"`
	CreatedAt      time.Time   `json:"created_at"`
	UpdatedAt      time.Time   `json:"updated_at"`
}

Policy represents a spend policy governing agent wallets.

type PolicyResponse

type PolicyResponse = openapi.PolicyResponse

PolicyResponse is the gateway response shape for a single policy.

type PolicyRules

type PolicyRules struct {
	MaxAmount         string       `json:"max_amount,omitempty"`
	DailyLimit        string       `json:"daily_limit,omitempty"`
	MonthlyLimit      string       `json:"monthly_limit,omitempty"`
	AllowedChains     []string     `json:"allowed_chains,omitempty"`
	AllowedRecipients []string     `json:"allowed_recipients,omitempty"`
	TimeWindows       []TimeWindow `json:"time_windows,omitempty"`
}

PolicyRules defines the set of rules within a policy.

type PolicyType

type PolicyType string

PolicyType represents the type of policy.

const (
	PolicyTypeSpendCap   PolicyType = "spend_cap"
	PolicyTypeAllowlist  PolicyType = "allowlist"
	PolicyTypeTimeWindow PolicyType = "time_window"
	PolicyTypeVelocity   PolicyType = "velocity"
	PolicyTypeComposite  PolicyType = "composite"
)

type PresentationClaim

type PresentationClaim struct {
	Amount      MandateMoney `json:"amount"`
	MerchantID  string       `json:"merchant_id"`
	MCC         string       `json:"mcc"`
	OccurredAt  int64        `json:"occurred_at"`
	Geo         string       `json:"geo"`
	ResourceURL string       `json:"resource_url"`
}

PresentationClaim is the per-charge claim asserted by the agent at presentation time.

type ProblemDetails

type ProblemDetails = middleware.ProblemDetails

ProblemDetails re-exports the RFC 9457 error envelope from the internal middleware package.

type ProposePaymentBody

type ProposePaymentBody = openapi.ProposePaymentJSONRequestBody

ProposePaymentBody is the request body for POST /v1/payments/propose.

type ProposePaymentRequest

type ProposePaymentRequest struct {
	WalletID    string `json:"wallet_id"`
	Recipient   string `json:"recipient"`
	Amount      string `json:"amount"`
	Currency    string `json:"currency"`
	Description string `json:"description,omitempty"`
}

ProposePaymentRequest contains the fields for proposing an x402 payment.

type RateLimitError

type RateLimitError = middleware.RateLimitError

RateLimitError re-exports the 429 typed error.

type RefundResponse

type RefundResponse = openapi.RefundResponse

RefundResponse is the gateway response shape for a refund.

type RetryPolicy

type RetryPolicy = middleware.RetryPolicy

RetryPolicy re-exports the retry policy configuration from the internal middleware package so callers can stay on the parent import.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns a sensible default retry policy.

type RevokedGrant

type RevokedGrant struct {
	JTI       string `json:"jti"`
	RevokedAt string `json:"revoked_at"`
}

RevokedGrant is the response from POST /v1/mandates/{jti}/revoke.

type SessionKey

type SessionKey struct {
	// KeyID is the unique identifier for this session key.
	KeyID string `json:"key_id"`
	// Secret is the HMAC secret used for signing.
	Secret string `json:"secret"`
	// ExpiresAt is when the session key expires.
	ExpiresAt time.Time `json:"expires_at"`
	// Scopes lists the permitted API scopes for this key.
	Scopes []string `json:"scopes,omitempty"`
}

SessionKey represents a time-scoped signing key for request authentication. Session keys allow agents to sign requests without exposing the primary API key.

func (*SessionKey) IsExpired

func (sk *SessionKey) IsExpired() bool

IsExpired reports whether the session key has expired.

func (*SessionKey) Sign

func (sk *SessionKey) Sign(message string) (string, error)

Sign produces an HMAC-SHA256 signature for the given message using the session key secret.

func (*SessionKey) SignRequest

func (sk *SessionKey) SignRequest(method, path string, ts time.Time) (string, error)

SignRequest produces a signature string suitable for the Authorization header. The canonical message is: METHOD\nPATH\nTIMESTAMP

type StatsResponse

type StatsResponse = openapi.StatsResponse

StatsResponse is the gateway response shape for the merchant /stats surface.

type TimeWindow

type TimeWindow struct {
	DaysOfWeek []string `json:"days_of_week"`
	StartTime  string   `json:"start_time"`
	EndTime    string   `json:"end_time"`
	Timezone   string   `json:"timezone"`
}

TimeWindow defines an allowed time window for transactions.

type Transaction

type Transaction struct {
	ID        string            `json:"id"`
	WalletID  string            `json:"wallet_id"`
	Type      TransactionType   `json:"type"`
	Status    TransactionStatus `json:"status"`
	Amount    string            `json:"amount"`
	Currency  string            `json:"currency"`
	TxHash    string            `json:"tx_hash,omitempty"`
	Chain     string            `json:"chain"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

Transaction represents a blockchain transaction.

type TransactionResponse

type TransactionResponse = openapi.TransactionResponse

TransactionResponse is the gateway response shape for a single transaction.

type TransactionStatus

type TransactionStatus string

TransactionStatus represents the lifecycle status of a transaction.

const (
	TransactionStatusPending   TransactionStatus = "pending"
	TransactionStatusConfirmed TransactionStatus = "confirmed"
	TransactionStatusFailed    TransactionStatus = "failed"
	TransactionStatusCancelled TransactionStatus = "cancelled"
)

type TransactionType

type TransactionType string

TransactionType represents the type of transaction.

const (
	TransactionTypeTransfer TransactionType = "transfer"
	TransactionTypeFund     TransactionType = "fund"
	TransactionTypeWithdraw TransactionType = "withdraw"
	TransactionTypePayment  TransactionType = "payment"
)

type UnauthorizedError

type UnauthorizedError = middleware.UnauthorizedError

UnauthorizedError re-exports the 401 typed error.

type UpdateOrganizationRequest

type UpdateOrganizationRequest struct {
	Name string `json:"name,omitempty"`
}

UpdateOrganizationRequest contains the fields for updating an organization.

type UpdatePolicyRequest

type UpdatePolicyRequest struct {
	Name  string       `json:"name,omitempty"`
	Rules *PolicyRules `json:"rules,omitempty"`
}

UpdatePolicyRequest contains the fields for updating a spend policy.

type User

type User struct {
	ID             string    `json:"id"`
	OrganizationID string    `json:"organization_id"`
	Email          string    `json:"email"`
	Name           string    `json:"name"`
	Role           string    `json:"role"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
}

User represents a user within an organization.

type ValidationError

type ValidationError = middleware.ValidationError

ValidationError re-exports the 422 typed error.

type Wallet

type Wallet struct {
	ID             string       `json:"id"`
	OrganizationID string       `json:"organization_id"`
	AgentID        string       `json:"agent_id,omitempty"`
	Address        string       `json:"address"`
	Chain          string       `json:"chain"`
	Balance        string       `json:"balance"`
	Status         WalletStatus `json:"status"`
	CreatedAt      time.Time    `json:"created_at"`
	UpdatedAt      time.Time    `json:"updated_at"`
}

Wallet represents a USDC smart account wallet.

type WalletResponse

type WalletResponse = openapi.WalletResponse

WalletResponse is the gateway response shape for a single wallet.

type WalletStatus

type WalletStatus string

WalletStatus represents the status of a wallet.

const (
	WalletStatusActive WalletStatus = "active"
	WalletStatusFrozen WalletStatus = "frozen"
	WalletStatusClosed WalletStatus = "closed"
)

type WithdrawWalletRequest

type WithdrawWalletRequest struct {
	Amount      string `json:"amount"`
	Currency    string `json:"currency"`
	Destination string `json:"destination"`
}

WithdrawWalletRequest contains the fields for withdrawing from a wallet.

type X402Client

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

X402Client is the x402 paywall walker. Construct via NewX402Client(*Client) — it shares the parent Client's authenticated transport.

func NewX402Client

func NewX402Client(c *Client) *X402Client

NewX402Client creates a new X402Client from an existing Client.

func (*X402Client) Fetch

func (x *X402Client) Fetch(ctx context.Context, url string, opts ...FetchOption) (*http.Response, error)

Fetch performs an x402 walk: GET (or other method) the resource; if it returns 402, propose a payment, poll until it settles, then retry the original request with the payment receipt header set.

The walker uses the Client's underlying http.Client so the same retry + auth middleware applies to the outer fetch as to gateway calls.

func (*X402Client) GetPayment

func (x *X402Client) GetPayment(ctx context.Context, id string) (*PaymentIntent, error)

GetPayment issues GET /v1/payments/{id} via the generated transport.

Used by Fetch to poll for settlement; exposed publicly so callers driving their own polling loop can reuse the same path.

func (*X402Client) Propose

Propose issues POST /v1/payments/propose via the generated transport and returns the parsed PaymentResponse.

Use this directly when you already have the payment_requirements blob and want to drive the polling loop yourself. For the full 402 walk use Fetch.

type X402PaymentRequest

type X402PaymentRequest struct {
	// URL is the API endpoint that returned HTTP 402.
	URL string `json:"url"`
	// PaymentRequirements is the value of the upstream `X-PAYMENT-REQUIREMENTS`
	// (or `X-Payment-Requirements`) header from the 402 response.
	PaymentRequirements string `json:"payment_requirements"`
	// MaxAmount is the maximum amount the caller is willing to pay (optional cap).
	MaxAmount string `json:"max_amount,omitempty"`
}

X402PaymentRequest describes a payment triggered by an HTTP 402 response.

Retained as a thin public input type so callers can stage propose calls without importing the generated package.

Directories

Path Synopsis
examples
connection command
internal
middleware
Package middleware composes auth, retry, and RFC 7807 error mapping for the PayAgentic HTTP transport.
Package middleware composes auth, retry, and RFC 7807 error mapping for the PayAgentic HTTP transport.
openapi
Package openapi provides primitives to interact with the openapi HTTP API.
Package openapi provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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