dominaite

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 18 Imported by: 0

README

dominaite-go

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; a signed webhook tells you when the money actually arrived. Card details go straight from your customer's browser into the payment widget - they never touch your server, which keeps your PCI scope minimal (SAQ A).

Go 1.21 or newer. Zero dependencies: crypto/hmac, crypto/sha256, net/http, encoding/json, all standard library.

Install

go get github.com/dominaite/merchant-sdk-go
import dominaite "github.com/dominaite/merchant-sdk-go"

To work on the SDK itself:

go vet ./...
go test ./...      # includes the offline signing and webhook vectors

Credentials

You get two values from the Dominaite dashboard, Website integration tab, when you generate an API key (shown once - store them like passwords):

  • dmk_... - your API key id. Identifies you; not secret by itself.
  • dms_... - your API secret. Server-side only: environment variable or a config file outside the web root. Never in a browser, never in git, never in logs.

Every request is signed with the secret (HMAC-SHA256) and timestamped. Keep your server clock on NTP - signatures older than 5 minutes are rejected with TIMESTAMP_OUT_OF_RANGE.

If the key has an IP allowlist, calls from anywhere else fail with IP_NOT_ALLOWED. The allowlist is managed on the same dashboard tab.

A webhook endpoint has a third secret, separate from the two above: whsec_..., shown once when you create the endpoint on the Webhooks tab. It signs deliveries to you rather than requests from you, so it is never sent anywhere - see Webhooks.

Quickstart (zero to a paid order)

Everything below is copy-paste. It assumes an empty directory and nothing installed.

A complete integration is three moving parts, and you want all three:

  1. Create a session from your backend, and render the widget with what it returns.
  2. Receive a webhook when the payment resolves. This is how you learn you were paid.
  3. Reconcile on a schedule, because no webhook system delivers everything forever.

Steps 1 and 2 are below. Step 3 is not optional; see Reconciliation is still mandatory.

mkdir my-checkout && cd my-checkout
go mod init example.com/my-checkout
go get github.com/dominaite/merchant-sdk-go

Set your credentials and the environment you are pointing at:

export DOMINAITE_KEY_ID=dmk_...      # Website integration tab
export DOMINAITE_SECRET=dms_...      # shown once when you generated the key
export DOMINAITE_WEBHOOK_SECRET=whsec_...  # shown once when you created the endpoint
# Dev: the payments function app, whose Azure Functions route prefix is /api.
# Confirm the host for your environment before the first call.
export DOMINAITE_BASE_URL=https://func-dom-gw-payments-dev-gwc-01.azurewebsites.net/api
# Production needs no DOMINAITE_BASE_URL - the SDK defaults to
# https://api.dominaite.com/payments

Ping before your first mint. It is one signed GET that creates nothing, so anything that fails here is your credentials, your signing or your clock:

client, err := dominaite.New(
	os.Getenv("DOMINAITE_KEY_ID"),
	os.Getenv("DOMINAITE_SECRET"),
	dominaite.WithBaseURL(os.Getenv("DOMINAITE_BASE_URL")), // no-op in production
)
if err != nil {
	log.Fatal(err)
}

ping, err := client.Ping(context.Background())
if err != nil {
	log.Fatal(err)
}
log.Printf("merchant %s, clock skew %ds", ping.MerchantID, ping.ClockSkewSeconds)

Watch ClockSkewSeconds: the gateway rejects requests once it passes 300, so a number that keeps growing is your cue to fix NTP before payments start failing.

Step 1: create a session

main.go:

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	dominaite "github.com/dominaite/merchant-sdk-go"
)

func main() {
	client, err := dominaite.New(
		os.Getenv("DOMINAITE_KEY_ID"),
		os.Getenv("DOMINAITE_SECRET"),
		dominaite.WithBaseURL(os.Getenv("DOMINAITE_BASE_URL")), // ignored when empty
	)
	if err != nil {
		panic(err)
	}

	session, err := client.CreateCheckoutSession(context.Background(), dominaite.CreateCheckoutSessionParams{
		Amount:         2500,          // minor units: 2500 = 25.00 EUR
		Currency:       "EUR",
		OrderReference: "order-1042",  // your own order id, shows up in your dashboard
		Customer: &dominaite.Customer{
			// Pass everything you already know - prefilled fields are hidden from the
			// payer, so the checkout form stays short.
			FirstName: "Ana",
			LastName:  "Kirova",
			Email:     "ana@example.com",
		},
		Language: "bg",   // widget UI language
		Theme:    "dark",
	})
	if err != nil {
		var refusal *dominaite.RefusalError
		var transport *dominaite.TransportError
		switch {
		case errors.As(err, &refusal):
			// Machine-readable: refusal.ErrorCode - codes listed below.
			fmt.Println("Payment unavailable:", refusal.ErrorCode)
		case errors.As(err, &transport):
			// Network blip - safe to retry with the same idempotency key.
			fmt.Println("Payment temporarily unavailable")
		default:
			panic(err)
		}
		return
	}

	// Store session.TransactionID against your order, then hand CashierKey +
	// CashierToken to the page that renders the widget.
	fmt.Printf("%+v\n", session)
}
go run .

