absolutepay

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 16 Imported by: 0

README

absolutepay-go

Official AbsolutePay API client for Go. Server-side only — your API key and signing secret must never reach a browser.

Every request from an app key is HMAC-signed automatically. Inbound webhooks are verified with one call. Zero third-party dependencies — standard library only.

Install

go get github.com/AbsolutePay/absolutepay-go@latest

Requires Go 1.18+.

import absolutepay "github.com/AbsolutePay/absolutepay-go"

Environments

Option Base URL
default https://api.absolutepay.io (production)
WithSandbox(true) https://sandbox-api.absolutepay.io
WithBaseURL("https://…") your override (wins over sandbox)

Quickstart

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	absolutepay "github.com/AbsolutePay/absolutepay-go"
)

func main() {
	ap, err := absolutepay.New(
		os.Getenv("ABSOLUTEPAY_API_KEY"), // ap_live_… / ap_test_…
		absolutepay.WithSigningSecret(os.Getenv("ABSOLUTEPAY_SIGNING_SECRET")), // apisign_…
		// absolutepay.WithSandbox(true),
	)
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	balances, err := ap.Balances.List(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(balances)

	inv, err := ap.Invoices.Create(ctx, absolutepay.InvoiceParams{
		Reference: "order-123",
		Amount:    absolutepay.Money{Amount: "25.00", Currency: "USDT"},
		Chain:     "MATIC", // mint the deposit address up front; omit to let the payer pick
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(inv["token"])
}

Errors

Non-2xx responses return an *absolutepay.Error:

_, err := ap.Payouts.Create(ctx, items)
var apErr *absolutepay.Error
if errors.As(err, &apErr) {
	fmt.Println(apErr.Status, apErr.Code, apErr.Detail, apErr.RequestID)
	if apErr.IsRateLimited() { /* 429 — back off and retry */ }
	if apErr.IsAuth()        { /* 401/403 — check key, scope, or signature */ }
}

Pagination

Live lists use keyset pagination. Pass a prior page's NextCursor as PageQuery.Before; it's nil on the last page.

var before string
for {
	page, err := ap.Invoices.List(ctx, absolutepay.PageQuery{Limit: 50, Before: before})
	if err != nil {
		log.Fatal(err)
	}
	for _, raw := range page.Items {
		// json.Unmarshal(raw, &yourType)
	}
	if page.NextCursor == nil {
		break
	}
	before = *page.NextCursor
}

Webhooks

Verify the signature and parse the event in one call. Pass the raw request body:

func handler(w http.ResponseWriter, r *http.Request) {
	raw, _ := io.ReadAll(r.Body) // RAW bytes — do not re-serialize
	event, err := absolutepay.ConstructEvent(raw, r.Header, os.Getenv("ABSOLUTEPAY_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	if event.Type == "payment.succeeded" {
		// json.Unmarshal(event.Data, &yourType)
	}
	w.WriteHeader(http.StatusOK)
}

The freshness (replay) window defaults to 5 minutes; pass absolutepay.WithTolerance(0) to disable it.

Security

  • Server-side only. The API key + signing secret authenticate as your workspace.
  • Requests go over HTTPS only (except localhost for local development).
  • The Idempotency-Key header (on payouts) is intentionally not part of the signed canonical string.

License

MIT

Documentation

Overview

Package absolutepay is the official Go client for the AbsolutePay API.

It signs every request from an app key automatically (HMAC-SHA512) and verifies inbound webhooks. Server-side only — your API key and signing secret must never reach a browser. Zero third-party dependencies (standard library only).

Index

Constants

View Source
const (
	ProductionBaseURL = "https://api.absolutepay.io"
	SandboxBaseURL    = "https://sandbox-api.absolutepay.io"
)

The only public API origins. Anything else must be passed via WithBaseURL.

View Source
const DefaultWebhookTolerance = 5 * time.Minute

DefaultWebhookTolerance is the freshness window enforced on webhook timestamps (replay defense).

Variables

View Source
var ErrInvalidSignature = errors.New("absolutepay: invalid webhook signature")

ErrInvalidSignature is returned by ConstructEvent when a webhook fails signature or freshness verification.

Functions

func VerifySignature

func VerifySignature(secret string, rawBody []byte, timestamp, signature string) bool

VerifySignature reports whether HMAC-SHA512 over "{timestamp}.{rawBody}" with secret matches signature (constant-time).

Types

type Balance

type Balance struct {
	Currency  string `json:"currency"`
	Available string `json:"available"`
	Locked    string `json:"locked"`
}

Balance is one asset balance.

type BalancesService

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

func (*BalancesService) List

func (s *BalancesService) List(ctx context.Context) ([]Balance, error)

List returns every asset balance for the workspace.

func (*BalancesService) Summary

func (s *BalancesService) Summary(ctx context.Context, quote string) (JSON, error)

Summary values the whole balance in one quote currency (default USDT).

type CheckoutParams

type CheckoutParams struct {
	MerchantTradeNo string `json:"merchantTradeNo,omitempty"`
	Amount          Money  `json:"amount"`
	Chain           string `json:"chain"`
	MerchantUserID  int64  `json:"merchantUserId"`
	GoodsName       string `json:"goodsName"`
	TerminalType    string `json:"terminalType,omitempty"`
	ExpiresIn       int    `json:"expiresIn,omitempty"`
	Method          string `json:"method,omitempty"`
}

CheckoutParams is the body for CreateCheckout.

type Client

type Client struct {
	Balances      *BalancesService
	Fees          *FeesService
	Payments      *PaymentsService
	Payouts       *PayoutsService
	Refunds       *RefundsService
	Conversions   *ConversionsService
	Invoices      *InvoicesService
	Subscriptions *SubscriptionsService
	GiftCards     *GiftCardsService
	OffRamp       *OffRampService
	Transactions  *TransactionsService
	// contains filtered or unexported fields
}

Client is the AbsolutePay API client. Construct it once with New and reuse it; each resource service hangs off it.

func New

func New(apiKey string, opts ...Option) (*Client, error)

New builds a Client. apiKey is required (ap_live_ / ap_test_). Options can set the signing secret, sandbox/base URL, and HTTP client.

type ConversionsService

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

func (*ConversionsService) Convert

func (s *ConversionsService) Convert(ctx context.Context, p QuoteParams) (JSON, error)

Convert quotes then executes in one call.

func (*ConversionsService) Execute

Execute runs a previously quoted conversion.

func (*ConversionsService) Quote

Quote previews a conversion (no funds move).

type ConvertExecuteParams

type ConvertExecuteParams struct {
	QuoteID string `json:"quoteId"`
	Sell    Money  `json:"sell"`
	Buy     Money  `json:"buy"`
}

ConvertExecuteParams executes a previously quoted conversion.

type ConvertQuote

type ConvertQuote struct {
	QuoteID      string `json:"quoteId"`
	Rate         string `json:"rate"`
	SellCurrency string `json:"sellCurrency"`
	SellAmount   string `json:"sellAmount"`
	BuyCurrency  string `json:"buyCurrency"`
	BuyAmount    string `json:"buyAmount"`
}

ConvertQuote is a conversion quote.

type DepositParams

type DepositParams struct {
	Currency     string `json:"currency"`
	Chain        string `json:"chain"`
	FullCurrType string `json:"fullCurrType"`
}

DepositParams selects the asset for a hosted-invoice deposit.

type Error

type Error struct {
	Status    int    // HTTP status code (0 for a transport/network failure)
	Code      string // stable, machine-readable code (branch on this)
	Title     string // human-readable summary
	Detail    string // optional extra context
	RequestID string // x-request-id, include it when reporting a problem
}

Error is returned when the API responds with a non-2xx status. It carries the platform's problem+json fields.

func (*Error) Error

func (e *Error) Error() string

func (*Error) IsAuth

func (e *Error) IsAuth() bool

IsAuth reports a 401/403 — bad/insufficient credentials, missing scope, or an invalid request signature.

func (*Error) IsRateLimited

func (e *Error) IsRateLimited() bool

IsRateLimited reports a 429 — back off and retry after a moment.

type Event

type Event struct {
	ID   string          `json:"id"`
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

Event is a delivered callback (the JSON the platform POSTs to your callback URL).

func ConstructEvent

func ConstructEvent(rawBody []byte, headers http.Header, secret string, opts ...EventOption) (*Event, error)

ConstructEvent verifies a callback's signature and freshness and returns the parsed event. Pass the RAW request body, the request headers, and your app's callback secret (whsec_...). Returns ErrInvalidSignature on any failure.

type EventOption

type EventOption func(*eventOptions)

EventOption customizes ConstructEvent.

func WithTolerance

func WithTolerance(d time.Duration) EventOption

WithTolerance sets the freshness window (replay defense). Pass 0 to disable it.

type FeePreview

type FeePreview struct {
	Amount      string      `json:"amount"`
	Currency    string      `json:"currency"`
	PaymentType PaymentType `json:"paymentType"`
	Fee         string      `json:"fee"`
	Net         string      `json:"net"`
	Markup      string      `json:"markup"`
	NetworkFee  string      `json:"networkFee"`
}

FeePreview is the fee breakdown for an amount (network base + account-tier markup).

type FeesService

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

func (*FeesService) Preview

func (s *FeesService) Preview(ctx context.Context, amount, currency string, paymentType PaymentType) (*FeePreview, error)

Preview returns the total fee on an amount for a payment type (default CHECKOUT).

type GiftCardParams

type GiftCardParams struct {
	Title      string `json:"title"`
	TemplateID string `json:"templateId"`
	Amount     Money  `json:"amount"`
}

GiftCardParams issues a gift card.

type GiftCardsService

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

func (*GiftCardsService) Create

func (*GiftCardsService) Get

func (s *GiftCardsService) Get(ctx context.Context, cardNum string) (JSON, error)

func (*GiftCardsService) List

func (s *GiftCardsService) List(ctx context.Context, q PageQuery) (*Page, error)

List returns a keyset-paginated page of issued gift cards (see PageQuery / Page).

func (*GiftCardsService) Templates

func (s *GiftCardsService) Templates(ctx context.Context) (JSON, error)

type InvoiceParams

type InvoiceParams struct {
	Reference     string `json:"reference"`
	Amount        Money  `json:"amount"`
	Description   string `json:"description,omitempty"`
	CustomerEmail string `json:"customerEmail,omitempty"`
	ExpiresAt     int64  `json:"expiresAt,omitempty"`
	Chain         string `json:"chain,omitempty"`
}

InvoiceParams is the body for Create / CreateCheckout. Set Chain on Create to mint the deposit address up front.

type InvoicesService

type InvoicesService struct {

	// Public holds the unauthenticated payer-facing endpoints.
	Public *PublicInvoicesService
	// contains filtered or unexported fields
}

func (*InvoicesService) Create

func (s *InvoicesService) Create(ctx context.Context, p InvoiceParams) (JSON, error)

func (*InvoicesService) CreateCheckout

func (s *InvoicesService) CreateCheckout(ctx context.Context, p InvoiceParams) (JSON, error)

CreateCheckout creates a hosted checkout link (the payer picks the asset).

func (*InvoicesService) List

func (s *InvoicesService) List(ctx context.Context, q PageQuery) (*Page, error)

List returns a keyset-paginated page. Pass a prior page's NextCursor as PageQuery.Before for the next page; NextCursor is nil on the last page.

func (*InvoicesService) Pause

func (s *InvoicesService) Pause(ctx context.Context, token string, paused bool) (JSON, error)

Pause pauses or unpauses an open invoice/link.

func (*InvoicesService) Stats

func (s *InvoicesService) Stats(ctx context.Context) (JSON, error)

func (*InvoicesService) Void

func (s *InvoicesService) Void(ctx context.Context, token string) (JSON, error)

Void makes an invoice/link permanently unpayable.

type JSON

type JSON = map[string]any

JSON is a loosely-typed object returned by endpoints without a dedicated struct.

type Money

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

Money is a decimal-string amount plus a currency code, e.g. Money{Amount: "10.00", Currency: "USDT"}.

type OffRampQuoteParams

type OffRampQuoteParams struct {
	CryptoCurrency string `json:"cryptoCurrency"`
	FiatCurrency   string `json:"fiatCurrency"`
	CryptoAmount   string `json:"cryptoAmount"`
}

OffRampQuoteParams requests a crypto→fiat quote.

type OffRampService

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

func (*OffRampService) Banks

func (s *OffRampService) Banks(ctx context.Context) (JSON, error)

func (*OffRampService) Countries

func (s *OffRampService) Countries(ctx context.Context) (JSON, error)

func (*OffRampService) Orders

func (s *OffRampService) Orders(ctx context.Context, q PageQuery) (*Page, error)

Orders returns a keyset-paginated page of off-ramp orders (see PageQuery / Page).

func (*OffRampService) Quote

func (*OffRampService) Withdraw

type OffRampWithdrawParams

type OffRampWithdrawParams struct {
	QuoteToken     string `json:"quoteToken"`
	BankAccountID  string `json:"bankAccountId"`
	CryptoCurrency string `json:"cryptoCurrency"`
	FiatCurrency   string `json:"fiatCurrency"`
	CryptoAmount   string `json:"cryptoAmount"`
	FiatAmount     string `json:"fiatAmount"`
}

OffRampWithdrawParams executes an off-ramp against a quote + registered bank.

type Option

type Option func(*Client)

Option customizes a Client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the API origin entirely (takes precedence over WithSandbox).

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom *http.Client (timeouts, transport, proxy).

func WithSandbox

func WithSandbox(sandbox bool) Option

WithSandbox targets the public sandbox host instead of production. Ignored when WithBaseURL is also set.

func WithSigningSecret

func WithSigningSecret(secret string) Option

WithSigningSecret sets the request signing secret (apisign_...). Required for app keys — when set, every request is HMAC-signed.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout on the default HTTP client.

type Page

type Page struct {
	Items      []json.RawMessage `json:"items"`
	NextCursor *string           `json:"nextCursor"`
}

Page is one page of a keyset-paginated list. NextCursor is a response-only opaque cursor: pass it back as PageQuery.Before to fetch the next page. It is nil on the last page.

type PageQuery

type PageQuery struct {
	Limit  int    // max items per page (0 = server default)
	Before string // opaque cursor from the previous page's NextCursor
	Status string // optional status filter (endpoint-specific; "" = all)
}

PageQuery holds keyset-pagination options for list endpoints. Before is the previous page's NextCursor; leave it empty for the first page.

type PaymentType

type PaymentType = string

PaymentType enumerates the fee-bearing operation kinds.

const (
	PaymentCheckout     PaymentType = "CHECKOUT"
	PaymentWithdrawal   PaymentType = "WITHDRAWAL"
	PaymentSubscription PaymentType = "SUBSCRIPTION"
	PaymentConversion   PaymentType = "CONVERSION"
	PaymentOffRamp      PaymentType = "OFFRAMP"
	PaymentGiftCard     PaymentType = "GIFTCARD"
)

type PaymentsService

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

func (*PaymentsService) CreateCheckout

func (s *PaymentsService) CreateCheckout(ctx context.Context, p CheckoutParams) (JSON, error)

CreateCheckout creates a pay-in order.

func (*PaymentsService) GetCheckout

func (s *PaymentsService) GetCheckout(ctx context.Context, merchantTradeNo string) (JSON, error)

GetCheckout looks up a checkout by merchant trade number.

type PayoutItem

type PayoutItem struct {
	RecipientAddress string `json:"recipientAddress"`
	Chain            string `json:"chain"`
	Amount           Money  `json:"amount"`
	Memo             string `json:"memo,omitempty"`
}

PayoutItem is one recipient in a batch payout.

type PayoutsService

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

func (*PayoutsService) Create

func (s *PayoutsService) Create(ctx context.Context, items []PayoutItem, opts ...RequestOption) (JSON, error)

Create submits a batch payout. Pass WithIdempotencyKey to make retries safe.

func (*PayoutsService) Get

func (s *PayoutsService) Get(ctx context.Context, id string) (JSON, error)

Get looks up a payout batch by id.

func (*PayoutsService) Options

func (s *PayoutsService) Options(ctx context.Context, currency string) (JSON, error)

Options lists supported chains + per-chain withdraw fee/limits for a currency.

type PlanParams

type PlanParams struct {
	MerchantPlanNo string `json:"merchantPlanNo"`
	Name           string `json:"name"`
	Amount         Money  `json:"amount"`
	Interval       string `json:"interval"`
	IntervalCount  int    `json:"intervalCount"`
	TotalCycles    int    `json:"totalCycles"`
}

PlanParams defines a recurring billing plan.

type PublicInvoicesService

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

PublicInvoicesService holds the unauthenticated payer endpoints (no API key).

func (*PublicInvoicesService) Assets

func (s *PublicInvoicesService) Assets(ctx context.Context, token string) ([]JSON, error)

func (*PublicInvoicesService) Deposit

func (s *PublicInvoicesService) Deposit(ctx context.Context, token string, p DepositParams) (JSON, error)

func (*PublicInvoicesService) Get

func (s *PublicInvoicesService) Get(ctx context.Context, token string) (JSON, error)

func (*PublicInvoicesService) Quote

func (s *PublicInvoicesService) Quote(ctx context.Context, token, currency string) (JSON, error)

func (*PublicInvoicesService) Status

func (s *PublicInvoicesService) Status(ctx context.Context, token string) (JSON, error)

type QuoteParams

type QuoteParams struct {
	SellCurrency string `json:"sellCurrency"`
	BuyCurrency  string `json:"buyCurrency"`
	SellAmount   string `json:"sellAmount,omitempty"`
	BuyAmount    string `json:"buyAmount,omitempty"`
}

QuoteParams requests a conversion quote. Set exactly one of SellAmount / BuyAmount.

type RefundParams

type RefundParams struct {
	MerchantTradeNo string `json:"merchantTradeNo"`
	Amount          Money  `json:"amount"`
	Reason          string `json:"reason,omitempty"`
}

RefundParams is the body for Create.

type RefundsService

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

func (*RefundsService) Create

func (s *RefundsService) Create(ctx context.Context, p RefundParams) (JSON, error)

func (*RefundsService) Get

func (s *RefundsService) Get(ctx context.Context, id string) (JSON, error)

Get looks up a refund by its refundRequestId.

type RequestOption

type RequestOption func(map[string]string)

RequestOption sets per-request extras (e.g. an idempotency key). These headers are merged AFTER signing and are not part of the signed canonical string.

func WithIdempotencyKey

func WithIdempotencyKey(key string) RequestOption

WithIdempotencyKey makes a write retry-safe — the same key returns the original result instead of acting twice.

type SubscribeParams

type SubscribeParams struct {
	MerchantSubNo string `json:"merchantSubNo"`
	PlanNo        string `json:"planNo"`
	CallbackURL   string `json:"callbackUrl,omitempty"`
}

SubscribeParams subscribes a customer to a plan.

type SubscriptionsService

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

func (*SubscriptionsService) Cancel

func (s *SubscriptionsService) Cancel(ctx context.Context, merchantSubNo string) (JSON, error)

func (*SubscriptionsService) Create

func (*SubscriptionsService) CreatePlan

func (s *SubscriptionsService) CreatePlan(ctx context.Context, p PlanParams) (JSON, error)

func (*SubscriptionsService) Deductions

func (s *SubscriptionsService) Deductions(ctx context.Context, merchantSubNo string) (JSON, error)

Deductions returns the per-cycle charge history for a subscription.

func (*SubscriptionsService) List

List returns a keyset-paginated page of subscriptions (see PageQuery / Page).

func (*SubscriptionsService) ListPlans

func (s *SubscriptionsService) ListPlans(ctx context.Context) (JSON, error)

type TransactionsQuery

type TransactionsQuery struct {
	Currency string
	From     int64
	To       int64
	Limit    int
	Offset   int
	Format   string
}

TransactionsQuery filters the ledger. From/To are epoch milliseconds; page with Limit/Offset. Format "csv" returns an export.

type TransactionsService

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

func (*TransactionsService) List

Jump to

Keyboard shortcuts

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