Documentation
¶
Overview ¶
Package dominaite is the server-side Go client for the Dominaite merchant API.
One call from your backend opens a hosted checkout session; a two-line script tag renders the payment widget on your page. Card details go straight from your customer's browser into the widget. They never touch your server or this SDK, which keeps your PCI scope minimal (SAQ A).
Keep your API secret on the server. Never ship it to a browser, never commit it, never log it.
client, err := dominaite.New(os.Getenv("DOMINAITE_KEY_ID"), os.Getenv("DOMINAITE_SECRET"))
if err != nil {
return err
}
session, err := client.CreateCheckoutSession(ctx, dominaite.CreateCheckoutSessionParams{
Amount: 2500, // minor units: 25.00 EUR
Currency: "EUR",
OrderReference: "order-1042",
})
Hand session.CashierKey and session.CashierToken to the embed snippet.
Index ¶
- Constants
- Variables
- func Sign(in SignInput) string
- type APIError
- type AuthError
- type CheckoutSession
- type CheckoutStatus
- type Client
- func (c *Client) CreateCheckoutSession(ctx context.Context, params CreateCheckoutSessionParams) (*CheckoutSession, error)
- func (c *Client) CreateCheckoutSessionWithRetry(ctx context.Context, params CreateCheckoutSessionParams, opts RetryOptions) (*CheckoutSession, error)
- func (c *Client) GetStatus(ctx context.Context, transactionID string) (*CheckoutStatus, error)
- func (c *Client) Ping(ctx context.Context) (*Ping, error)
- type CreateCheckoutSessionParams
- type Customer
- type Error
- type Option
- type Ping
- type RefusalError
- type RetryOptions
- type SignInput
- type TransportError
- type ValidationError
Constants ¶
const ( // DefaultBaseURL is the production merchant API. DefaultBaseURL = "https://api.dominaite.com/payments" // SessionsPath is the canonical path that gets signed. POST creates a // session; GET SessionsPath + "/{transactionId}" reads its status. SessionsPath = "/merchant-api/bridgerpay/checkout/sessions" // PingPath is the credentials-and-clock smoke test. It creates nothing. PingPath = "/merchant-api/ping" // Version is this SDK's version, reported in the User-Agent. Version = "0.1.2" )
const ( StatusPending = "pending" StatusProcessing = "processing" StatusSucceeded = "succeeded" StatusFailed = "failed" StatusRefunded = "refunded" StatusPartiallyRefunded = "partially_refunded" StatusCancelled = "cancelled" StatusDisputed = "disputed" StatusRequiresCapture = "requires_capture" StatusAbandoned = "abandoned" )
Transaction status values returned by GetStatus.
Variables ¶
var ErrDominaite = errors.New("dominaite")
ErrDominaite matches every error this SDK returns, for a single errors.Is catch-all:
if errors.Is(err, dominaite.ErrDominaite) { ... }
For the specific kind, use errors.As with *RefusalError, *AuthError, *APIError, *TransportError or *ValidationError, or errors.As with the Error interface to catch any of them while keeping the message.
Functions ¶
func Sign ¶
Sign builds the X-Signature value for one request: lowercase hex HMAC-SHA256 over
"{timestamp}\n{METHOD}\n{path}\n{idempotencyKey}\n{sha256hex(body)}"
The idempotency key is INSIDE the signature, so a captured request cannot be replayed with a different key to mint extra sessions. The server rejects timestamps more than 5 minutes off, so keep your server clock on NTP.
The client signs for you. Sign is exported so you can pin the recipe against the offline test vector before calling the live API, and so you can debug an INVALID_SIGNATURE without reading this package's source.
Types ¶
type APIError ¶
type APIError struct {
HTTPStatus int
// contains filtered or unexported fields
}
APIError means the API answered, but with an unexpected or rejecting response. HTTPStatus carries the code. A 422 means an idempotency key was replayed with a different body; use a fresh key. A 404 from GetStatus means an unknown transaction id.
type AuthError ¶
type AuthError struct {
ErrorCode string
// contains filtered or unexported fields
}
AuthError means the API rejected your credentials or signature (HTTP 401/403). Not retryable: fix the key id, the secret, the server clock, or the caller allowlist.
ErrorCode is one of INVALID_API_KEY, INVALID_SIGNATURE, TIMESTAMP_OUT_OF_RANGE, IP_NOT_ALLOWED.
type CheckoutSession ¶
type CheckoutSession struct {
TransactionID string `json:"transactionId"`
OrderID string `json:"orderId"`
// CashierKey feeds the widget's data-cashier-key. A per-payment value, not
// a credential.
CashierKey string `json:"cashierKey"`
// CashierToken feeds the widget's data-cashier-token. A per-payment value,
// not a credential.
CashierToken string `json:"cashierToken"`
// Amount is in MINOR units.
Amount int64 `json:"amount"`
Currency string `json:"currency"`
// ExpiresAt is ISO 8601. Sessions are valid for 2 hours.
ExpiresAt string `json:"expiresAt"`
// Raw is the unparsed payload, for fields this struct does not model yet.
Raw json.RawMessage `json:"-"`
}
CheckoutSession is what CreateCheckoutSession returns.
type CheckoutStatus ¶
type CheckoutStatus struct {
TransactionID string `json:"transactionId"`
OrderID string `json:"orderId"`
OrderReference string `json:"orderReference,omitempty"`
// Status is one of the Status* constants.
Status string `json:"status"`
// Amount is in MINOR units.
Amount int64 `json:"amount"`
Currency string `json:"currency"`
RefundedAmount int64 `json:"refundedAmount,omitempty"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt,omitempty"`
// ExpiresAt is present while the session is still payable.
ExpiresAt string `json:"expiresAt,omitempty"`
// Raw is the unparsed payload, for fields this struct does not model yet.
Raw json.RawMessage `json:"-"`
}
CheckoutStatus is what GetStatus returns.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a server-side client for the Dominaite merchant API. It is safe for concurrent use.
func New ¶
New builds a client from your API key id (dmk_...) and secret (dms_...), both from the dashboard's Website integration tab. It returns a *ValidationError when either credential has the wrong prefix, which catches a swapped key id and secret before anything is sent.
func (*Client) CreateCheckoutSession ¶
func (c *Client) CreateCheckoutSession(ctx context.Context, params CreateCheckoutSessionParams) (*CheckoutSession, error)
CreateCheckoutSession opens a hosted checkout session for one payment.
Errors it returns:
- *ValidationError: bad arguments; nothing was sent.
- *AuthError: wrong credentials, bad signature, clock off, IP not allowlisted. Fix the config, do not retry.
- *RefusalError: the gateway refused the session; inspect ErrorCode.
- *APIError: an unexpected or rejecting response; inspect HTTPStatus.
- *TransportError: network failure or 5xx. Safe to retry WITH the same idempotency key, which is what CreateCheckoutSessionWithRetry does.
func (*Client) CreateCheckoutSessionWithRetry ¶
func (c *Client) CreateCheckoutSessionWithRetry(ctx context.Context, params CreateCheckoutSessionParams, opts RetryOptions) (*CheckoutSession, error)
CreateCheckoutSessionWithRetry creates a session, retrying *TransportError only, with THE SAME idempotency key across every attempt.
Reusing the key is what makes the retry safe. A transport failure leaves you not knowing whether the request landed; the API returns the original session for a key it has already seen instead of opening a second one. Generating a fresh key per attempt would be exactly the double-charge bug this method exists to prevent, so the key is pinned once before the first attempt.
Refusals and authentication failures are returned immediately. They will not change on a retry.
func (*Client) GetStatus ¶
GetStatus reads the payment status of one of your checkout sessions.
Status is one of the Status* constants: pending, processing, succeeded, failed, refunded, partially_refunded, cancelled, disputed, requires_capture, abandoned. While a session is still payable the response also carries ExpiresAt; after that instant a pending session can only become abandoned. Amounts are integers in MINOR units. An unknown transaction id returns an *APIError with HTTPStatus 404.
StatusSucceeded is the only value that means the payment is complete. Keep polling on StatusPending, StatusProcessing and StatusRequiresCapture - none of them is terminal.
StatusRequiresCapture is NOT "unpaid": the payer has already paid and the funds are held awaiting capture. Never treat it as an abandoned order.
Treat any status you do not recognise as still-open too: a value the API adds later should make you keep polling, never silently close a live order.
Poll after the payer returns to you, or on your order timeout. Not in a tight loop: the endpoint is rate limited per key.
func (*Client) Ping ¶ added in v0.1.2
Ping verifies your credentials, your signing and your clock without creating anything. Make this your first live call: it isolates the setup problems from the payment ones, so a failure here is the key id, the secret, the signature, the clock or an IP allowlist and nothing else.
Check Ping.ClockSkewSeconds. Requests start failing at 300.
Errors it returns:
- *AuthError: wrong credentials, bad signature, clock off, IP not allowlisted.
- *APIError: an unexpected or rejecting response; inspect HTTPStatus.
- *TransportError: network failure or 5xx.
type CreateCheckoutSessionParams ¶
type CreateCheckoutSessionParams struct {
// Amount is in MINOR units: 2500 is 25.00 EUR. Integers only.
Amount int64 `json:"amount"`
// Currency is ISO 4217, e.g. "EUR".
Currency string `json:"currency"`
// OrderReference is your own order id, at most 100 characters. It shows up
// in your dashboard.
OrderReference string `json:"orderReference"`
Customer *Customer `json:"customer,omitempty"`
// Country is ISO 3166-1 alpha-2.
Country string `json:"country,omitempty"`
// Language is the ISO 639-1 widget UI language.
Language string `json:"language,omitempty"`
// Theme is "light", "dark" or "bright".
Theme string `json:"theme,omitempty"`
Description string `json:"description,omitempty"`
// IdempotencyKey is auto-generated when empty. It travels in the header and
// in the signature, never in the body. Retrying with the same key never
// creates a second payment, so on a timeout retry with the same key.
IdempotencyKey string `json:"-"`
// Extra carries any additional field the API accepts that this struct does
// not model yet. Keys here are merged into the JSON body.
Extra map[string]any `json:"-"`
}
CreateCheckoutSessionParams are the parameters for Client.CreateCheckoutSession. Amount, Currency and OrderReference are required.
func (CreateCheckoutSessionParams) MarshalJSON ¶
func (p CreateCheckoutSessionParams) MarshalJSON() ([]byte, error)
MarshalJSON emits the request body: the modelled fields in declaration order, with Extra merged in. IdempotencyKey is excluded; it is a header, not a body field.
type Customer ¶
type Customer struct {
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
}
Customer holds optional payer details. Prefilled fields are hidden from the payer in the widget, so the checkout form stays short.
type Error ¶
type Error interface {
error
// contains filtered or unexported methods
}
Error is implemented by every error this SDK returns. It is sealed: only the types in this package satisfy it, so a type switch over them is exhaustive.
var apiErr dominaite.Error
if errors.As(err, &apiErr) { ... }
type Option ¶
type Option func(*Client)
Option configures a Client. Pass options to New.
func WithBaseURL ¶
WithBaseURL points the client at a non-production environment. Trailing slashes are trimmed. Empty values are ignored, so you can pass an unset environment variable straight through and still get production.
func WithHTTPClient ¶
WithHTTPClient supplies your own *http.Client: a proxy-aware transport, custom TLS, or a test double. It replaces WithTimeout, so set the timeout on the client you pass.
func WithTimeout ¶
WithTimeout sets the per-request timeout on the default HTTP client. Defaults to 45 seconds. A context deadline still wins when it is shorter.
func WithUserAgent ¶
WithUserAgent appends your own identifier to the SDK's User-Agent, which helps when Dominaite support reads the access logs for your integration.
type Ping ¶ added in v0.1.2
type Ping struct {
// Pong is always true on a 200.
Pong bool `json:"pong"`
// MerchantID is the merchant your key authenticated as.
MerchantID string `json:"merchantId"`
// ServerTime is ISO 8601.
ServerTime string `json:"serverTime,omitempty"`
// ServerUnixTime is the server clock in unix seconds.
ServerUnixTime int64 `json:"serverUnixTime,omitempty"`
// ClockSkewSeconds is server time minus your X-Timestamp. If its absolute
// value creeps toward 300, fix NTP now - requests start failing at 300.
ClockSkewSeconds int64 `json:"clockSkewSeconds"`
// Raw is the unparsed payload, for fields this struct does not model yet.
Raw json.RawMessage `json:"-"`
}
Ping is what Ping returns: proof that your key, secret, signing and clock are all good, without creating anything.
type RefusalError ¶
type RefusalError struct {
ErrorCode string
// TransactionID is the payment this idempotency key collided with, when the
// API named one. Empty otherwise.
TransactionID string
// Raw is the unparsed refusal payload, for fields not modelled above.
Raw json.RawMessage
// contains filtered or unexported fields
}
RefusalError means the gateway understood the request but refused to open a checkout session. The API answered with success: false.
Branch on ErrorCode:
- PAYMENT_PROCESSING_UNAVAILABLE: card payments are off right now; retry later.
- DUPLICATE_REQUEST: a session for this idempotency key is already open.
- ALREADY_PROCESSED: this idempotency key's payment already completed.
- PRIOR_ATTEMPT_FAILED: a prior attempt with this key failed terminally; use a fresh key.
- IDEMPOTENCY_KEY_REUSED: same key sent with a DIFFERENT body; use a fresh key.
On a replay refusal the API also names WHICH payment your key collided with, on TransactionID. That is the recovery path - read it back with GetStatus to find out what the earlier attempt did, instead of minting a second payment for the same order:
session, err := client.CreateCheckoutSession(ctx, params)
var refusal *dominaite.RefusalError
if errors.As(err, &refusal) && refusal.TransactionID != "" {
status, err := client.GetStatus(ctx, refusal.TransactionID)
}
TransactionID is empty when the API did not name one - notably the concurrent-race DUPLICATE_REQUEST, which knows a key was taken but not yet by which row. Always check before using it.
Never blind-retry a refusal. It will not change on its own.
type RetryOptions ¶
type RetryOptions struct {
// Attempts is the total number of attempts including the first. Zero means
// the default of 3.
Attempts int
// BaseDelay is the wait before the first retry; it doubles each attempt.
// Zero means the default of 500ms.
BaseDelay time.Duration
}
RetryOptions tunes CreateCheckoutSessionWithRetry.
type SignInput ¶
type SignInput struct {
// Secret is your API secret (dms_...).
Secret string
// Timestamp is unix SECONDS, as sent in X-Timestamp.
Timestamp string
// Method is the HTTP method. Uppercased before signing.
Method string
// Path is the canonical path only: no host, no query string.
Path string
// IdempotencyKey is the Idempotency-Key header value. Empty string for GET.
IdempotencyKey string
// Body is the exact request body string that will be sent. Empty string for GET.
Body string
}
SignInput is everything that goes into one request signature.
type TransportError ¶
type TransportError struct {
Err error
// contains filtered or unexported fields
}
TransportError means a network-level failure, a timeout, or a 5xx. The request may or may not have reached the API, so retry WITH THE SAME idempotency key: a retried key never creates a second payment. CreateCheckoutSessionWithRetry does exactly that.
Err is the underlying cause when there was one, reachable with errors.Unwrap or errors.As.
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
Unwrap exposes the underlying network error, if any.
type ValidationError ¶
type ValidationError struct {
// contains filtered or unexported fields
}
ValidationError means the SDK rejected the call before sending anything. Nothing reached the network; fix the arguments.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
create-session
command
Command create-session mints a Dominaite checkout session and reads its status back.
|
Command create-session mints a Dominaite checkout session and reads its status back. |