fincra

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fincra-go

An idiomatic Go SDK for the Fincra payments API.

Status: active development. The SDK provides a reusable Go client and resource APIs; it does not orchestrate application-specific payment flows.

Install

go get github.com/1Btln/fincra-go

Requires Go 1.24 or newer. The SDK has no third-party dependencies.

Quick start

package main

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

	fincra "github.com/1Btln/fincra-go"
)

func main() {
	cfg := fincra.DefaultConfig()
	cfg.SecretKey = os.Getenv("FINCRA_SECRET_KEY")
	cfg.BusinessID = os.Getenv("FINCRA_BUSINESS_ID")

	client, err := fincra.NewWithConfig(cfg)
	if err != nil {
		log.Fatal(err)
	}

	wallets, err := client.Balances.ListWallets(context.Background(), "")
	if err != nil {
		log.Fatal(err)
	}

	for _, wallet := range wallets.Data {
		fmt.Printf("%s: available=%f ledger=%f\n",
			wallet.Currency, wallet.AvailableBalance, wallet.LedgerBalance)
	}
}

The environment defaults to sandbox. Point the client at production explicitly:

cfg := fincra.DefaultConfig()
cfg.SecretKey = os.Getenv("FINCRA_SECRET_KEY")
cfg.Environment = fincra.EnvironmentLive

client, err := fincra.NewWithConfig(cfg)

Configuration

A Config object is the primary source of settings. Start from fincra.DefaultConfig() or a literal, set the fields you need, and pass it to fincra.NewWithConfig(cfg, opts...). NewWithConfig never reads the environment, and the config is cloned before use, so the caller's value is never modified.

cfg := fincra.DefaultConfig()
cfg.SecretKey = os.Getenv("FINCRA_SECRET_KEY")
cfg.BusinessID = os.Getenv("FINCRA_BUSINESS_ID")
cfg.Timeout = 20 * time.Second

client, err := fincra.NewWithConfig(cfg)

Environment variables are a fallback, not the primary source:

  • fincra.New(opts...) starts from DefaultConfig, then applies FINCRA_* variables, then options. This is convenient for small programs.
  • cfg.ApplyEnv() fills only fields that are still unset (empty string, zero Environment, Timeout, or MaxRetries). Values already set on Config win.
  • fincra.ConfigFromEnv() builds a complete Config from the environment. It validates the result and fails fast when the secret key is missing.

Precedence depends on the constructor:

  • NewWithConfig: Config fields, then options, then defaults. No environment variables are read.
  • New: defaults, then environment variables, then options.
  • ApplyEnv: explicit Config fields win; environment variables only fill fields that are still unset.
Field Environment variable Default Purpose
SecretKey FINCRA_SECRET_KEY — (required) Sent as api-key. Grants full account access.
PublicKey FINCRA_PUBLIC_KEY empty Sent as x-pub-key. Needed by checkout endpoints.
WebhookSecret FINCRA_WEBHOOK_SECRET empty Verifies inbound webhook signatures.
BusinessID FINCRA_BUSINESS_ID empty Sent as x-business-id; default business/sub-account.
Environment FINCRA_ENVIRONMENT sandbox sandbox/test or live/production.
BaseURL FINCRA_BASE_URL environment URL Override for tests, proxies, or mocks.
HTTPClient — new http.Client Shared, never mutated by the SDK.
Timeout FINCRA_TIMEOUT 30s Bounds one logical call including retries.
MaxRetries FINCRA_MAX_RETRIES 2 Retries after the first attempt.
RetryWaitMin/RetryWaitMax — 500ms/5s Exponential backoff bounds.
UserAgent — fincra-go/<version> Request identification.
Log — disabled LogConfig for slog request logging.

Loading from the environment validates the result and fails fast when the secret key is missing:

cfg, err := fincra.ConfigFromEnv()
if err != nil {
	log.Fatal(err)
}
client, err := fincra.NewWithConfig(cfg)
Credentials

Fincra issues three keys per environment, and sandbox keys do not work in live:

  • Secret key authenticates API requests (api-key).
  • Public key identifies the business (x-pub-key).
  • Webhook secret signs webhook payloads (HMAC-SHA512).

Config.String() redacts all three.

Logging

Logging is built on log/slog and is disabled by default. Attach a logger and choose how much detail to record:

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
	Level: slog.LevelDebug,
}))

