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
- Variables
- func DefaultMaskedHeaders() []string
- func DefaultMaskedJSONFields() []string
- func DefaultMaskedQueryParams() []string
- func SignWebhookPayload(secret string, payload []byte) string
- func VerifyWebhookSignature(secret string, payload []byte, signature string) bool
- type APIError
- type Client
- type Config
- type ConfigError
- type Environment
- type HTTPClient
- type LogConfig
- type LogDepth
- type Option
- func WithBaseURL(baseURL string) Option
- func WithBusinessID(id string) Option
- func WithEnvironment(env Environment) Option
- func WithEnvironmentName(name string) Option
- func WithHTTPClient(client *http.Client) Option
- func WithLogBodyLimit(bytes int) Option
- func WithLogConfig(logConfig LogConfig) Option
- func WithLogDepth(depth LogDepth) Option
- func WithLogLevel(level slog.Level) Option
- func WithLogMaskHeaders(headers ...string) Option
- func WithLogMaskJSONFields(fields ...string) Option
- func WithLogMaskQueryParams(params ...string) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxRetries(n int) Option
- func WithPublicKey(key string) Option
- func WithRetryWait(min, max time.Duration) Option
- func WithSecretKey(key string) Option
- func WithTimeout(d time.Duration) Option
- func WithUserAgent(userAgent string) Option
- func WithWebhookSecret(secret string) Option
- type RequestOption
Constants ¶
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.
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.
const ( SandboxBaseURL = "https://sandboxapi.fincra.com" LiveBaseURL = "https://api.fincra.com" )
Base URLs for the Fincra environments.
const DefaultLogBodyBytes = 2048
DefaultLogBodyBytes caps the body text attached to a log record.
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.
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 ¶
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 ¶
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 ¶
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 ¶
IsAPIError extracts an *APIError from err.
func (*APIError) IsForbidden ¶
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 ¶
IsNotFound reports whether the resource was not found (HTTP 404).
func (*APIError) IsRateLimited ¶
IsRateLimited reports whether the request was throttled (HTTP 429).
func (*APIError) IsServerError ¶
IsServerError reports whether Fincra returned a 5xx status.
func (*APIError) IsUnauthorized ¶
IsUnauthorized reports whether authentication failed (HTTP 401).
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 ¶
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 ¶
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) BusinessID ¶
BusinessID returns the configured default business or sub-account identifier. Resource packages use it when a request omits a business ID.
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 ¶
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 ¶
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 ¶
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 ¶
ResolveBaseURL returns the base URL requests are sent to. An explicit BaseURL wins; otherwise the environment URL is used.
type ConfigError ¶
ConfigError describes an invalid configuration value. It deliberately never carries secret values.
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.
type HTTPClient ¶
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.
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 )
type Option ¶
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 ¶
WithBaseURL overrides the environment base URL. It is mainly useful for tests and proxies.
func WithBusinessID ¶
WithBusinessID sets the default business or sub-account identifier.
func WithEnvironment ¶
func WithEnvironment(env Environment) Option
WithEnvironment selects the Fincra environment.
func WithEnvironmentName ¶
WithEnvironmentName parses name and selects the matching environment.
func WithHTTPClient ¶
WithHTTPClient sets the HTTP client used to perform requests.
func WithLogBodyLimit ¶
WithLogBodyLimit caps the request and response body text attached to a log record. Values <= 0 restore the default limit.
func WithLogConfig ¶
WithLogConfig replaces the client's logging configuration.
func WithLogDepth ¶
WithLogDepth selects how much request and response detail is logged. Use LogDepthNone to disable logging while keeping the logger configured.
func WithLogLevel ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithLogger attaches a slog logger. Logging starts at the configured depth (LogDepthBasic by default); use WithLogDepth(LogDepthNone) to disable it.
func WithMaxRetries ¶
WithMaxRetries sets the number of retries after the initial attempt. Zero disables retries.
func WithPublicKey ¶
WithPublicKey sets the x-pub-key header value used by endpoints such as checkout.
func WithRetryWait ¶
WithRetryWait bounds the exponential backoff between retries.
func WithSecretKey ¶
WithSecretKey sets the api-key credential used to authenticate API calls.
func WithTimeout ¶
WithTimeout bounds a logical API call, including retries.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent header.
func WithWebhookSecret ¶
WithWebhookSecret sets the key used by Client.VerifyWebhookSignature.
type RequestOption ¶
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.
Source Files
¶
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. |