A successful run prints TransactionID, OrderID, CashierKey, CashierToken, Amount, Currency, ExpiresAt. Render the widget with the two cashier values:

<div id="checkout"></div>
<script src="https://bp-checkout.dominaite.com/v2/launcher"
        data-cashier-key="CASHIER_KEY_FROM_SESSION"
        data-cashier-token="CASHIER_TOKEN_FROM_SESSION"></script>

CashierKey and CashierToken are per-payment session values, not credentials - but HTML-escape them when you template them into the page (html/template does it for you).

There is a runnable version of the above in examples/create-session/main.go in this repo - it mints a session and reads the status back, using the same environment variables:

go run ./examples/create-session
Step 2: receive the webhook

The payer finishes on the widget, not on your site, so the session call cannot tell you the order was paid. A webhook does. Register an endpoint on the dashboard's Webhooks tab, subscribe to payment.succeeded, and handle it:

func handleWebhook(w http.ResponseWriter, r *http.Request) {
	// The RAW bytes, before any decoding. The signature covers exactly these,
	// so decoding and re-encoding first will break verification.
	body, err := io.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	event, err := dominaite.VerifyWebhook(
		body,
		r.Header.Get(dominaite.WebhookSignatureHeader),
		os.Getenv("DOMINAITE_WEBHOOK_SECRET"),
	)
	if err != nil {
		// Log the reason for yourself; never tell the caller why it failed.
		log.Printf("rejected webhook: %v", err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Delivery is at-least-once, so the same event.ID will sometimes arrive
	// twice. Dedupe on it, in your database, before doing anything with money.
	if inserted := recordDelivery(event.ID); !inserted {
		w.WriteHeader(http.StatusOK)
		return
	}

	if event.Type == dominaite.EventPaymentSucceeded {
		// Queue the work. Do not fulfil the order on this goroutine.
		enqueueFulfilment(event.Data.TransactionID, event.Data.IdempotencyKey)
	}

	// Answer fast. A slow 2xx is counted as a failed delivery and retried.
	w.WriteHeader(http.StatusOK)
}

A runnable version, with every event type handled, is in examples/webhook-handler/main.go:

export DOMINAITE_WEBHOOK_SECRET=whsec_...
go run ./examples/webhook-handler

That is the whole integration: the session call, the script tag, the webhook, and your domain bound to your checkout by Dominaite during onboarding.

Webhooks

VerifyWebhook authenticates a delivery and returns the parsed event. It verifies before it parses, and a WebhookEvent cannot be obtained any other way, so an unverified payload cannot reach your business logic by accident.

event, err := dominaite.VerifyWebhook(payload, signatureHeader, secret, opts...)
Argument What
payload The raw request body, byte for byte as received. Not a re-encoded struct.
signatureHeader The X-Webhook-Signature value, also available as dominaite.WebhookSignatureHeader.
secret The endpoint's whsec_... secret.

Options: WithWebhookTolerance(d) changes the freshness window from its 300 second default (dominaite.DefaultWebhookTolerance), and WithWebhookClock(fn) replaces the clock so tests can verify a recorded delivery at a fixed instant.

There is no way to switch the freshness check off. WithWebhookTolerance(0) is the strictest setting, not an off switch: it requires t to equal your clock to the second, which rejects anything that spent time in flight. A negative duration is refused with INVALID_TOLERANCE.

Getting the raw body right

This is the one thing that reliably goes wrong. The signature covers the exact bytes that were sent, so anything that reserialises the body invalidates it. Read the body first, verify, then parse. If a framework or middleware has already decoded the body for you, reach for its raw-body escape hatch rather than re-marshalling the decoded value.

The signature scheme

The header is t={unix_seconds},v1={lowercase_hex}. v1 is HMAC-SHA256 over the ASCII concatenation "{t}.{raw_body}", keyed with the UTF-8 bytes of the whsec_ secret. The SDK compares in constant time and then checks that |now - t| is within tolerance.

The timestamp is checked after the MAC, deliberately: t is covered by the signature, so until the MAC passes there is no reason to trust it. That ordering also means a stale but genuine replay reports TIMESTAMP_OUT_OF_TOLERANCE while a forgery reports SIGNATURE_MISMATCH, instead of the two failure modes blurring together.

If deliveries start failing with TIMESTAMP_OUT_OF_TOLERANCE, your server clock has drifted. Fix NTP rather than widening the tolerance.

Rejections

Every failure is a *WebhookVerificationError with a Reason. Nothing else comes out and nothing panics, so a hostile header is an ordinary rejection path:

var verr *dominaite.WebhookVerificationError
if errors.As(err, &verr) {
	log.Printf("rejected: %s", verr.Reason)
	w.WriteHeader(http.StatusBadRequest)
	return
}
Reason Meaning
MALFORMED_SIGNATURE Header missing, empty, or not t=...,v1=.... Nothing could be checked.
SIGNATURE_MISMATCH The MAC did not match. Wrong secret, or the payload is not what was signed.
TIMESTAMP_OUT_OF_TOLERANCE MAC valid, timestamp too old or too far ahead. A replay, or clock drift.
MALFORMED_PAYLOAD Signature good, body not valid JSON. Surprising - log it rather than dropping it.

Answer a rejected delivery with 400 and no detail. Never echo the reason back: whoever sent an unverified request does not get to learn whether the secret or the timestamp was the problem.

The event

The envelope is flat. There is no ApiResponse wrapper and no success field, so do not branch on one.

event.ID                     // delivery id, and YOUR DEDUPE KEY
event.Type                   // one of the Event* constants
event.CreatedAt              // ISO 8601 UTC instant of the transition, not of delivery
event.Data.TransactionID
event.Data.Status            // wire status, one of the Status* constants
event.Data.PreviousStatus    // empty when the wire sent null
event.Data.Amount            // MINOR units: what you are PAID
event.Data.GrossAmount       // MINOR units: what the card was charged
event.Data.SurchargeAmount   // *int64, nil when no surcharge is known
event.Data.Currency
event.Data.OriginalTransactionID  // parent, on refunds and reversals
event.Data.IdempotencyKey    // your own mint key, when the gateway knows it
event.Raw                    // the verified bytes, for anything not modelled above

Amount and GrossAmount are not the same number when a surcharge applies: Amount is what you are paid, GrossAmount is what moved on the card. Credit orders from Amount.

SurchargeAmount is a pointer so that "no surcharge information" stays distinct from "a surcharge of zero".

IdempotencyKey is the cheapest way to match a delivery back to your own order without a lookup. It is empty when the gateway does not know it, which today includes every refund.

Event catalog

payment.succeeded, payment.failed, payment.requires_capture, payment.cancelled, payment.abandoned, payment.refunded, payment.disputed (exported as the Event* constants). The set is closed and case-sensitive; endpoint registration rejects anything else.

  • payment.succeeded is the only signal that means money is in hand.
  • payment.refunded fires once per refund, from the refund row - never from the parent payment's status flip.
  • payment.requires_capture includes approved pre-auth holds. It is not an unpaid order.
  • payment.cancelled is a pre-completion void only.
  • payment.abandoned is the terminal sweep verdict on a checkout that was never paid.

pending and processing are deliberately not webhooked. Poll session status if you want to drive in-flight UX off them.

Treat a Type you do not recognise as a no-op and still answer 2xx. The catalog can grow, and a 400 on an unknown type will trip the circuit breaker on your endpoint.

Delivery semantics

Delivery is at-least-once. Dedupe on event.ID, persistently - an in-memory set loses on restart, and retries can arrive hours apart.

Respond 2xx quickly and queue the real work. A slow response counts as a failed delivery.

Failed deliveries are retried up to the endpoint's RetryCount (default 3, max 10, 0 disables) at 1m, 5m, 30m, 2h, 12h. An endpoint whose initial attempt and every configured retry fail consecutively is auto-disabled; a later successful delivery re-enables it. An endpoint you disabled by hand in the dashboard is never re-enabled automatically.

A merchant can have at most 25 active endpoints.

Reconciliation is still mandatory

Webhooks complement the reconciliation sweep, they do not replace it. There is no publish outbox, and chains parked against a disabled endpoint are simply lost, so there are windows in which a delivery never arrives at all. Keep a scheduled job that reads back the status of every order you believe is still open and settles it from the API.

If you do only one of the two, do reconciliation. It is the one that cannot silently lose money.

Rotating a secret

Regenerating an endpoint's secret replaces it: the old secret stops verifying immediately. There is no overlap window, and VerifyWebhook rejects a header carrying more than one v1 rather than trying candidates in turn. Update the secret in your configuration as part of the same change that regenerates it.

Testing your handler

The suite in this repo pins the canonical cross-SDK vector, byte for byte, along with tamper, wrong-secret, stale-timestamp and malformed-header cases. Every Dominaite SDK pins the same vector, so the recipe cannot drift between languages. Run go test ./... before you point a real endpoint at your handler.

To test your own handler against a fixed delivery, sign a body yourself and pin the clock:

event, err := dominaite.VerifyWebhook(
	body,
	header,
	secret,
	dominaite.WithWebhookClock(func() time.Time { return time.Unix(1755700000, 0) }),
)

Client options

dominaite.New(keyID, secret, opts...) takes functional options:

Option What
WithBaseURL(url) Point at a non-production environment. Empty values are ignored, so an unset env var still gives you production. Must be https://; plain http:// is accepted only for localhost, 127.0.0.1 and ::1, and New returns a *ValidationError for anything else.
WithTimeout(d) Per-request timeout on the default HTTP client. Defaults to 45s (serverless cold starts can take 10+s).
WithHTTPClient(c) Your own *http.Client: proxy-aware transport, custom TLS, a test double. Replaces WithTimeout.
WithUserAgent(s) Appends your identifier to the SDK's User-Agent, which helps when support reads the access logs.

Every call takes a context.Context. A context deadline shorter than the client timeout wins, and cancelling the context returns a *TransportError wrapping context.Canceled.

Amounts are minor units

Amount is always an integer in the currency's minor unit: 2500 is 25.00 EUR. The field is an int64, so a float will not compile; non-positive values are rejected before anything reaches the network. The amount is locked server-side - what you pass here is what gets charged; nothing in the browser can change it.

Retries and double-charges

Every CreateCheckoutSession call carries an idempotency key (auto-generated, or set your own in IdempotencyKey). Retrying with the same key never opens a second payment - on a timeout, retry with the same key rather than generating a new one.

What a retry does not do is hand back the session the first attempt created. If that attempt landed, the retry comes back as a *RefusalError with a replay code (DUPLICATE_REQUEST, ALREADY_PROCESSED, PRIOR_ATTEMPT_FAILED, IDEMPOTENCY_KEY_REUSED) and no cashier fields. Recover through RefusalError.TransactionID and GetStatus - see Recovering from a replay refusal below.

CreateCheckoutSessionWithRetry does that for you: it pins one key up front and reuses it across attempts, retrying only *TransportError (network failures and 5xx, including MERCHANT_API_UNAVAILABLE). Refusals and authentication failures are not retried - they will not change. Rate limits are not retried either: retrying into a full queue only makes it longer, so a *RateLimitError comes straight back for you to reschedule.

session, err := client.CreateCheckoutSessionWithRetry(
	ctx,
	dominaite.CreateCheckoutSessionParams{Amount: 2500, Currency: "EUR", OrderReference: "order-1042"},
	dominaite.RetryOptions{Attempts: 3, BaseDelay: 500 * time.Millisecond}, // zero values use these defaults
)

The delay doubles each attempt, and a cancelled context stops the wait immediately.

Sessions expire

A session is valid for 2 hours. If the payer comes back later, create a new session.

Status polling (fallback, and the reconciliation sweep)

Prefer webhooks for learning that a payment resolved. Polling is the right tool for three narrower jobs: the reconciliation sweep, in-flight UX on pending and processing (which are never webhooked), and local development before you have a public URL to deliver to.

Reaching for polling as your primary signal means holding an order open until you happen to ask about it. Reaching for it as your only signal means a busy loop against a rate-limited endpoint. Use both: webhooks for latency, the sweep for completeness.

status, err := client.GetStatus(ctx, session.TransactionID)
// status.Status == "succeeded", status.OrderReference == "order-1042",
// status.Amount == 2500, status.Currency == "EUR", ...

Status is one of pending, processing, succeeded, failed, refunded, partially_refunded, cancelled, disputed, requires_capture, abandoned (exported as the Status* constants). While the session is still payable the response also carries ExpiresAt; after that instant a pending session can only become abandoned. An unknown transaction id returns an *APIError with HTTPStatus 404.

succeeded is the only value that means the payment is complete. Keep polling on pending, processing and requires_capture - none of them is terminal.

requires_capture 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 as well: a value the API adds later should make you keep polling, never silently close an order that is still live.

Poll after the payer returns to you, or on your order timeout - not in a tight loop; the endpoint is rate limited at 60 requests per minute per key and 120 per minute per IP. Going over returns a *RateLimitError.

Both response types also carry Raw (json.RawMessage) with the unparsed payload, for fields the structs do not model yet.

Errors

Every error the SDK returns satisfies the dominaite.Error interface and matches errors.Is(err, dominaite.ErrDominaite), so one catch-all works:

var sdkErr dominaite.Error
if errors.As(err, &sdkErr) { ... }

For the specific kind, use errors.As with the concrete pointer type:

Error When What to do
*RefusalError The API answered with success: false. ErrorCode carries the reason. Branch on ErrorCode. Do not blind-retry.
*AuthError 401/403. ErrorCode is INVALID_API_KEY, INVALID_SIGNATURE, TIMESTAMP_OUT_OF_RANGE, or IP_NOT_ALLOWED. Fix the key id, secret, server clock, or allowlist. Never retry-loop.
*RateLimitError 429. RetryAfterSeconds carries the Retry-After header when the API sent one as integer seconds; HasRetryAfter tells "wait 0s" apart from "the API did not say". Back off, then reschedule with the same idempotency key. The SDK never retries this for you.
*TransportError Network failure, timeout, or 5xx (MERCHANT_API_UNAVAILABLE). Wraps the cause, reachable with errors.Unwrap. A 5xx classifies on the status, so an HTML or empty error page from an overloaded edge is still retryable. Retry with the same idempotency key.
*APIError Any other rejecting or unexpected response; HTTPStatus carries the code. Inspect. A 3xx means a proxy or a wrong base URL answered with a redirect - the SDK never follows one. A replayed idempotency key does not land here; it comes back as a *RefusalError.
*ValidationError Bad arguments (non-positive amount, missing field, malformed key id). Fix the call; nothing was sent.
*WebhookVerificationError VerifyWebhook rejected an inbound delivery; Reason carries which check failed. Answer 400 with no detail. See Webhooks.

Refusal codes on RefusalError.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.
Recovering from a replay refusal

When your idempotency key collides with an earlier attempt, the refusal names the transaction it collided with, so you can reconcile instead of minting a second payment:

session, err := client.CreateCheckoutSession(ctx, params)

var refusal *dominaite.RefusalError
if errors.As(err, &refusal) && refusal.TransactionID != "" {
	status, err := client.GetStatus(ctx, refusal.TransactionID)
	// Now you know what the earlier attempt actually did.
}

RefusalError.TransactionID is empty when the API did not name one (a concurrent-race DUPLICATE_REQUEST knows the key is taken but not yet by which row), so check it before use. The full refusal payload is on RefusalError.Raw.

Verifying your signing

Run go test ./... before you touch the live API. The SDK signs for you, but the recipe is pinned by an offline known-answer vector shared with the gateway and the dashboard, and the suite reproduces it byte-for-byte. If that test fails, nothing else matters.

If you ever hand-roll the signing (or debug an INVALID_SIGNATURE), Sign is exported:

dominaite.Sign(dominaite.SignInput{
	Secret:         "dms_...",
	Timestamp:      "1755302400",                           // unix SECONDS
	Method:         "POST",
	Path:           "/merchant-api/checkout/sessions",      // path only, no host
	IdempotencyKey: "00000000-0000-4000-8000-000000000001", // "" for GET
	Body:           `{"amount":2500,"currency":"EUR","orderReference":"order-1042"}`, // "" for GET
})
// "8f5fba0b29a8eea81b76a0e6d7119e79ec68f586910f77713b045652e5ce9b74"

Printing a SignInput or a Client itself is safe: both redact the secret under %v, %+v, %#v and %s, so a debug log shows dms_***redacted*** and every other field. SignInput also carries json:"-" on Secret, so JSON encoders drop it.

Two cases the redaction cannot reach, because neither goes through the String method:

  • A SignInput or Client sitting in an unexported field of your own struct, printed by printing that outer struct. fmt cannot call methods on values it reaches by reflection, so it dumps the fields raw: a by-value field leaks under %v, %+v and %s, and even the usual client *dominaite.Client field leaks under %s.
  • Any encoder that walks the struct instead of printing it. SignInput is covered by the tag; anything else you build around your secret is not.

Keep the secret out of structured logs entirely rather than relying on redaction.

The signed payload is five lines: "{timestamp}\n{METHOD}\n{path}\n{idempotencyKey}\n{sha256hex(body)}", signed as lowercase hex HMAC-SHA256 with your secret, UTF-8 throughout. GET signs an empty idempotency key and an empty body, and sends no Idempotency-Key header.

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

Examples

Constants

View Source
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/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"
)
View Source
const (
	// WebhookReasonMalformedSignature means the signature header was missing,
	// empty, or not in the "t=...,v1=..." shape (no t, no v1, or a v1 that is
	// not hex). Nothing could be checked.
	WebhookReasonMalformedSignature = "MALFORMED_SIGNATURE"
	// WebhookReasonSignatureMismatch means the MAC did not match. Either the
	// secret is wrong or the payload is not the bytes that were signed. Treat
	// the request as hostile.
	WebhookReasonSignatureMismatch = "SIGNATURE_MISMATCH"
	// WebhookReasonTimestampOutOfTolerance means the MAC was valid but the
	// timestamp is too far from now: a replay of a genuine old delivery, or
	// your server clock has drifted. Check NTP before widening the tolerance.
	WebhookReasonTimestampOutOfTolerance = "TIMESTAMP_OUT_OF_TOLERANCE"
	// WebhookReasonMalformedPayload means the signature was good but the body
	// was not valid JSON. Surprising - the bytes are authentic - so log it
	// rather than silently dropping it.
	WebhookReasonMalformedPayload = "MALFORMED_PAYLOAD"
	// WebhookReasonInvalidTolerance means the caller passed a negative
	// tolerance to WithWebhookTolerance. That is your bug, not the sender's:
	// nothing about the delivery was checked. Use 0 to require an exact
	// timestamp, or a positive window.
	WebhookReasonInvalidTolerance = "INVALID_TOLERANCE"
)

Reasons reported on WebhookVerificationError.Reason.

View Source
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.

View Source
const (
	EventPaymentSucceeded       = "payment.succeeded"
	EventPaymentFailed          = "payment.failed"
	EventPaymentRequiresCapture = "payment.requires_capture"
	EventPaymentCancelled       = "payment.cancelled"
	EventPaymentAbandoned       = "payment.abandoned"
	EventPaymentRefunded        = "payment.refunded"
	EventPaymentDisputed        = "payment.disputed"
)

Webhook event types. This is the complete v1 catalog - endpoint registration rejects anything outside it, and the match is case-sensitive.

EventPaymentSucceeded is the ONLY signal that means money is in hand. The in-flight states (pending, processing) are deliberately not webhooked; poll GetStatus if you want to drive UX off them.

View Source
const DefaultWebhookTolerance = 5 * time.Minute

DefaultWebhookTolerance is how far a delivery's timestamp may sit from your clock before VerifyWebhook rejects it. It matches the gateway's own window.

View Source
const WebhookSignatureHeader = "X-Webhook-Signature"

WebhookSignatureHeader is the header Dominaite signs each delivery with. An endpoint can be configured to use a different header name, but this is the default and the one the dashboard shows.

Variables

View Source
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, *RateLimitError, *APIError, *TransportError or *ValidationError, or errors.As with the Error interface to catch any of them while keeping the message.

Statuses is the complete v1 status vocabulary. A value outside this list means the gateway grew a status this SDK does not know yet: keep polling, never treat it as terminal.

Functions

func Sign

func Sign(in SignInput) string

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
	ErrorCode  string
	// contains filtered or unexported fields
}