client, err := fincra.NewWithConfig(cfg,
	fincra.WithLogger(logger),
	fincra.WithLogLevel(slog.LevelInfo),
	fincra.WithLogDepth(fincra.LogDepthBasic),
)

Depth controls what is attached to a record; Level filters severity. Both the SDK level and the slog handler level must allow a record.

Depth Value Records include
LogDepthNone -1 Nothing, even with a logger configured.
LogDepthBasic 0 Method, URL, status, duration, attempt.
LogDepthHeaders 1 Request and response headers, masked.
LogDepthBody 2 Request and response bodies, masked and truncated.

Credentials are masked at every depth. By default the SDK masks the api-key, x-pub-key, authorization, and cookie headers; credential and personal identifier JSON keys such as password, token, bvn, nin, accountNumber, and bankAccountNumber; and sensitive query parameters such as token and secret. Bodies that are not JSON are never logged in full. Bodies are capped at 2048 bytes by default.

Customise masking or the body limit with WithLogMaskHeaders, WithLogMaskJSONFields, WithLogMaskQueryParams, and WithLogBodyLimit. The mask options add to the secure defaults; use WithLogConfig (or the Log field on Config) to replace a list entirely. The Log field accepts the same settings.

Balances

ctx := context.Background()

// All wallets for the configured business.
wallets, err := client.Balances.ListWallets(ctx, "")

// One wallet by Fincra wallet ID.
wallet, err := client.Balances.GetWallet(ctx, "105146")

// Credits and debits with pagination and filters.
history, err := client.Balances.GetBalanceHistory(ctx, &fincra.BalanceHistoryParams{
	Action:   "debit",
	DateFrom: "2024-01-01",
	DateTo:   "2024-10-10",
	PerPage:  50,
})

// A paginated statement for one currency.
statement, err := client.Balances.GetAccountStatement(ctx, &fincra.AccountStatementParams{
	DateFrom: "2024-01-01",
	DateTo:   "2024-10-31",
	Currency: "NGN",
})

Amounts are decoded as float64 because Fincra mixes integers and decimals. Convert to a decimal type before accounting or persisting balances.

Webhooks

Fincra signs the raw request body with HMAC-SHA512 using the webhook secret and sends the lowercase hex digest in the signature header. Verify before decoding:

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err != nil {
		http.Error(w, "cannot read body", http.StatusBadRequest)
		return
	}

	if !client.VerifyWebhookSignature(payload, r.Header.Get(fincra.WebhookSignatureHeader)) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	// Only now decode and process payload.
}

Re-marshalling a decoded struct changes key order and whitespace and will invalidate the signature. Use fincra.SignWebhookPayload in tests and local mocks.

Errors

Every non-2xx response becomes an *fincra.APIError:

wallets, err := client.Balances.ListWallets(ctx, businessID)
if err != nil {
	var apiErr *fincra.APIError
	if errors.As(err, &apiErr) {
		switch {
		case apiErr.IsUnauthorized():
			// bad or missing api-key
		case apiErr.IsForbidden():
			// IP not whitelisted, or action not permitted
		case apiErr.IsNotFound():
			// unknown resource
		case apiErr.IsRateLimited():
			// back off and retry later
		}
		log.Printf("fincra %s %s failed: %s (request %s)",
			apiErr.Method, apiErr.Path, apiErr.Message, apiErr.RequestID)
	}
	return err
}

Client-side argument problems wrap ErrMissingRequiredParameter or ErrInvalidParameter and can be checked with errors.Is.

Retries

The client retries network errors, 408, 425, 429, 500, 502, 503, and 504 up to MaxRetries with exponential backoff and jitter. A Retry-After header is honoured. POST requests are retried too, so operations that are not safe to repeat should carry a caller-generated unique reference; Fincra rejects duplicate customer references for payouts and charges.

Tune the policy globally:

client, err := fincra.New(
	fincra.WithSecretKey(key),
	fincra.WithTimeout(20*time.Second),
	fincra.WithMaxRetries(0),
)

Advanced usage

Client.Do is available for endpoints this SDK does not yet wrap. It applies authentication, headers, retries, and error mapping:

var out struct {
	Data []fincra.Wallet `json:"data"`
}
err := client.Do(ctx, http.MethodGet, "/wallets?businessID="+url.QueryEscape(id), nil, &out)

Resource services use an internal verb-oriented HTTP client backed by the same request pipeline. Use Client.Do for requests that do not have a service method.

Per-request headers, such as a sub-account override, can be supplied with fincra.WithRequestHeader.

