manza

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 16 Imported by: 0

README

manza-go

Go SDK for the Manza API.

go get github.com/getmanza/manza-go
import manza "github.com/getmanza/manza-go"

client, err := manza.New(manza.WithAPIKey(os.Getenv("MANZA_API_KEY")))
if err != nil { ... }

entity, err := client.Entity.Get(ctx)

page, err := client.Accounts.List(ctx, manza.AccountListParams{})
for _, account := range page.Data {
    fmt.Println(account["id"], account["name"])
}

// Initiate a transfer (a payment). Creating one never executes it: it goes
// to your enrolled transfer authorizer or to your in-app approvers.
payment, err := client.Payments.Create(ctx, manza.Attributes{
    "account_id":        accountID,
    "beneficiary_id":    beneficiaryID,
    "amount":            "150.00",
    "payment_reference": "INV-000042",
})

Response shape

Response bodies are returned as-is from the API — snake_case keys in a map[string]any (resp.Body). The same shape ships across every Manza SDK (Ruby, TypeScript, Python, Go, ...) so the cassette contract is one-to-one.

For typed access, decode the raw body onto a model from types.go (TransferDraft, Authorization, TransferAuthorizer, Beneficiary, ExternalAccount, PayeeTrustRequest, CheckoutSession, PaymentLink, Customer, Invoice):

var draft manza.TransferDraft
if err := resp.Decode(&draft); err != nil { ... }

Market-gated keys (tax_id, ice_number, delivery_date) are absent outside Morocco, so they are pointers and nil there.

Hosts

Market Base URL
Morocco (default) https://ma.manza.finance
South Africa https://za.manza.finance

Override with manza.WithBaseURL(...) or MANZA_BASE_URL (the legacy ZAZU_BASE_URL still works, with a one-time deprecation warning). The replay cassettes were recorded against https://ma.manza.dev (the staging host).

Resources

Service Methods
Accounts List, Get, ListTransactions, GetTransaction
Beneficiaries List, Get, Create, ListExternalAccounts, GetExternalAccount, CreateExternalAccount
CheckoutSessions Create, Get
Customers List, Get, Create, Update, Delete
Entity Get
Invoices List, Get, Create, Update, Send, MarkAsPaid, Cancel, CreditNote, Delete, CreatePaymentLink
PayeeTrustRequests Create(ctx, externalAccountIDs), Get
PaymentLinks List, Get, Create, Cancel
Payments Create, Get (authorization: status, refusal_reason), Authorize, Decline
TransferAuthorizer Get (status, suspension_reason, limits, daily_authorized_total; a not-found *manza.Error when none is enrolled)
TransferDrafts Deprecated alias of Payments (the same service; it calls /api/payments)
WebhookEndpoints List, Get, Create, Update, Delete, Test, RegenerateSecret, Enable, Disable

Machine-authorized transfers

A payment inside your entity's authorization envelope (trusted payee, or a new one when you allow it, within limits) is sent to your enrolled authorizer endpoint as a payment.authorization_requested webhook carrying an authorization.id and a one-time nonce. Your system checks it against its own ledger, signs it and authorizes it with a different API key from the one that created it. examples/transfer_authorizer/ runs the whole flow; the transfer authorization docs explain every step.

Setup, step by step
  1. Feature flags. Ask support to enable API transfers and transfer authorization (release_api_webhook_authorization) on your workspace.

  2. Two API keys. Key A creates payments (transfers:write; beneficiaries:request_trust for step 6; entity:read, accounts:read, webhook_endpoints:read and beneficiaries:read for the preflight in step 7). Key B answers the challenges (transfers:authorize). The creating key is always refused with 403 same_key_forbidden, so keep key B and the signing secret on the system that holds your ledger. Bind key B to an IP allowlist: authorizing from a key without one is refused with 403 unrestricted_api_key. Bind key A to one too if you allow new payees (step 6): a payment to a new payee from a key without an allowlist goes to your approvers (unrestricted_api_key).

  3. A stable public URL. Your authorizer needs an HTTPS URL that never changes: an enrolled endpoint's URL is locked. Use a reserved ngrok domain (ngrok http --url=your-name.ngrok.app 4599) or a named Cloudflare tunnel. Never a free ngrok URL: it changes on every restart.

  4. Create the webhook endpoint at that URL:

    _, err := client.WebhookEndpoints.Create(ctx, manza.Attributes{
        "url":    "https://your-name.ngrok.app/",
        "events": []string{"transfer.executed"},
    })
    
  5. Enrol it in the app: Settings → Developer → Transfer approval. Pick the endpoint, the currency and both limits, confirm with your two-factor code, and copy the signing secret: it is shown once.

  6. Allow new payees, or trust each payee. Turn on Approve transfers to new payees at enrolment (or later, same page, with your two-factor code) and set the Limit per transfer to a new payee. Your authorizer may then approve a transfer to bank details your workspace never trusted, up to that limit, and its signature trusts them: the webhook's payment.payee_trusted is false for such a transfer. Bank details whose trust was revoked, or that were edited after trusting, still go to your approvers. Without the option, an approver marks the beneficiary's bank account as trusted from the Beneficiaries list, or you ask them to:

    _, err := client.PayeeTrustRequests.Create(ctx, []string{"01a1..."})
    

    Trusted on the ExternalAccount from client.Beneficiaries.GetExternalAccount says which it is. The API does not show whether the option is on.

  7. Run the preflight, then the example (from examples/transfer_authorizer/, after filling in .env): go run ./cmd/preflight checks what the API shows of steps 1–6 and prints a fix for each that fails. What it cannot see, check by hand: that key B is bound to an IP allowlist, and, for a payee not trusted yet, that Approve transfers to new payees is on and key A is bound to an IP allowlist too (it warns, it does not fail). Then go run ./cmd/authorizer in one terminal, go run ./cmd/create_transfer in another.

  8. Troubleshooting: a payment that goes to your approvers instead has an authorization with status refused and a refusal_reason (cmd/create_transfer prints it in words); client.TransferAuthorizer.Get shows a suspension and its suspension_reason. An authorize answered 409 authorization_busy (a bank-detail edit, trust or trust revocation on the same payee was in flight) is safe to retry. The reasons, and an API error's Type, are in the transfer authorization docs.