APIError means the API answered, but with an unexpected or rejecting response. HTTPStatus carries the code. A 404 from GetStatus means an unknown transaction id. A 3xx means something in front of the API answered with a redirect: the SDK never follows one and never treats its body as a real response, because the API itself does not redirect.

A key replayed with a different body does NOT arrive here. The API answers HTTP 200 with success false and IDEMPOTENCY_KEY_REUSED, so it reaches you as a *RefusalError. A 429 does not arrive here either: it is a *RateLimitError.

ErrorCode is the machine-readable code when the API sent one, so input rejections can be branched on rather than string-matched. A 400 carrying IDEMPOTENCY_KEY_REQUIRED means the Idempotency-Key header was missing or empty. Empty when the API named no code.

func (APIError) Error

func (e APIError) Error() string

func (APIError) Is

func (e APIError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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.

func (AuthError) Error

func (e AuthError) Error() string

func (AuthError) Is

func (e AuthError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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

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

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, and when WithBaseURL was given a non-https URL outside loopback.

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.
  • *RateLimitError: HTTP 429; back off and reschedule with the same idempotency key. Not retried for you, by CreateCheckoutSessionWithRetry either.
  • *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; a key the API has already seen is refused instead of opening a second session. 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.

A retry after the first attempt DID land does not give you that session back. The API answers with a replay refusal (*RefusalError, ErrorCode DUPLICATE_REQUEST, ALREADY_PROCESSED, PRIOR_ATTEMPT_FAILED or IDEMPOTENCY_KEY_REUSED) and no cashier fields. Recover through RefusalError.TransactionID with GetStatus when the API named one.

Refusals and authentication failures are returned immediately. They will not change on a retry.

Rate limits (*RateLimitError) are returned immediately too. Retrying into a full queue lengthens it; back off for RetryAfterSeconds and reschedule with the same idempotency key.

func (*Client) GetStatus

func (c *Client) GetStatus(ctx context.Context, transactionID string) (*CheckoutStatus, error)

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 (60/min per key, 120/min per IP), and going over returns a *RateLimitError.

func (Client) GoString added in v0.2.0

func (c Client) GoString() string

GoString covers %#v, which does not use String.

func (*Client) Ping added in v0.1.2

func (c *Client) Ping(ctx context.Context) (*Ping, error)

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.
  • *RateLimitError: HTTP 429; back off, the SDK does not retry it for you.
  • *TransportError: network failure or 5xx.

func (Client) String added in v0.2.0

func (c Client) String() string

String keeps the secret out of your logs. Printing a Client with %v, %+v or %#v (value or pointer) shows the key id and the base URL, never the secret.

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

func WithBaseURL(baseURL string) Option

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.

The URL must be https://. Plain http:// is accepted only for localhost, 127.0.0.1 and ::1, so a local mock server still works; anything else is refused by New with a *ValidationError. Over http:// your API secret's signature, key id and the whole request body travel in clear text.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

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.

The client is shallow-copied, so the SDK can pin its own redirect policy without changing the behaviour of the client you keep using elsewhere.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

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

func WithUserAgent(userAgent string) Option

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 RateLimitError added in v0.2.0

type RateLimitError struct {
	RetryAfterSeconds int
	HasRetryAfter     bool
	ErrorCode         string
	// contains filtered or unexported fields
}

RateLimitError means the API answered HTTP 429: you sent requests faster than your allowance. Nothing was created and nothing is wrong with the request.

The platform limits are 60 requests per minute per API key and 120 per minute per IP address. Both are enforced, so several keys behind one egress IP share the second budget.

The SDK does NOT retry this for you, on purpose. A client that retries into a rate limit makes the queue longer for everyone, and only your code knows whether this payment can wait. CreateCheckoutSessionWithRetry returns it immediately too. When you do retry, reuse the SAME idempotency key: the request may have been rejected at the edge, but that is not guaranteed.

RetryAfterSeconds carries the Retry-After header when the API sent one as integer seconds. HasRetryAfter distinguishes "wait 0 seconds" from "the API did not say" - a Retry-After in the HTTP-date form is reported as absent.

var limited *dominaite.RateLimitError
if errors.As(err, &limited) {
	wait := 5 * time.Second
	if limited.HasRetryAfter {
		wait = time.Duration(limited.RetryAfterSeconds) * time.Second
	}
	// reschedule with the same idempotency key
}

ErrorCode is the machine-readable code when the API named one. Empty otherwise.

func (RateLimitError) Error added in v0.2.0

func (e RateLimitError) Error() string

func (RateLimitError) Is added in v0.2.0

func (e RateLimitError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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.

func (RefusalError) Error

func (e RefusalError) Error() string

func (RefusalError) Is

func (e RefusalError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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_...). json:"-" keeps it out of every
	// structured JSON logger: those encode the struct rather than calling
	// String, so a tag is the only thing that stops them.
	Secret string `json:"-"`
	// 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.

func (SignInput) GoString added in v0.2.0

func (in SignInput) GoString() string

GoString covers %#v, which does not use String.

func (SignInput) String added in v0.2.0

func (in SignInput) String() string

String keeps the secret out of your logs. Debugging an INVALID_SIGNATURE usually means printing the input that produced it, so printing a SignInput with %v, %+v or %#v (value or pointer) shows every field except the secret.

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) Error

func (e TransportError) Error() string

func (TransportError) Is

func (e TransportError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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.

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) Is

func (e ValidationError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

type VerifyOption added in v0.2.0

type VerifyOption func(*verifyConfig)

VerifyOption tunes VerifyWebhook. The defaults are correct for production; you should not need any of these outside tests.

func WithWebhookClock added in v0.2.0

func WithWebhookClock(now func() time.Time) VerifyOption

WithWebhookClock replaces the clock VerifyWebhook compares against. This exists so tests can pin a fixed instant against a recorded delivery; it has no use in production code. A nil function is ignored.

func WithWebhookTolerance added in v0.2.0

func WithWebhookTolerance(tolerance time.Duration) VerifyOption

WithWebhookTolerance overrides how far the delivery timestamp may sit from your clock. Defaults to DefaultWebhookTolerance (5 minutes).

Zero is the strictest setting, not an off switch: it requires the timestamp to equal your clock to the second, which in practice rejects everything that spent any time in flight. There is no way to disable the freshness check, because doing so accepts a replay of any delivery ever captured. A negative duration is refused outright - VerifyWebhook returns WebhookReasonInvalidTolerance without checking anything.

If you are reaching for this because deliveries keep failing, your server clock is wrong. Fix NTP rather than widening the window.

type WebhookData added in v0.2.0

type WebhookData struct {
	TransactionID string `json:"transactionId"`
	// Status is the wire status of the row, one of the Status* constants.
	Status string `json:"status"`
	// PreviousStatus is the status the row moved from. Nullable on the wire;
	// empty string when absent.
	PreviousStatus string `json:"previousStatus"`
	// Kind is the movement kind, e.g. "sale". Nullable on the wire; empty
	// string when absent.
	Kind string `json:"kind"`

	// Amount is in MINOR units. For payment.* it is what the merchant is PAID
	// (the base amount). For payment.refunded it is what was returned to the
	// customer. It is NOT the card movement - that is GrossAmount.
	Amount int64 `json:"amount"`
	// GrossAmount is the card movement in MINOR units: what the customer's card
	// was actually charged.
	GrossAmount int64 `json:"grossAmount"`
	// SurchargeAmount is in MINOR units and nil when no surcharge is known.
	// A pointer, so "no surcharge information" stays distinct from "zero".
	SurchargeAmount *int64 `json:"surchargeAmount"`
	// Currency is ISO 4217.
	Currency string `json:"currency"`

	// OriginalTransactionID is the parent transaction for refunds and
	// reversals. Empty on an original payment.
	OriginalTransactionID string `json:"originalTransactionId"`
	// IdempotencyKey is your own mint key when the gateway knows it - the
	// cheapest way to match a delivery back to your order without a lookup.
	// Empty when unknown, which today includes every refund.
	IdempotencyKey string `json:"idempotencyKey"`

	// Raw is the unparsed data object, for fields not modelled above.
	Raw json.RawMessage `json:"-"`
}

WebhookData is the payload of a WebhookEvent.

type WebhookEvent added in v0.2.0

type WebhookEvent struct {
	// ID is the delivery id and YOUR DEDUPE KEY. Delivery is at-least-once, so
	// the same ID can arrive more than once and you must ignore the repeats.
	ID string `json:"id"`
	// Type is one of the Event* constants. Treat an unrecognised type as a
	// no-op rather than an error; the catalog can grow.
	Type string `json:"type"`
	// CreatedAt is the ISO 8601 UTC instant of the transition, not of delivery.
	// On a retry it still carries the original transition time.
	CreatedAt string      `json:"createdAt"`
	Data      WebhookData `json:"data"`

	// Raw is the exact verified payload, byte for byte as signed. Use it for
	// fields this struct does not model yet, or to store the delivery verbatim.
	Raw json.RawMessage `json:"-"`
}

WebhookEvent is one verified webhook delivery. VerifyWebhook returns it; there is no other way to get one, which is the point - the signature is checked before the body is parsed.

The envelope is FLAT. There is no ApiResponse wrapper and no `success` field, so do not branch on one.

func VerifyWebhook added in v0.2.0

func VerifyWebhook(payload []byte, signatureHeader, secret string, opts ...VerifyOption) (*WebhookEvent, error)

VerifyWebhook authenticates one webhook delivery and returns the parsed event. Verification happens BEFORE parsing, and the only way to obtain a WebhookEvent is through this function, so an unverified payload cannot reach your business logic by accident.

payload must be the RAW request body, exactly the bytes that arrived. Reading the body into a struct and re-encoding it will change them and the signature will not match. In net/http that means io.ReadAll(r.Body) before any json.Decode.

signatureHeader is the WebhookSignatureHeader value: "t={unix_seconds},v1={hex}". secret is the endpoint's whsec_ secret, shown once when the endpoint was created.

Every failure returns a *WebhookVerificationError carrying a WebhookReason* on .Reason. Nothing panics and no other error type comes out, so a malformed or hostile header is an ordinary rejection path:

body, err := io.ReadAll(r.Body)
if err != nil {
	w.WriteHeader(http.StatusBadRequest)
	return
}
event, err := dominaite.VerifyWebhook(body, r.Header.Get(dominaite.WebhookSignatureHeader), secret)
if err != nil {
	w.WriteHeader(http.StatusBadRequest)
	return
}
if !alreadySeen(event.ID) {   // delivery is at-least-once: dedupe on ID
	enqueue(event)            // do the work off the request path
}
w.WriteHeader(http.StatusOK)  // answer fast; a slow 2xx counts as a failure
Example

The doc example must stay compilable and correct.

event, err := VerifyWebhook(
	[]byte(webhookVector.Body),
	webhookVector.Header,
	webhookVector.Secret,
	atVectorTime(),
)
if err != nil {
	fmt.Println("rejected:", err)
	return
}
fmt.Println(event.Type, event.Data.Amount, event.Data.Currency)
Output:
payment.succeeded 8440 EUR

type WebhookVerificationError added in v0.2.0

type WebhookVerificationError struct {

	// Reason is one of the WebhookReason* constants.
	Reason string
	// contains filtered or unexported fields
}

WebhookVerificationError means VerifyWebhook rejected a delivery. Nothing was parsed and nothing should be acted on.

Answer the HTTP request with 400 and no detail. Never echo the reason back to the caller: whoever sent an unverified request does not get to learn whether their secret or their timestamp was the problem.

event, err := dominaite.VerifyWebhook(body, r.Header.Get("X-Webhook-Signature"), secret)
var verr *dominaite.WebhookVerificationError
if errors.As(err, &verr) {
	log.Printf("rejected webhook: %s", verr.Reason) // your logs only
	w.WriteHeader(http.StatusBadRequest)
	return
}

func (WebhookVerificationError) Error added in v0.2.0

func (e WebhookVerificationError) Error() string

func (WebhookVerificationError) Is added in v0.2.0

func (e WebhookVerificationError) Is(target error) bool

Is makes errors.Is(err, ErrDominaite) true for every SDK error.

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.
webhook-handler command
Command webhook-handler is a runnable webhook receiver.
Command webhook-handler is a runnable webhook receiver.

Jump to

Keyboard shortcuts

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