For safety, absolute URLs are only accepted on the configured origin and cross-host redirects are rejected, so the api-key header cannot be forwarded to an unexpected host.

Project layout

.
├── client.go          Public client and shared HTTP engine
├── config.go          Public configuration and environment fallback
├── options.go         Public functional options
├── environment.go     Public sandbox/live environment values
├── errors.go          Public API and validation error types
├── logging.go         Public slog settings and private logging helpers
├── webhook.go         Webhook signing and signature verification
├── webhook/           Event names, typed payloads, and signature helpers
├── account/           Business, banks, account resolution, BVN
├── balances/          Wallets, history, statements, top-ups
├── beneficiaries/     Saved-recipient management
├── checkout/          Hosted checkout and fee calculation
├── collections/       Deposits, refunds, chargebacks
├── conversions/       FX rates, quotes, wallet conversion
├── directcharge/      Card, bank-transfer, mobile-money, EFT charges
├── mandates/          Direct-debit mandates
├── payouts/           Disbursements and transfers
├── virtualaccounts/   Permanent, temporary, and BVN virtual-account lookup
├── internal/api/      Shared validation and request helpers
├── internal/httpclient/ Verb adapter used by resource services
├── test/              External (fincra_test) tests
└── .github/           CI workflow

New resources should follow the same shape: a XxxService field on Client, typed request/response structs, methods that build a relative path, and a call through the injected verb-based HTTP client.

Roadmap

  • Client core, configuration, retries, errors, webhooks
  • Balances
  • Structured slog logging with configurable depth and masking
  • Business information and rates
  • Quotes and conversions
  • Checkout and direct charges
  • Virtual accounts and deposits
  • Payouts, beneficiaries, and transfers
  • Refunds, chargebacks, and mandates
  • Webhook event types and payload structs

Conversion listing and status lookup, BVN virtual-account lookup, charge OTP resend, mandate listing, and typed stablecoin payout beneficiary fields are available on their existing services. Virtual-account responses expose nested account information, including CAD Interac aliases.

Webhook payloads can be decoded with webhook.WebhookEnvelope[T], using the matching payload type such as webhook.PayoutWebhookData or webhook.CollectionWebhookData after verifying the signature against the untouched raw request body. Root-level signature helpers remain available for compatibility.

Development

make check      # gofmt, vet, tests
make test-race  # race detector
make cover      # coverage report

All tests and runnable examples live in test/ as the external fincra_test package. Please add an httptest contract test for every endpoint, covering the request path, query parameters, headers, success decoding, and API error mapping.

See CONTRIBUTING.md for the contribution workflow and SECURITY.md for reporting vulnerabilities.

Operational notes

  • IP whitelisting. Fincra rejects requests from non-whitelisted server IPs with HTTP 403. Configure this in the dashboard; it cannot be done from the SDK.
  • Sandbox isolation. Sandbox accounts, keys, balances, and webhook settings are separate from live and never carry over.
  • Balance history wire format. Fincra documents GET /wallets/logs with a JSON request body. This SDK sends those fields as query parameters because GET bodies are not reliably forwarded by proxies. Use Client.Do directly if you need to mirror the documented form exactly.
  • Money. Use decimal arithmetic for accounting; float64 is only the transport representation.

License

MIT. See LICENSE.

Documentation

Overview

Package fincra provides an idiomatic Go client for the Fincra payments API.