Verifying the webhook

Pass the raw request body, never re-serialized JSON. manza.ConstructWebhookEvent reads X-Manza-Signature and X-Manza-Timestamp (names in any case, the CGI HTTP_X_MANZA_* form, or the legacy X-Zazu-* names), checks the signature in constant time and the timestamp within 5 minutes, and returns the parsed event (a map[string]any). It returns a *manza.ArgumentError otherwise:

func handle(w http.ResponseWriter, r *http.Request) {
    // Cap the body: it is read before the signature can be checked.
    body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
    var tooLarge *http.MaxBytesError
    if errors.As(err, &tooLarge) {
        w.WriteHeader(http.StatusRequestEntityTooLarge)
        return
    } else if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    event, err := manza.ConstructWebhookEvent(body, r.Header, signingSecret)
    if err != nil { // *manza.ArgumentError: "invalid webhook signature", ...
        http.Error(w, err.Error(), http.StatusUnauthorized)
        return
    }
    w.WriteHeader(http.StatusOK) // respond first: the delivery has a timeout
    if event["event"] == "payment.authorization_requested" {
        go answer(event) // check your ledger, sign and authorize (see below)
    }
}

manza.VerifyWebhook(payload, signature, timestamp, secret) returns a bool instead, and manza.SignWebhook builds a signature for tests. Both verifiers take options: manza.WithWebhookTolerance(d) changes the 5 minutes, and manza.WithoutWebhookTolerance() skips the timestamp check. Use the latter only to replay a captured delivery in a local tool or test, never on a live endpoint: without the check, anyone holding a captured delivery can replay it.

Signing the challenge