The client supports the two Fincra environments: the sandbox used for testing (https://sandboxapi.fincra.com) and live production (https://api.fincra.com). Sandbox is the default so that a misconfigured client never moves real money.

The primary way to configure a client is to build a Config and pass it to NewWithConfig. A Config object is authoritative and is never read from the environment implicitly:

cfg := fincra.DefaultConfig()
cfg.SecretKey = os.Getenv("FINCRA_SECRET_KEY")
cfg.BusinessID = "64f1c9ef838af8cda0211d9d"

client, err := fincra.NewWithConfig(cfg)
if err != nil {
	return err
}

client.Balances.ListWallets(ctx, "")

New is a convenience constructor that starts from DefaultConfig, fills unset fields from FINCRA_* environment variables, and then applies functional options. Options always win. Config.ApplyEnv is available when a Config is partly populated and only missing values should come from the environment; ConfigFromEnv builds a complete Config from the environment alone.

Logging uses log/slog and is disabled by default. Configure Client.Log or use WithLogger and, optionally, WithLogDepth and WithLogLevel. Depth controls how much detail is attached (basic request information, headers, or bodies), while Level filters severity. Credentials and configured sensitive fields are masked at every depth.

Fincra requires the originating server IP to be whitelisted in the dashboard. IP whitelisting is an account-level setting and cannot be configured here.

Index

Constants

View Source
const (
	// DefaultTimeout bounds a single logical API call, including retries.
	DefaultTimeout = 30 * time.Second

	// DefaultMaxRetries is the number of retries after the initial attempt.
	DefaultMaxRetries = 2

	// DefaultRetryWaitMin and DefaultRetryWaitMax bound the exponential
	// backoff delay between retries.
	DefaultRetryWaitMin = 500 * time.Millisecond
	DefaultRetryWaitMax = 5 * time.Second

	// DefaultUserAgent identifies this SDK to Fincra.
	DefaultUserAgent = "fincra-go/" + Version
)

Defaults applied by DefaultConfig, New, and NewWithConfig.

View Source
const (
	EnvSecretKey     = "FINCRA_SECRET_KEY"
	EnvPublicKey     = "FINCRA_PUBLIC_KEY"
	EnvWebhookSecret = "FINCRA_WEBHOOK_SECRET"
	EnvBusinessID    = "FINCRA_BUSINESS_ID"
	EnvEnvironment   = "FINCRA_ENVIRONMENT"
	EnvBaseURL       = "FINCRA_BASE_URL"
	EnvTimeout       = "FINCRA_TIMEOUT"
	EnvMaxRetries    = "FINCRA_MAX_RETRIES"
)

Environment variables read by ConfigFromEnv.

View Source
const (
	SandboxBaseURL = "https://sandboxapi.fincra.com"
	LiveBaseURL    = "https://api.fincra.com"
)

Base URLs for the Fincra environments.

View Source
const DefaultLogBodyBytes = 2048

DefaultLogBodyBytes caps the body text attached to a log record.

View Source
const Version = "0.1.0"

Version is the semantic version of this SDK. It is sent in the User-Agent header and should match the released git tag.

View Source
const WebhookSignatureHeader = webhook.SignatureHeader

WebhookSignatureHeader is the header Fincra uses for the HMAC-SHA512 signature of a webhook payload. Header lookups are case-insensitive in net/http.

Variables

View Source
var (
	// ErrMissingRequiredParameter is wrapped by client-side validation errors
	// caused by a missing required argument.
	ErrMissingRequiredParameter = api.ErrMissingRequiredParameter

	// ErrInvalidParameter is wrapped by client-side validation errors caused by
	// a malformed argument.
	ErrInvalidParameter = api.ErrInvalidParameter
)

Functions

func DefaultMaskedHeaders

func DefaultMaskedHeaders() []string

DefaultMaskedHeaders returns the header names masked by default.

func DefaultMaskedJSONFields

func DefaultMaskedJSONFields() []string

DefaultMaskedJSONFields returns the JSON keys masked by default. The list covers credentials, one-time secrets, and strong personal identifiers.

func DefaultMaskedQueryParams

func DefaultMaskedQueryParams() []string

DefaultMaskedQueryParams returns the query parameter names masked by default.

func SignWebhookPayload

func SignWebhookPayload(secret string, payload []byte) string

SignWebhookPayload returns the lowercase hex HMAC-SHA512 of payload using secret. It is exposed so tests and local mocks can produce signatures that match Fincra's.

func VerifyWebhookSignature

func VerifyWebhookSignature(secret string, payload []byte, signature string) bool

VerifyWebhookSignature reports whether signature is the HMAC-SHA512 of the raw payload under secret.

Pass the raw request body exactly as received. Re-marshalling a decoded struct changes key order and whitespace, which invalidates the signature.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status code.
	StatusCode int

	// Method and Path identify the failed request. Path includes the query
	// string but never the request body.
	Method string
	Path   string

	// Message is the human-readable message reported by Fincra. Fincra uses
	// both "error" and "message" fields depending on the endpoint.
	Message string

	// ErrorType is Fincra's machine-readable error category, such as
	// RESOURCE_NOT_FOUND, when supplied.
	ErrorType string

	// Details is the raw "errors" field from the response. Fincra encodes it
	// as a string on some endpoints and as an array or object on others.
	Details json.RawMessage

	// RequestID is the value of the x-request-id response header, when present.
	// Include it when reporting issues to Fincra support.
	RequestID string

	// Body is the raw response body, capped by the client response limit.
	Body []byte

	// Retryable reports whether the client considered this status retryable.
	Retryable bool

	// Err is the underlying transport, read, or decode error, when applicable.
	Err error
}

APIError is returned when Fincra responds with a non-2xx status code. It is compatible with errors.As:

var apiErr *fincra.APIError
if errors.As(err, &apiErr) && apiErr.IsNotFound() {
	// handle a missing resource
}

func IsAPIError

func IsAPIError(err error) (*APIError, bool)

IsAPIError extracts an *APIError from err.

func (*APIError) Error

func (e *APIError) Error() string

Error implements error.

func (*APIError) IsForbidden

func (e *APIError) IsForbidden() bool

IsForbidden reports whether the request was denied (HTTP 403). Fincra also returns 403 when the caller's IP address is not whitelisted.

func (*APIError) IsNotFound

func (e *APIError) IsNotFound() bool

IsNotFound reports whether the resource was not found (HTTP 404).

func (*APIError) IsRateLimited

func (e *APIError) IsRateLimited() bool

IsRateLimited reports whether the request was throttled (HTTP 429).

func (*APIError) IsServerError

func (e *APIError) IsServerError() bool

IsServerError reports whether Fincra returned a 5xx status.

func (*APIError) IsUnauthorized

func (e *APIError) IsUnauthorized() bool

IsUnauthorized reports whether authentication failed (HTTP 401).

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the underlying error, if any.

type Client

type Client struct {

	// HTTPClient exposes the authenticated HTTP verbs for endpoints not yet
	// covered by a resource service.
	HTTPClient HTTPClient

	// Account exposes business, merchant, bank, account-resolution, and BVN
	// endpoints.
	Account *account.Service

	// Balances exposes wallet, balance history, statement, and top-up
	// endpoints.
	Balances *balances.Service

	// Beneficiaries exposes saved-recipient management endpoints.
	Beneficiaries *beneficiaries.Service

	// Checkout exposes hosted checkout and fee-calculation endpoints.
	Checkout *checkout.Service

	// Collections exposes deposits, refunds, and chargeback endpoints.
	Collections *collections.Service

	// Conversions exposes FX conversions, quotes, and treasury rates.
	Conversions *conversions.Service

	// DirectCharge exposes card, bank-transfer, and mobile-money charge
	// endpoints.
	DirectCharge *directcharge.Service

	// Mandates exposes direct-debit mandate endpoints.
	Mandates *mandates.Service

	// Payouts exposes disbursement and Fincra-to-Fincra transfer endpoints.
	Payouts *payouts.Service

	// VirtualAccounts exposes permanent virtual-account endpoints.
	VirtualAccounts *virtualaccounts.Service
	// contains filtered or unexported fields
}

Client is a Fincra API client. It is safe for concurrent use by multiple goroutines once constructed.

func New

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

New returns a Client configured from DefaultConfig, then FINCRA_* environment variables, then opts. Options always win.

Environment variables are only a fallback for callers that do not build a Config. Use NewWithConfig when configuration comes from your own object or configuration system. At minimum a secret key is required from one of the three sources:

client, err := fincra.New(fincra.WithSecretKey(os.Getenv("FINCRA_SECRET_KEY")))

func NewWithConfig

func NewWithConfig(cfg *Config, opts ...Option) (*Client, error)

NewWithConfig returns a Client based on cfg plus opts. cfg is cloned before defaults and options are applied, so the caller's Config is not modified.

This is the primary constructor: it never reads the environment. To use environment variables as a fallback for unset fields, call cfg.ApplyEnv before passing it here.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the base URL requests are sent to.

func (*Client) BusinessID

func (c *Client) BusinessID() string

BusinessID returns the configured default business or sub-account identifier. Resource packages use it when a request omits a business ID.

func (*Client) Config

func (c *Client) Config() Config

Config returns a copy of the client configuration. Logging mask slices are copied so callers cannot mutate the running client.

func (*Client) VerifyWebhookSignature

func (c *Client) VerifyWebhookSignature(payload []byte, signature string) bool

VerifyWebhookSignature verifies a signature using the client's configured WebhookSecret. It returns false when no webhook secret is configured.

type Config