Sign the payment from your own record of it (not the webhook's signature_input, which is there only to compare against) with the endpoint's signing secret, and answer with key B:

// payment is a manza.TransferDraft (decoded via resp.Decode) or your own record.
// Its ExternalAccountID, DestinationAccountID and ClientReference are *string:
// exactly one of the first two is set, and ClientReference is nil for a
// transfer without a client_reference.
externalAccountID, destinationAccountID := "", ""
if payment.ExternalAccountID != nil {
    externalAccountID = *payment.ExternalAccountID
}
if payment.DestinationAccountID != nil {
    destinationAccountID = *payment.DestinationAccountID
}
payee, err := manza.PayeeFor(externalAccountID, destinationAccountID)
if err != nil {
    return err
}
clientReference := ""
if payment.ClientReference != nil {
    clientReference = *payment.ClientReference
}
input := manza.SignatureInput(manza.TransferAuthorizationFields{
    PaymentID:       payment.ID,
    Nonce:           nonce, // data.authorization.nonce from the webhook
    Amount:          payment.Amount, // the API's string verbatim, e.g. "2500.0"
    CurrencyCode:    payment.CurrencyCode,
    AccountID:       payment.AccountID,
    Payee:           payee,
    ClientReference: clientReference, // "" when the transfer has none
})
signature := manza.Sign(signingSecret, input) // lowercase hex HMAC-SHA256

resp, err := authorizerClient.Payments.Authorize(ctx, payment.ID, authorizationID, signature)
// or: authorizerClient.Payments.Decline(ctx, payment.ID, authorizationID, "reason") // "" omits reason

Authorize refuses a blank signature locally (*manza.ArgumentError) because the API counts a missing signature as a failed attempt. A wrong signature returns a KindValidation error of Type invalid_signature; five on one challenge send the payment to your in-app approvers, five in a row suspend the authorizer. Create accepts an optional client_reference (at most 128 characters, unique per entity); a duplicate returns a conflict error carrying the existing payment's PaymentID.

Errors

Non-2xx responses come back as *manza.Error with Status, Kind (manza.KindAuthentication, KindForbidden, KindNotFound, KindValidation for 400 and 422, KindConflict for 409, KindRateLimit, KindServer, KindAPI), the API's Type/Message/Param, and the RequestID. A conflict also carries PaymentID. Discriminate on Kind, not on status codes:

var apiErr *manza.Error
if errors.As(err, &apiErr) && apiErr.Kind == manza.KindConflict {
    fmt.Println("already created as", apiErr.PaymentID)
}

Transport failures are *manza.ConnectionError, a misconfigured client is *manza.ConfigurationError, and a value the SDK refuses to send is *manza.ArgumentError.

Tests

Tests replay the canonical cassettes recorded by manza-ruby. The cassettes are downloaded from the Ruby SDK's release tarball and served from an httptest.Server. Same interactions, same assertions, every language.

scripts/fetch-cassettes.sh
go test ./...
(cd examples/transfer_authorizer && go test ./...)   # the example is its own module

The SDK family

SDK Repository Install
Ruby (reference implementation, records the cassettes) getmanza/manza-ruby gem "manza"
TypeScript / JavaScript getmanza/manza-ts npm install @getmanza/sdk
Python getmanza/manza-python pip install manza
Go getmanza/manza-go (this repo) go get github.com/getmanza/manza-go
PHP getmanza/manza-php composer require manza/manza-php
Rust getmanza/manza-rust cargo add manza
Crystal getmanza/manza-crystal shard manza (github: getmanza/manza-crystal)
Elixir getmanza/manza-elixir {:manza, "~> 1.0"}
CLI getmanza/cli npm install -g @getzazu/cli or brew install getmanza/tap/zazu

Documentation

Overview

Package manza is the Go SDK for the Manza API.

Response bodies are returned as-is from the API — snake_case keys in a map. The same shape ships across every Manza SDK (Ruby, TypeScript, Python, Go, ...) so the cassette contract is one-to-one. Response.Decode maps a body onto the typed models in types.go when you want structs.

Index

Constants

View Source
const (
	KindAuthentication = "authentication" // 401
	KindForbidden      = "forbidden"      // 403
	KindNotFound       = "not_found"      // 404
	KindValidation     = "validation"     // 400, 422
	KindConflict       = "conflict"       // 409
	KindRateLimit      = "rate_limit"     // 429
	KindServer         = "server"         // 5xx
	KindAPI            = "api"            // any other non-2xx
)

Error kinds, mirroring the shared Manza SDK error hierarchy. Together with ConfigurationError, ConnectionError and ArgumentError they make up the ten classes every SDK exposes.

View Source
const (
	BeneficiaryTypeIndividual = "individual"
	BeneficiaryTypeBusiness   = "business"
)

BeneficiaryType values.

View Source
const DefaultWebhookTolerance = 300 * time.Second

DefaultWebhookTolerance is how far a delivery's X-Manza-Timestamp may be from now before VerifyWebhook and ConstructWebhookEvent refuse it.

View Source
const MaxPerPage = 100

MaxPerPage is the API's hard page-size cap.

View Source
const StatusClearing = "clearing"

StatusClearing is the checkout-session and payment-link status between a customer's payment and settlement; settled_at is set once it clears.

View Source
const (
	// Version is the SDK version, sent in the User-Agent header.
	Version = "1.1.0"
)

Variables

This section is empty.

Functions

func ConstructWebhookEvent added in v1.1.0

func ConstructWebhookEvent(payload []byte, header http.Header, secret string, opts ...WebhookOption) (map[string]any, error)

ConstructWebhookEvent reads X-Manza-Signature and X-Manza-Timestamp from header (names in any case, the CGI HTTP_X_MANZA_* form, or the legacy X-Zazu-* names; X-Manza-* wins), verifies them, and returns the parsed event. It returns *ArgumentError when a header is missing, the signature does not match, the timestamp is outside the tolerance, or the body is not a JSON object.

Every delivery carries X-Manza-Signature (lowercase hex HMAC-SHA256 of "<timestamp>.<raw body>" under the endpoint's signing secret) and X-Manza-Timestamp (Unix seconds, fresh on every attempt). Pass the raw request body, never re-serialized JSON:

body, err := io.ReadAll(r.Body)
...
event, err := manza.ConstructWebhookEvent(body, r.Header, signingSecret)
if err != nil { // *manza.ArgumentError
	w.WriteHeader(http.StatusUnauthorized)
	return
}
event["event"] // "payment.authorization_requested"

func PayeeFor

func PayeeFor(externalAccountID, destinationAccountID string) (string, error)

PayeeFor returns the payee token: `ext:<id>` for a beneficiary's bank account, `own:<id>` for one of the entity's own accounts. Pass exactly one id; the other must be empty.

func Sign

func Sign(secret, signatureInput string) string

Sign returns the lowercase hex HMAC-SHA256 of signatureInput under the authorizer endpoint's signing secret. Pass the result to PaymentsService.Authorize.

func SignWebhook added in v1.1.0

func SignWebhook(payload []byte, timestamp, secret string) string

SignWebhook returns the lowercase hex HMAC-SHA256 of "<timestamp>.<payload>" under secret: the X-Manza-Signature of a delivery. For tests and local tools.

func SignatureInput

func SignatureInput(f TransferAuthorizationFields) string

SignatureInput builds the pipe-joined, versioned string that Sign signs:

manza.transfer-authorization.v1|<payment_id>|<nonce>|<amount>|<currency_code>|<account_id>|<payee>|<client_reference or "">

Amount must be the API's decimal string verbatim ("2500.0", not "2500.00" or a formatted float), otherwise the server's signature will not match.

func VerifyWebhook added in v1.1.0

func VerifyWebhook(payload []byte, signature, timestamp, secret string, opts ...WebhookOption) bool

VerifyWebhook reports whether signature matches payload and timestamp under secret (compared in constant time) and timestamp is within the tolerance of now. An empty secret, or a timestamp that is not an integer, never verifies.

Types

type AccountListParams

type AccountListParams struct {
	ListParams
	Status       string
	CurrencyCode string
}

AccountListParams filters GET /api/accounts.

type AccountsService

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

AccountsService — accounts and their transactions.

func (*AccountsService) Get

func (s *AccountsService) Get(ctx context.Context, id string) (*Response, error)

Get calls GET /api/accounts/:id.

func (*AccountsService) GetTransaction

func (s *AccountsService) GetTransaction(ctx context.Context, accountID, transactionID string) (*Response, error)

GetTransaction calls GET /api/accounts/:account_id/transactions/:id.

func (*AccountsService) List

func (s *AccountsService) List(ctx context.Context, params AccountListParams) (*Page, error)

List calls GET /api/accounts.

func (*AccountsService) ListTransactions

func (s *AccountsService) ListTransactions(ctx context.Context, accountID string, params TransactionListParams) (*Page, error)

ListTransactions calls GET /api/accounts/:account_id/transactions.

type ArgumentError

type ArgumentError struct{ Message string }

ArgumentError is returned when the caller passes a value the SDK refuses to send (e.g. a blank signature). Distinct from *Error with KindValidation, which is the server rejecting a request. No HTTP call was made.

func (*ArgumentError) Error

func (e *ArgumentError) Error() string

type Attributes

type Attributes map[string]any

Attributes is a request body for create/update calls — snake_case keys, exactly what the API accepts (see the per-endpoint docs).

type Authorization

type Authorization struct {
	ID            string  `json:"id"`
	Status        string  `json:"status"` // pending, authorized, declined, refused, expired, superseded, failed
	ExpiresAt     string  `json:"expires_at"`
	AuthorizedAt  *string `json:"authorized_at,omitempty"`
	DeclinedAt    *string `json:"declined_at,omitempty"`
	RefusalReason *string `json:"refusal_reason,omitempty"`
}

Authorization is a machine-authorization challenge on a payment, and the response of PaymentsService.Decline. RefusalReason is set when Status is refused, expired, superseded or failed: the payment went to the in-app approvers (see PaymentsService).

type BeneficiariesService

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

BeneficiariesService — saved transfer recipients. Each beneficiary embeds its bank accounts; the one flagged `default` is used when a transfer names only the beneficiary_id. There is no update or delete via the API.

func (*BeneficiariesService) Create

func (s *BeneficiariesService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/beneficiaries. Attributes: beneficiary_type ("individual" | "business"; inferred from person_name / company_name when omitted), person_name, company_name, email, phone_number. Values must be strings. Shares a 10/minute limit with CreateExternalAccount.

func (*BeneficiariesService) CreateExternalAccount

func (s *BeneficiariesService) CreateExternalAccount(ctx context.Context, beneficiaryID string, attributes Attributes) (*Response, error)

CreateExternalAccount calls POST /api/beneficiaries/:beneficiary_id/external_accounts. Required: account_number. Optional: name, country_code, currency_code, account_type ("bank" only), bank_identifier (required in ZA, rejected in MA, where it is derived from the RIB).

func (*BeneficiariesService) Get

Get calls GET /api/beneficiaries/:id.

func (*BeneficiariesService) GetExternalAccount

func (s *BeneficiariesService) GetExternalAccount(ctx context.Context, beneficiaryID, id string) (*Response, error)

GetExternalAccount calls GET /api/beneficiaries/:beneficiary_id/external_accounts/:id.

func (*BeneficiariesService) List

func (s *BeneficiariesService) List(ctx context.Context, params ListParams) (*Page, error)

List calls GET /api/beneficiaries.

func (*BeneficiariesService) ListExternalAccounts

func (s *BeneficiariesService) ListExternalAccounts(ctx context.Context, beneficiaryID string, params ListParams) (*Page, error)

ListExternalAccounts calls GET /api/beneficiaries/:beneficiary_id/external_accounts.

type Beneficiary

type Beneficiary struct {
	ID               string            `json:"id"`
	BeneficiaryType  string            `json:"beneficiary_type"` // individual | business
	Name             string            `json:"name"`
	Email            *string           `json:"email"`
	PhoneNumber      *string           `json:"phone_number"`
	ExternalAccounts []ExternalAccount `json:"external_accounts"`
	CreatedAt        string            `json:"created_at"`
}

Beneficiary is a saved transfer recipient.

type CheckoutSession

type CheckoutSession struct {
	ID                    string         `json:"id"`
	URL                   string         `json:"url"`
	Status                string         `json:"status"`
	Amount                string         `json:"amount"`
	CurrencyCode          string         `json:"currency_code"`
	Description           *string        `json:"description"`
	CustomerEmail         *string        `json:"customer_email"`
	CustomerName          *string        `json:"customer_name"`
	CollectBillingAddress *bool          `json:"collect_billing_address"`
	BillingAddress        map[string]any `json:"billing_address"`
	SuccessURL            string         `json:"success_url"`
	CancelURL             *string        `json:"cancel_url"`
	Metadata              map[string]any `json:"metadata"`
	ExpiresAt             string         `json:"expires_at"`
	CompletedAt           *string        `json:"completed_at"`
	SettledAt             *string        `json:"settled_at"`
	CreatedAt             string         `json:"created_at"`
	Transaction           map[string]any `json:"transaction"`
}

CheckoutSession is a one-off hosted checkout session. Status is open, clearing (StatusClearing), or a terminal state.

type CheckoutSessionsService

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

CheckoutSessionsService — one-off hosted checkout sessions. No list, update, or delete; sessions are created and inspected by id.

func (*CheckoutSessionsService) Create

func (s *CheckoutSessionsService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/checkout_sessions. Required attributes: account_id, amount, success_url. Optional: cancel_url, description, customer_email, customer_name, metadata, collect_billing_address, billing_address. The response carries settled_at and transaction once the session has cleared (status "clearing" → "complete").

func (*CheckoutSessionsService) Get

Get calls GET /api/checkout_sessions/:id.

type Client

type Client struct {
	Accounts           *AccountsService
	Beneficiaries      *BeneficiariesService
	CheckoutSessions   *CheckoutSessionsService
	Customers          *CustomersService
	Entity             *EntityService
	Invoices           *InvoicesService
	PayeeTrustRequests *PayeeTrustRequestsService
	PaymentLinks       *PaymentLinksService
	Payments           *PaymentsService
	TransferAuthorizer *TransferAuthorizerService
	// Deprecated: use Payments. Kept for all of 1.x; it is the same service
	// and calls /api/payments.
	TransferDrafts   *TransferDraftsService
	WebhookEndpoints *WebhookEndpointsService
	// contains filtered or unexported fields
}

Client is the SDK entry point. Resources hang off it as fields.

client, err := manza.New(manza.WithAPIKey("sk_live_..."))
page, err := client.Accounts.List(ctx, manza.ListParams{})

func New

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

New builds a Client. An API key is required — pass WithAPIKey or set MANZA_API_KEY.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, path string, params url.Values, body any) (*Response, error)

Request performs an HTTP request against the API. Non-2xx responses are returned as *Error. Body (when non-nil) is JSON-encoded.

type ConfigurationError

type ConfigurationError struct{ Message string }

ConfigurationError is returned by New when the client can't be built.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

type ConnectionError

type ConnectionError struct{ Message string }

ConnectionError wraps transport-level failures (timeouts, DNS, refused).

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

type Customer

type Customer struct {
	ID                 string  `json:"id"`
	CustomerType       string  `json:"customer_type"`
	Name               string  `json:"name"`
	PersonName         *string `json:"person_name"`
	CompanyName        *string `json:"company_name"`
	Email              *string `json:"email"`
	Phone              *string `json:"phone"`
	RegistrationNumber *string `json:"registration_number,omitempty"`
	VATNumber          *string `json:"vat_number,omitempty"`
	TaxID              *string `json:"tax_id,omitempty"`
	ICENumber          *string `json:"ice_number,omitempty"`
	CreatedAt          string  `json:"created_at"`
	UpdatedAt          string  `json:"updated_at"`
}

Customer is an individual or business the entity invoices. TaxID and ICENumber are market-gated (absent outside Morocco); RegistrationNumber and VATNumber are absent where the entity's market does not collect them.

type CustomerListParams

type CustomerListParams struct {
	ListParams
	Query string // matches company name, person name, email
}

CustomerListParams filters GET /api/customers.

type CustomersService

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

CustomersService — individuals or businesses the entity invoices.

func (*CustomersService) Create

func (s *CustomersService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/customers.

func (*CustomersService) Delete

func (s *CustomersService) Delete(ctx context.Context, id string) (*Response, error)

Delete calls DELETE /api/customers/:id.

func (*CustomersService) Get

func (s *CustomersService) Get(ctx context.Context, id string) (*Response, error)

Get calls GET /api/customers/:id.

func (*CustomersService) List

func (s *CustomersService) List(ctx context.Context, params CustomerListParams) (*Page, error)

List calls GET /api/customers.

func (*CustomersService) Update

func (s *CustomersService) Update(ctx context.Context, id string, attributes Attributes) (*Response, error)

Update calls PATCH /api/customers/:id.

type EntityService

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

EntityService — the current entity (the tenant the API key belongs to).

func (*EntityService) Get

func (s *EntityService) Get(ctx context.Context) (*Response, error)

Get calls GET /api/entity.

type Error

type Error struct {
	Status     int
	Kind       string // one of the Kind* constants
	Type       string // the API's error.type field
	Message    string
	Param      string
	PaymentID  string // only set for conflict: the draft already holding a duplicate client_reference
	RequestID  string
	RetryAfter int // seconds; only set for rate_limit
	Body       map[string]any
}

Error is the API error envelope, mirroring the other Manza SDKs' hierarchy: { "error": { "type": ..., "message": ..., "param": ..., "payment_id": ... } }. Discriminate on Kind (errors.As to *Error, then compare against the Kind* constants) instead of matching status codes.

func (*Error) Error

func (e *Error) Error() string

type ExternalAccount

type ExternalAccount struct {
	ID             string `json:"id"`
	Name           string `json:"name"`
	AccountNumber  string `json:"account_number"`
	BankIdentifier string `json:"bank_identifier"`
	CurrencyCode   string `json:"currency_code"`
	Default        bool   `json:"default"`
	// Trusted is true once the bank details are a trusted payee.
	Trusted bool `json:"trusted"`
}

ExternalAccount is a beneficiary's bank account.

type Invoice

type Invoice struct {
	ID           string  `json:"id"`
	Number       string  `json:"number"`
	Status       string  `json:"status"`
	CurrencyCode string  `json:"currency_code"`
	IssueDate    string  `json:"issue_date"`
	DueDate      string  `json:"due_date"`
	DeliveryDate *string `json:"delivery_date,omitempty"`
	Total        string  `json:"total"`
}

Invoice carries the headline fields; use Response.Body for the rest. DeliveryDate is market-gated: the key is absent outside Morocco.

type InvoiceListParams

type InvoiceListParams struct {
	ListParams
	Status     string
	CustomerID string
}

InvoiceListParams filters GET /api/invoices.

type InvoicesService

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

InvoicesService — invoices and their lifecycle actions.

func (*InvoicesService) Cancel

func (s *InvoicesService) Cancel(ctx context.Context, id string) (*Response, error)

Cancel calls POST /api/invoices/:id/cancel.

func (*InvoicesService) Create

func (s *InvoicesService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/invoices.

func (s *InvoicesService) CreatePaymentLink(ctx context.Context, invoiceID, accountID string) (*Response, error)

CreatePaymentLink calls POST /api/invoices/:invoice_id/payment_link.

func (*InvoicesService) CreditNote

func (s *InvoicesService) CreditNote(ctx context.Context, id string) (*Response, error)

CreditNote calls POST /api/invoices/:id/credit_note.

func (*InvoicesService) Delete

func (s *InvoicesService) Delete(ctx context.Context, id string) (*Response, error)

Delete calls DELETE /api/invoices/:id.

func (*InvoicesService) Get

func (s *InvoicesService) Get(ctx context.Context, id string) (*Response, error)

Get calls GET /api/invoices/:id.

func (*InvoicesService) List

func (s *InvoicesService) List(ctx context.Context, params InvoiceListParams) (*Page, error)

List calls GET /api/invoices.

func (*InvoicesService) MarkAsPaid

func (s *InvoicesService) MarkAsPaid(ctx context.Context, id string) (*Response, error)

MarkAsPaid calls POST /api/invoices/:id/mark_as_paid.

func (*InvoicesService) Send

func (s *InvoicesService) Send(ctx context.Context, id string) (*Response, error)

Send calls POST /api/invoices/:id/send.

func (*InvoicesService) Update

func (s *InvoicesService) Update(ctx context.Context, id string, attributes Attributes) (*Response, error)

Update calls PATCH /api/invoices/:id.

type ListParams

type ListParams struct {
	Limit  int
	Cursor string
}

ListParams are the shared cursor-pagination inputs. Limit 0 means MaxPerPage.

type Option

type Option func(*Client)

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key (default: MANZA_API_KEY, falling back to the deprecated ZAZU_API_KEY).

func WithAPIVersion

func WithAPIVersion(v string) Option

WithAPIVersion pins the Manza-Version request header (default: MANZA_API_VERSION).

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sets the API base URL (default: MANZA_BASE_URL or https://ma.manza.finance). South Africa is https://za.manza.finance.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient swaps the underlying *http.Client (default: 30s timeout).

type Page

type Page struct {
	Data       []map[string]any
	HasMore    bool
	NextCursor string
	Response   *Response
	// contains filtered or unexported fields
}

Page is one page of a cursor-paginated list endpoint: { "data": [...], "has_more": bool, "next_cursor": string|null }.

func (*Page) Next

func (p *Page) Next(ctx context.Context) (*Page, error)

Next fetches the following page, or returns nil when this is the last one.

type PayeeTrustRequest

type PayeeTrustRequest struct {
	ID                 string   `json:"id"`
	Status             string   `json:"status"` // pending, approved, declined, cancelled
	ExternalAccountIDs []string `json:"external_account_ids"`
	CreatedAt          string   `json:"created_at"`
	ResolvedAt         *string  `json:"resolved_at"`
}

PayeeTrustRequest is a request to trust payees for machine-authorized transfers.

type PayeeTrustRequestsService

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

PayeeTrustRequestsService — requests to trust payees for machine-authorized transfers. The API key can only ask: a member holding payment-authorize permission approves the request in the Manza app. Status: pending → approved / declined / cancelled. No list, update, or delete.

func (*PayeeTrustRequestsService) Create

func (s *PayeeTrustRequestsService) Create(ctx context.Context, externalAccountIDs []string) (*Response, error)

Create calls POST /api/payee_trust_requests with at most 100 bank account ids.

func (*PayeeTrustRequestsService) Get

Get calls GET /api/payee_trust_requests/:id.

type PaymentLink struct {
	ID                    string         `json:"id"`
	Slug                  string         `json:"slug"`
	LinkType              string         `json:"link_type"`
	Status                string         `json:"status"`
	Amount                *string        `json:"amount"`
	CurrencyCode          string         `json:"currency_code"`
	Title                 *string        `json:"title"`
	Description           *string        `json:"description"`
	PaymentReference      *string        `json:"payment_reference"`
	PaymentsCount         int            `json:"payments_count"`
	MaxPayments           *int           `json:"max_payments"`
	RedirectURL           *string        `json:"redirect_url"`
	InvoiceID             *string        `json:"invoice_id"`
	CollectBillingAddress *bool          `json:"collect_billing_address"`
	BillingAddress        map[string]any `json:"billing_address"`
	URL                   string         `json:"url"`
	ExpiresAt             *string        `json:"expires_at"`
	PaidAt                *string        `json:"paid_at"`
	SettledAt             *string        `json:"settled_at"`
	CreatedAt             string         `json:"created_at"`
	UpdatedAt             string         `json:"updated_at"`
}

PaymentLink is a standalone payment link. Status is active, clearing (StatusClearing), or a terminal state.

type PaymentLinkListParams

type PaymentLinkListParams struct {
	ListParams
	Status   string
	LinkType string
}

PaymentLinkListParams filters GET /api/payment_links.

type PaymentLinksService

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

PaymentLinksService — standalone payment links (not attached to an invoice).

func (*PaymentLinksService) Cancel

func (s *PaymentLinksService) Cancel(ctx context.Context, id string) (*Response, error)

Cancel calls POST /api/payment_links/:id/cancel.

func (*PaymentLinksService) Create

func (s *PaymentLinksService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/payment_links.

func (*PaymentLinksService) Get

Get calls GET /api/payment_links/:id.

func (*PaymentLinksService) List

List calls GET /api/payment_links.

type PaymentsService added in v1.1.0

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

PaymentsService — API-initiated transfers, called payments (formerly transfer drafts; /api/transfer_drafts stays a server-side alias). Creating a payment never executes a transfer by itself. A payment inside the entity's machine-authorization envelope (trusted payee, or a new one when "Approve transfers to new payees" is on, within limits) is sent to the enrolled transfer authorizer as a `payment.authorization_requested` webhook; answer it with Authorize or Decline, using an API key other than the one that created the payment. Every other payment goes to the in-app approval flow, where a manager or legal representative approves it. Poll Get (status: requested → processing → completed / failed) or subscribe to the `transfer.executed` webhook to follow execution.

A payment's `authorization` says which way it went: `pending` (a challenge was sent), `authorized`, `declined` (the payment is deleted), or an outcome that sends it to the in-app approvers with a `refusal_reason`: `refused` (it did not qualify: `untrusted_payee`, `unrestricted_api_key`, `over_new_payee_limit`, `over_transfer_limit`, `over_daily_limit`, `currency_mismatch`, `suspended` or `secret_expired`), or `expired` / `superseded` / `failed` (a challenge closed without an authorize: `expired`, `stale` or `signature_failed`). It is null when no authorizer was enrolled.

func (*PaymentsService) Authorize added in v1.1.0

func (s *PaymentsService) Authorize(ctx context.Context, id, authorizationID, signature string) (*Response, error)

Authorize calls POST /api/payments/:id/authorize.

Executes the payment. authorizationID comes from the `payment.authorization_requested` webhook; build signature with SignatureInput and Sign. Requires the `transfers:authorize` scope on a key other than the payment's creator (otherwise a forbidden *Error of type `same_key_forbidden`), bound to an IP allowlist (otherwise forbidden `unrestricted_api_key`). A conflict *Error of type `authorization_busy` means a bank-detail edit, trust or trust revocation on the payee was in flight: retry. A blank signature is refused locally with *ArgumentError: the API counts it as a failed attempt, and five fail the challenge.

func (*PaymentsService) Create added in v1.1.0

func (s *PaymentsService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/payments. Required: account_id, amount, and exactly one of beneficiary_id (external transfer) or destination_account_id (own-account move). Optional: external_account_id, currency_code, payment_reference, internal_notes, client_reference (unique per entity, at most 128 characters; a duplicate returns a conflict *Error whose PaymentID names the existing payment).

func (*PaymentsService) Decline added in v1.1.0

func (s *PaymentsService) Decline(ctx context.Context, id, authorizationID, reason string) (*Response, error)

Decline calls POST /api/payments/:id/decline.

Declines the challenge and deletes the payment; the response is the authorization (status "declined", a null refusal_reason). An empty reason is omitted from the request.

func (*PaymentsService) Get added in v1.1.0

func (s *PaymentsService) Get(ctx context.Context, id string) (*Response, error)

Get calls GET /api/payments/:id.

type Response

type Response struct {
	Status    int
	RequestID string
	Body      map[string]any
	Raw       []byte
}

Response is a successful (2xx) API response.

func (*Response) Decode

func (r *Response) Decode(v any) error

Decode unmarshals the raw response body into v, typically one of the models in types.go (TransferDraft, TransferAuthorizer, CheckoutSession, ...).

type TransactionListParams

type TransactionListParams struct {
	ListParams
	Operation    string
	PostedAfter  string // ISO-8601
	PostedBefore string // ISO-8601
}

TransactionListParams filters GET /api/accounts/:id/transactions.

type TransferAuthorizationFields

type TransferAuthorizationFields struct {
	PaymentID    string
	Nonce        string // one-time, from the payment.authorization_requested webhook
	Amount       string // the API's decimal string verbatim, e.g. "2500.0"
	CurrencyCode string
	AccountID    string
	Payee        string // see PayeeFor
	// ClientReference is empty when the transfer has none.
	ClientReference string
}

TransferAuthorizationFields are the inputs to a machine-authorization signature. Build them from your OWN record of the transfer, not from the webhook's `signature_input` (which is there only to compare against).

type TransferAuthorizer added in v1.1.0

type TransferAuthorizer struct {
	Status               string  `json:"status"`            // active, suspended
	SuspensionReason     *string `json:"suspension_reason"` // member, signature_failures, secret_expired, endpoint_disabled
	CurrencyCode         string  `json:"currency_code"`
	PerTransferLimit     string  `json:"per_transfer_limit"`
	DailyLimit           string  `json:"daily_limit"`
	DailyAuthorizedTotal string  `json:"daily_authorized_total"` // the last 24 hours
	SecretExpiresAt      string  `json:"secret_expires_at"`
	WebhookEndpointID    string  `json:"webhook_endpoint_id"`
	EnrolledAt           string  `json:"enrolled_at"`
}

TransferAuthorizer is the entity's enrolled transfer authorizer, the response of TransferAuthorizerService.Get. Limits and the total are the API's decimal strings.

type TransferAuthorizerService added in v1.1.0

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

TransferAuthorizerService — the entity's enrolled transfer authorizer, read-only. Enrolment, limits, the "Approve transfers to new payees" option and resume stay in the app behind a second factor. A singular resource: no list, no id.

func (*TransferAuthorizerService) Get added in v1.1.0

Get calls GET /api/transfer_authorizer.

Any key with `transfers:read`, `transfers:write` or `transfers:authorize`. Returns status (active / suspended), suspension_reason (member, signature_failures, secret_expired, endpoint_disabled; null when active), currency_code, per_transfer_limit, daily_limit, daily_authorized_total (the last 24 hours), secret_expires_at, webhook_endpoint_id and enrolled_at; decode it onto TransferAuthorizer. It does not show whether new payees are approved. A not-found *Error means no authorizer is enrolled.

type TransferDraft

type TransferDraft struct {
	ID                   string         `json:"id"`
	Status               string         `json:"status"`
	CurrencyCode         string         `json:"currency_code"`
	PaymentReference     *string        `json:"payment_reference"`
	ClientReference      *string        `json:"client_reference"`
	AccountID            string         `json:"account_id"`
	BeneficiaryID        *string        `json:"beneficiary_id"`
	ExternalAccountID    *string        `json:"external_account_id"`
	DestinationAccountID *string        `json:"destination_account_id"`
	Amount               string         `json:"amount"`
	Transfer             *TransferRef   `json:"transfer"`
	Authorization        *Authorization `json:"authorization"`
	CreatedAt            string         `json:"created_at"`
	UpdatedAt            string         `json:"updated_at"`
}

TransferDraft is an API-initiated transfer (a payment): the response of PaymentsService.Create, Get and Authorize.

type TransferDraftsService deprecated

type TransferDraftsService = PaymentsService

TransferDraftsService is the former name of PaymentsService.

Deprecated: use PaymentsService (Client.Payments). Kept for all of 1.x; it is the same type and calls /api/payments.

type TransferRef

type TransferRef struct {
	ID     string `json:"id"`
	Status string `json:"status"` // e.g. submitted
}

TransferRef is the executed transfer attached to an authorized draft.

type WebhookEndpointsService

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

WebhookEndpointsService — webhook endpoint management.

func (*WebhookEndpointsService) Create

func (s *WebhookEndpointsService) Create(ctx context.Context, attributes Attributes) (*Response, error)

Create calls POST /api/webhook_endpoints.

func (*WebhookEndpointsService) Delete

Delete calls DELETE /api/webhook_endpoints/:id.

func (*WebhookEndpointsService) Disable

func (s *WebhookEndpointsService) Disable(ctx context.Context, id string) (*Response, error)

Disable calls POST /api/webhook_endpoints/:id/disable.

func (*WebhookEndpointsService) Enable

Enable calls POST /api/webhook_endpoints/:id/enable.

func (*WebhookEndpointsService) Get

Get calls GET /api/webhook_endpoints/:id.

func (*WebhookEndpointsService) List

func (s *WebhookEndpointsService) List(ctx context.Context, params ListParams) (*Page, error)

List calls GET /api/webhook_endpoints.

func (*WebhookEndpointsService) RegenerateSecret

func (s *WebhookEndpointsService) RegenerateSecret(ctx context.Context, id string) (*Response, error)

RegenerateSecret calls POST /api/webhook_endpoints/:id/regenerate_secret.

func (*WebhookEndpointsService) Test

Test calls POST /api/webhook_endpoints/:id/test.

func (*WebhookEndpointsService) Update

func (s *WebhookEndpointsService) Update(ctx context.Context, id string, attributes Attributes) (*Response, error)

Update calls PATCH /api/webhook_endpoints/:id.

type WebhookOption added in v1.1.0

type WebhookOption func(*webhookConfig)

WebhookOption configures VerifyWebhook and ConstructWebhookEvent.

func WithWebhookNow added in v1.1.0

func WithWebhookNow(now time.Time) WebhookOption

WithWebhookNow sets the time the timestamp is compared against (default time.Now()).

func WithWebhookTolerance added in v1.1.0

func WithWebhookTolerance(d time.Duration) WebhookOption

WithWebhookTolerance sets how far the timestamp may be from now (default DefaultWebhookTolerance).

func WithoutWebhookTolerance added in v1.1.0

func WithoutWebhookTolerance() WebhookOption

WithoutWebhookTolerance skips the timestamp check. Use it only to replay a captured delivery in a local tool or test, never on a live endpoint: without the check, anyone holding a captured delivery can replay it.

Jump to

Keyboard shortcuts

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