type Config struct {
	// SecretKey authenticates API calls through the "api-key" header. It grants
	// full access to the account and must never be exposed to untrusted code.
	// Required.
	SecretKey string

	// PublicKey identifies the business through the "x-pub-key" header. It is
	// only needed by endpoints that explicitly ask for it, such as checkout.
	// Safe to publish.
	PublicKey string

	// WebhookSecret verifies inbound webhook signatures. Fincra signs the raw
	// request body with HMAC-SHA512 using this key.
	WebhookSecret string

	// BusinessID is sent as the "x-business-id" header and used as the default
	// business for endpoints that accept a business identifier. For sub-account
	// integrations set the sub-account ID; otherwise use the parent business ID.
	BusinessID string

	// Environment selects the Fincra environment. Empty means sandbox.
	Environment Environment

	// BaseURL overrides the environment base URL. It is primarily useful for
	// tests, proxies, and local mocks. When empty, Environment.BaseURL is used.
	BaseURL string

	// HTTPClient performs requests. When nil a new http.Client is used. The
	// client is shared, not mutated, and its Transport is left untouched.
	HTTPClient *http.Client

	// Timeout bounds a logical call, including retries. Zero uses
	// DefaultTimeout. Cancellation of the supplied context also applies.
	Timeout time.Duration

	// MaxRetries is the number of retries after the initial attempt for
	// retryable failures. Zero disables retries.
	MaxRetries int

	// RetryWaitMin and RetryWaitMax bound exponential backoff. Zero values use
	// DefaultRetryWaitMin and DefaultRetryWaitMax.
	RetryWaitMin time.Duration
	RetryWaitMax time.Duration

	// UserAgent is sent with every request. Empty uses DefaultUserAgent.
	UserAgent string

	// Log controls structured request logging. Logging is disabled when
	// Log.Logger is nil or Log.Depth is LogDepthNone.
	Log LogConfig
}

Config controls a Client.

A Config object is the primary source of settings. Construct a Config literal (or start from DefaultConfig), pass it to NewWithConfig, and set anything you need directly. Environment loading is an optional fallback: call ConfigFromEnv when there is no Config at all, or Config.ApplyEnv to fill only the fields you left unset.

NewWithConfig copies the Config before applying defaults and options, so the caller's value is never mutated.

func ConfigFromEnv

func ConfigFromEnv() (*Config, error)

ConfigFromEnv builds a Config from FINCRA_* environment variables, applies defaults, and validates the result.

This is a fallback helper for programs that do not construct a Config. Prefer setting fields on Config directly and passing it to NewWithConfig; use Config.ApplyEnv when only some fields should come from the environment.

Recognised variables are the Env* constants in this package. An error is returned when a variable is malformed or when the required secret key is missing.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config populated with safe defaults. The environment is sandbox and no credentials are set.

func (*Config) ApplyEnv

func (c *Config) ApplyEnv() error

ApplyEnv fills configuration fields that are still unset with values from FINCRA_* environment variables.

It is a fallback helper: values already set on Config win, so environment variables only fill the gaps. Fields considered unset are empty strings, a zero Environment, a zero Timeout, and a zero MaxRetries. Apply defaults by passing the Config to NewWithConfig afterwards.

ApplyEnv does not validate the result; NewWithConfig does that.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a copy of the Config. The HTTPClient pointer is shared, while the logging mask lists are copied so later changes cannot affect the client.

func (*Config) ResolveBaseURL

func (c *Config) ResolveBaseURL() string

ResolveBaseURL returns the base URL requests are sent to. An explicit BaseURL wins; otherwise the environment URL is used.

func (Config) String

func (c Config) String() string

String implements fmt.Stringer with credentials redacted.

func (*Config) Validate

func (c *Config) Validate() error

Validate reports whether the configuration can be used to build a Client.

SecretKey is required. Environment may be empty (sandbox). BaseURL, when set, must be an absolute http or https URL.

type ConfigError

type ConfigError struct {
	Field  string
	Value  string
	Reason string
}

ConfigError describes an invalid configuration value. It deliberately never carries secret values.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements error.

type Environment

type Environment string

Environment identifies the Fincra API environment a Client talks to.

const (
	// EnvironmentSandbox is Fincra's isolated test environment. No real money
	// moves. Sandbox accounts, keys, and webhooks are separate from live.
	EnvironmentSandbox Environment = "sandbox"

	// EnvironmentLive is Fincra's production environment.
	EnvironmentLive Environment = "live"
)

func ParseEnvironment

func ParseEnvironment(s string) (Environment, error)

ParseEnvironment normalises an environment name into an Environment.

It accepts "sandbox"/"test" for the sandbox and "live"/"production" for live. Matching is case-insensitive and surrounding whitespace is ignored.

func (Environment) BaseURL

func (e Environment) BaseURL() string

BaseURL returns the public API base URL for the environment.

Unknown or empty environments resolve to the sandbox so that a zero-value configuration cannot accidentally target production.

func (Environment) String

func (e Environment) String() string

String implements fmt.Stringer.

type HTTPClient

type HTTPClient = api.Backend

HTTPClient is the shared authenticated HTTP interface available on Client. It exposes the standard verbs while keeping the SDK's request pipeline private.

type LogConfig

type LogConfig struct {
	// Logger receives records. Pass a slog logger configured with the handler
	// and destination you want.
	Logger *slog.Logger

	// Level is the minimum record severity emitted by the SDK. The zero value
	// is slog.LevelInfo.
	//
	// The SDK emits request outcomes at Info (Warn for 5xx, transport failures,
	// and malformed responses) and retry decisions at Debug.
	Level slog.Level

	// Depth selects how much request and response detail is attached.
	Depth LogDepth

	// MaskHeaders lists header names whose values are replaced with
	// "[REDACTED]". Matching is case-insensitive. A nil slice uses
	// DefaultMaskedHeaders; an empty non-nil slice disables header masking.
	MaskHeaders []string

	// MaskJSONFields lists JSON object keys whose values are replaced with
	// "[REDACTED]" in logged request and response bodies. Matching is
	// case-insensitive. A nil slice uses DefaultMaskedJSONFields; an empty
	// non-nil slice disables field masking.
	MaskJSONFields []string

	// MaskQueryParams lists URL query parameter names whose values are replaced
	// with "[REDACTED]" in logged URLs. Matching is case-insensitive. A nil
	// slice uses DefaultMaskedQueryParams; an empty non-nil slice disables query
	// masking.
	MaskQueryParams []string

	// MaxBodyBytes truncates logged bodies. Zero uses DefaultLogBodyBytes.
	MaxBodyBytes int
}

LogConfig controls structured logging.

Logging is disabled when Logger is nil or Depth is LogDepthNone. The zero value is safe: Level defaults to slog.LevelInfo, Depth to LogDepthBasic, and the default masking lists are applied by New and NewWithConfig.

func (LogConfig) Clone

func (l LogConfig) Clone() LogConfig

Clone returns a copy of the LogConfig with independent mask slices.

type LogDepth

type LogDepth int

LogDepth controls how much request and response detail the client logs.

Depth is deliberately separate from Level: Level filters severity, while Depth decides which attributes are attached to a record. Credentials and configured sensitive fields are masked at every depth.

const (
	// LogDepthNone disables logging even when a Logger is configured.
	LogDepthNone LogDepth = -1

	// LogDepthBasic logs one record per request with method, URL, status,
	// duration, and attempt number.
	LogDepthBasic LogDepth = 0

	// LogDepthHeaders adds request and response headers, with sensitive header
	// values masked.
	LogDepthHeaders LogDepth = 1

	// LogDepthBody adds request and response bodies, with configured JSON
	// fields masked and bodies truncated to LogConfig.MaxBodyBytes.
	LogDepthBody LogDepth = 2
)

func (LogDepth) String

func (d LogDepth) String() string

String implements fmt.Stringer.

type Option

type Option func(*Config) error

Option customises a Config when passed to New or NewWithConfig. Options are applied in order after DefaultConfig (for New) or after the supplied Config (for NewWithConfig), so an option always wins.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the environment base URL. It is mainly useful for tests and proxies.

func WithBusinessID

func WithBusinessID(id string) Option

WithBusinessID sets the default business or sub-account identifier.

func WithEnvironment

func WithEnvironment(env Environment) Option

WithEnvironment selects the Fincra environment.

func WithEnvironmentName

func WithEnvironmentName(name string) Option

WithEnvironmentName parses name and selects the matching environment.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the HTTP client used to perform requests.

func WithLogBodyLimit

func WithLogBodyLimit(bytes int) Option

WithLogBodyLimit caps the request and response body text attached to a log record. Values <= 0 restore the default limit.

func WithLogConfig

func WithLogConfig(logConfig LogConfig) Option

WithLogConfig replaces the client's logging configuration.

func WithLogDepth

func WithLogDepth(depth LogDepth) Option

WithLogDepth selects how much request and response detail is logged. Use LogDepthNone to disable logging while keeping the logger configured.

func WithLogLevel

func WithLogLevel(level slog.Level) Option

WithLogLevel sets the minimum severity emitted by the SDK. The slog handler's own level is applied as well, so both must allow a record.

func WithLogMaskHeaders

func WithLogMaskHeaders(headers ...string) Option

WithLogMaskHeaders adds header names whose values are masked. Matching is case-insensitive. Default masks are kept, so adding a custom header cannot accidentally expose credentials. Use WithLogConfig to replace the list.

func WithLogMaskJSONFields

func WithLogMaskJSONFields(fields ...string) Option

WithLogMaskJSONFields adds JSON object keys whose values are masked in logged bodies. Matching is case-insensitive. Default masks are kept, so adding a field cannot accidentally expose credentials. Use WithLogConfig to replace the list.

func WithLogMaskQueryParams

func WithLogMaskQueryParams(params ...string) Option

WithLogMaskQueryParams adds query parameter names whose values are masked in logged URLs. Matching is case-insensitive. Default masks are kept, so adding a parameter cannot accidentally expose credentials. Use WithLogConfig to replace the list.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger attaches a slog logger. Logging starts at the configured depth (LogDepthBasic by default); use WithLogDepth(LogDepthNone) to disable it.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the number of retries after the initial attempt. Zero disables retries.

func WithPublicKey

func WithPublicKey(key string) Option

WithPublicKey sets the x-pub-key header value used by endpoints such as checkout.

func WithRetryWait

func WithRetryWait(min, max time.Duration) Option

WithRetryWait bounds the exponential backoff between retries.

func WithSecretKey

func WithSecretKey(key string) Option

WithSecretKey sets the api-key credential used to authenticate API calls.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds a logical API call, including retries.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent overrides the User-Agent header.

func WithWebhookSecret

func WithWebhookSecret(secret string) Option

WithWebhookSecret sets the key used by Client.VerifyWebhookSignature.

type RequestOption

type RequestOption = func(*http.Request)

RequestOption customises an individual request before it is sent.

It is an alias for func(*http.Request) so resource packages can define small backend interfaces without importing this package.

func WithRequestHeader

func WithRequestHeader(key, value string) RequestOption

WithRequestHeader sets a header on a single request, overriding any default value for the same header.

Directories

Path Synopsis
Package account exposes Fincra business, merchant, bank, account-resolution, and BVN verification endpoints.
Package account exposes Fincra business, merchant, bank, account-resolution, and BVN verification endpoints.
Package balances exposes Fincra wallet, balance-history, statement, and top-up endpoints.
Package balances exposes Fincra wallet, balance-history, statement, and top-up endpoints.
Package beneficiaries exposes Fincra's saved-recipient management endpoints.
Package beneficiaries exposes Fincra's saved-recipient management endpoints.
Package checkout exposes Fincra hosted-checkout endpoints.
Package checkout exposes Fincra hosted-checkout endpoints.
Package collections exposes Fincra deposit, refund, and chargeback endpoints.
Package collections exposes Fincra deposit, refund, and chargeback endpoints.
Package conversions exposes Fincra FX rates, quote, and conversion endpoints.
Package conversions exposes Fincra FX rates, quote, and conversion endpoints.
Package directcharge exposes Fincra's payment-method charge endpoints.
Package directcharge exposes Fincra's payment-method charge endpoints.
internal
api
Package api holds helpers shared by the Fincra resource packages.
Package api holds helpers shared by the Fincra resource packages.
httpclient
Package httpclient provides the authenticated verb-oriented request interface used by resource services and SDK callers.
Package httpclient provides the authenticated verb-oriented request interface used by resource services and SDK callers.
Package mandates exposes Fincra direct-debit mandate endpoints.
Package mandates exposes Fincra direct-debit mandate endpoints.
Package payouts exposes Fincra disbursement, payout-status, document-upload, and Fincra-to-Fincra transfer endpoints.
Package payouts exposes Fincra disbursement, payout-status, document-upload, and Fincra-to-Fincra transfer endpoints.
Package virtualaccounts exposes Fincra virtual-account endpoints.
Package virtualaccounts exposes Fincra virtual-account endpoints.
Package webhook provides Fincra webhook event types and signature helpers.
Package webhook provides Fincra webhook event types and signature helpers.

Jump to

Keyboard shortcuts

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