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
}
key, err := dominaite.OrderIdempotencyKey("checkout", "order-1042", 2500, "EUR")
if err != nil {
return err
}
session, err := client.CreateCheckoutSession(ctx, dominaite.CreateCheckoutSessionParams{
Amount: 2500, // minor units: 25.00 EUR
Currency: "EUR",
OrderReference: "order-1042",
IdempotencyKey: key, // "checkout-order-1042-2500-EUR"
})
Hand session.CashierKey and session.CashierToken to the embed snippet.
Index ¶
- Constants
- Variables
- func CurrencyExponent(currency string) (int, error)
- func IsPaid(status string) bool
- func IsTerminal(status string) bool
- func OrderIdempotencyKey(scope, orderID string, amountMinor int64, currency string) (string, error)
- func Sign(in SignInput) string
- func ToMinorUnits(amount, currency string) (int64, error)
- type APIError
- type AuthError
- type ChargeError
- type ChargePaymentMethodParams
- type CheckoutSession
- type CheckoutStatus
- type Client
- func (c *Client) ChargePaymentMethod(ctx context.Context, paymentMethodID string, params ChargePaymentMethodParams) (*PaymentMethodCharge, error)
- 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) GoString() string
- func (c *Client) Ping(ctx context.Context) (*Ping, error)
- func (c *Client) RevokePaymentMethod(ctx context.Context, paymentMethodID string) error
- func (c Client) String() string
- type CreateCheckoutSessionParams
- type Customer
- type Error
- type Option
- type PaymentMethodCharge
- type Ping
- type RateLimitError
- type RefusalError
- type RetryOptions
- type RevokeError
- type SignInput
- type StoredPaymentMethod
- type TransportError
- type ValidationError
- type VerifyOption
- type WebhookData
- type WebhookEvent
- type WebhookVerificationError
Examples ¶
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/checkout/sessions" // PaymentMethodsPath is the canonical path of stored payment methods. POST // PaymentMethodsPath + "/{paymentMethodId}/charges" charges one; DELETE // PaymentMethodsPath + "/{paymentMethodId}" revokes it. PaymentMethodsPath = "/merchant-api/payment-methods" // 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.3.0" )
const ( // ErrorCodeStorefrontNotWhitelisted (HTTP 409): the storefront's domain is // not whitelisted with the payment provider yet, and the environment // requires it. Nothing was minted. Ask Dominaite support to finish the // domain whitelisting; retrying will not help until then. ErrorCodeStorefrontNotWhitelisted = "STOREFRONT_NOT_WHITELISTED" // ErrorCodeStorefrontInactive (HTTP 409): the storefront was deactivated // or deleted. Reactivate it in the dashboard or use another one. ErrorCodeStorefrontInactive = "STOREFRONT_INACTIVE" // ErrorCodeStorefrontMismatch (HTTP 400): the API key is bound to one // storefront and the request named another. A replay of a key minted for // a different storefront answers the same code as a *RefusalError. ErrorCodeStorefrontMismatch = "STOREFRONT_MISMATCH" // ErrorCodeAlreadyProcessed (refusal): the payment for this idempotency // key already moved money. Mark the order paid; the key is spent. ErrorCodeAlreadyProcessed = "ALREADY_PROCESSED" // ErrorCodePriorAttemptFailed (refusal): the attempt for this key ended // failed, cancelled or abandoned. The key is spent; try again under a // new one. ErrorCodePriorAttemptFailed = "PRIOR_ATTEMPT_FAILED" // ErrorCodeDuplicateRequest (refusal): a session for this key exists but // cannot be handed back yet. Re-POST the SAME key after about a second. ErrorCodeDuplicateRequest = "DUPLICATE_REQUEST" // a charge): card payments are off right now. Nothing was minted or // charged; retry later with the SAME key. ErrorCodePaymentProcessingUnavailable = "PAYMENT_PROCESSING_UNAVAILABLE" // ErrorCodeIdempotencyKeyReused (refusal): this key was first used for a // different amount, currency or card-saving choice. A re-priced order // needs a new key; OrderIdempotencyKey derives one. ErrorCodeIdempotencyKeyReused = "IDEMPOTENCY_KEY_REUSED" )
Error codes the checkout session route answers with, for branching on the ErrorCode of a *RefusalError or an *APIError instead of on message text. The same strings can also arrive on a *ChargeError (see the ChargeError* constants for what they mean there).
The storefront codes mean the session was refused because of the online location (storefront) it would be filed under. They arrive as an *APIError with HTTPStatus set, not as a refusal, and a retry will not change them:
var apiErr *dominaite.APIError
if errors.As(err, &apiErr) && apiErr.ErrorCode == dominaite.ErrorCodeStorefrontNotWhitelisted {
// the site's domain is not whitelisted with the payment provider yet
}
const ( // ChargeErrorPaymentMethodNotActive (409): the method is revoked, expired // or retired; ask the customer for another card via a hosted session with // SaveCard. ChargeErrorPaymentMethodNotActive = "PAYMENT_METHOD_NOT_ACTIVE" // ChargeErrorDuplicateRequest (409): a request with this key is still in // flight; retry with the SAME key in a moment. ChargeErrorDuplicateRequest = "DUPLICATE_REQUEST" // ChargeErrorIdempotencyKeyReused (422): same key, different body or // method; a bug on your side. ChargeErrorIdempotencyKeyReused = "IDEMPOTENCY_KEY_REUSED" // ChargeErrorOutcomeUnknown (502): the provider gave no verdict and the // charge MAY have happened. Charge is set: poll // GetStatus(Charge.TransactionID) or wait for the webhook. Never retry // under a new key. ChargeErrorOutcomeUnknown = "CHARGE_OUTCOME_UNKNOWN" // ChargeErrorFailed (502): nothing was charged. Charge is set when a row // exists (its DeclineClass and DeclineCode are empty), nil when the // provider refused before one. ChargeErrorFailed = "CHARGE_FAILED" // ChargeErrorChargesDisabled (503): nothing was charged; retry later with // the SAME key. ChargeErrorChargesDisabled = "PAYMENT_METHOD_CHARGES_DISABLED" // with the SAME key. ChargeErrorProcessingUnavailable = "PAYMENT_PROCESSING_UNAVAILABLE" )
Charge error codes, in the gateway's own order: the codes ChargePaymentMethod returns as a *ChargeError. CHARGE_DECLINED (HTTP 402) is deliberately not one of them: a decline is a charge result with Status ChargeStatusFailed, not an error.
const ( // RevokeErrorUpstreamContract (502): the provider refused the deletion for // a reason a retry will not fix; contact support with the payment method id. RevokeErrorUpstreamContract = "UPSTREAM_CONTRACT_ERROR" // throttling; retry later. RevokeErrorMerchantAPIUnavailable = "MERCHANT_API_UNAVAILABLE" )
Revoke error codes, in the gateway's own order: the codes RevokePaymentMethod returns as a *RevokeError. Nothing changed under either.
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.
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.
const ( StoredPaymentMethodStatusActive = "active" StoredPaymentMethodStatusRevoked = "revoked" StoredPaymentMethodStatusExpired = "expired" StoredPaymentMethodStatusRetired = "retired" )
Stored payment method status values, in the gateway's own order.
Only active methods can be charged. StoredPaymentMethodStatusRevoked is what Client.RevokePaymentMethod leaves behind; StoredPaymentMethodStatusExpired means the card's expiry date has passed; StoredPaymentMethodStatusRetired means the platform stopped the card on its own (RetiredReason says why) and it never becomes active again, so ask the customer to save a card again.
const ( RetiredReasonHardDecline = "hard_decline" RetiredReasonChargeback = "chargeback" RetiredReasonSourceSaleReversed = "source_sale_reversed" )
Why the platform retired a stored payment method, in the gateway's own order.
RetiredReasonHardDecline: a charge on the card was declined as final. RetiredReasonChargeback: a charge on it was disputed. RetiredReasonSourceSaleReversed: the payment that saved it was fully refunded or disputed.
const ( ChargeStatusSucceeded = "succeeded" ChargeStatusFailed = "failed" ChargeStatusPending = "pending" ChargeStatusCancelled = "cancelled" )
Charge status values returned by ChargePaymentMethod, in the gateway's own order. ChargeStatusSucceeded: the money moved. ChargeStatusFailed: it did not; on a 402 DeclineClass says why. ChargeStatusPending is not terminal: keep polling GetStatus on the charge's TransactionID. ChargeStatusCancelled: an authorization voided before capture, no money moved.
const ( DeclineClassHard = "hard" DeclineClassSoftFunds = "soft_funds" DeclineClassSoftSCARequired = "soft_sca_required" DeclineClassSoftOther = "soft_other" )
Decline classes, coarse enough to act on without reading the issuer's code:
- DeclineClassHard: do not retry this card, ask the customer for another one.
- DeclineClassSoftFunds: insufficient funds; retry later (after the customer's payday, not in a loop).
- DeclineClassSoftSCARequired: the issuer wants the customer present; send them through a hosted checkout session with SaveCard instead of charging off-session again.
- DeclineClassSoftOther: a transient issuer or network condition; one retry later is reasonable.
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.
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.
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 ¶
var ChargeErrorCodes = []string{ ChargeErrorPaymentMethodNotActive, ChargeErrorDuplicateRequest, ChargeErrorIdempotencyKeyReused, ChargeErrorOutcomeUnknown, ChargeErrorFailed, ChargeErrorChargesDisabled, ChargeErrorProcessingUnavailable, }
ChargeErrorCodes is the complete v1 vocabulary of ChargeError.ErrorCode. Unknown codes still arrive as a *ChargeError; branch on the ones you know.
var ChargeStatuses = []string{ ChargeStatusSucceeded, ChargeStatusFailed, ChargeStatusPending, ChargeStatusCancelled, }
ChargeStatuses is the complete v1 charge status vocabulary. Treat a value outside this list as still open.
var DeclineClasses = []string{ DeclineClassHard, DeclineClassSoftFunds, DeclineClassSoftSCARequired, DeclineClassSoftOther, }
DeclineClasses is the complete v1 decline class vocabulary.
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, *ChargeError, *RevokeError, *AuthError, *RateLimitError, *APIError, *TransportError or *ValidationError, or errors.As with the Error interface to catch any of them while keeping the message.
var RevokeErrorCodes = []string{ RevokeErrorUpstreamContract, RevokeErrorMerchantAPIUnavailable, }
RevokeErrorCodes is the complete v1 vocabulary of RevokeError.ErrorCode.
var Statuses = []string{ StatusPending, StatusProcessing, StatusSucceeded, StatusFailed, StatusRefunded, StatusPartiallyRefunded, StatusCancelled, StatusDisputed, StatusRequiresCapture, StatusAbandoned, }
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.
var StoredPaymentMethodRetiredReasons = []string{ RetiredReasonHardDecline, RetiredReasonChargeback, RetiredReasonSourceSaleReversed, }
StoredPaymentMethodRetiredReasons is the complete v1 retired-reason vocabulary. Treat a value outside this list as retired for an unknown reason.
var StoredPaymentMethodStatuses = []string{ StoredPaymentMethodStatusActive, StoredPaymentMethodStatusRevoked, StoredPaymentMethodStatusExpired, StoredPaymentMethodStatusRetired, }
StoredPaymentMethodStatuses is the complete v1 stored-payment-method status vocabulary. Treat a value outside this list as not chargeable.
var StorefrontErrorCodes = []string{ ErrorCodeStorefrontMismatch, ErrorCodeStorefrontInactive, ErrorCodeStorefrontNotWhitelisted, }
StorefrontErrorCodes are the storefront codes a session create can be refused with, in the gateway's own order: ErrorCodeStorefrontMismatch (HTTP 400), ErrorCodeStorefrontInactive (409) and ErrorCodeStorefrontNotWhitelisted (409). None is retryable. They arrive as an *APIError, not as the HTTP 200 refusal shape, so they are not session refusal codes.
Functions ¶
func CurrencyExponent ¶ added in v0.3.0
CurrencyExponent returns the number of minor-unit digits the gateway uses for a currency: 2 for EUR (1 EUR is 100 cents), 0 for JPY and HUF, 3 for KWD. HUF differs from ISO 4217 on purpose; see ToMinorUnits. The code is case-insensitive. ISK, KRW, OMR, JOD and TND are refused as not supported, and an unknown currency is refused too, both with a *ValidationError.
func IsPaid ¶ added in v0.3.0
IsPaid reports whether a status means the payment is complete: true for StatusSucceeded only. StatusRequiresCapture is not paid yet (the funds are held, not captured), and neither is anything this SDK does not recognise.
func IsTerminal ¶ added in v0.3.0
IsTerminal reports whether a status is final, so polling can stop: succeeded, failed, cancelled, abandoned, refunded and partially_refunded. Everything else is still open and worth polling, including pending, processing, requires_capture, disputed and any status this SDK does not recognise: a value the API adds later must never close a live order.
func OrderIdempotencyKey ¶ added in v0.3.0
OrderIdempotencyKey builds the idempotency key for one payment of one order: "{scope}-{orderID}-{amountMinor}-{CURRENCY}", for example OrderIdempotencyKey("checkout", "order-1042", 2500, "eur") is "checkout-order-1042-2500-EUR".
Derive the key from the order, never per call. Your payment page will be re-entered: a reload, the Back button, a second tab, a retry after a timeout. The same order at the same amount produces the same key every time, so each of those replays the session already open (same TransactionID, same cashier handles) instead of opening a second payment. A changed amount or currency (the cart was edited) produces a new key and therefore a fresh session; the old key replayed with a new amount would be refused with IDEMPOTENCY_KEY_REUSED.
scope is a fixed label for the call site ("checkout", "renewal"), so two different kinds of payment for the same order never share a key. SaveCard is part of a session's identity too: if the payer can flip it after a session was opened, use a different scope for each choice (for example "checkout-save"). Keep scope free of values that vary per request.
amountMinor is in MINOR units and must be positive. currency is ISO 4217 and is uppercased here, so "eur" and "EUR" give the same key. Returns a *ValidationError when scope or orderID is blank, the amount is not positive, the currency is not three ASCII letters, or the key breaks the key rules: at most 100 characters, visible ASCII only (0x21 to 0x7E), so an order id with a space or a non-ASCII letter is refused rather than silently rewritten.
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.
func ToMinorUnits ¶ added in v0.3.0
ToMinorUnits converts a decimal amount string to the integer minor units Amount takes, by the exponent the gateway uses for the currency:
ToMinorUnits("0.30", "EUR") // 30
ToMinorUnits("25", "EUR") // 2500
ToMinorUnits("1500", "JPY") // 1500
ToMinorUnits("1500", "HUF") // 1500: whole forints, NOT ISO 4217's 150000
ToMinorUnits("1.250", "KWD") // 1250
Known currencies: EUR, USD, GBP, CAD, AUD, CHF, BGN, RON, PLN, CZK, SEK, DKK, NOK (2 decimals), JPY, HUF (0) and BHD, KWD (3).
The conversion is exact, done on the digits, never through a float (19.99 as a float64 times 100 is 1998.9999999999998, which truncates to 1998). The amount is plain digits with an optional point: no sign, no thousands separators, no exponent. More fractional digits than the currency has is refused, zeros included ("0.305" and "25.000" EUR, "100.0" JPY): nothing is rounded or trimmed, because rounding a price is a business decision, not the SDK's. Surrounding whitespace is ignored.
Returns a *ValidationError for a malformed amount, an unknown or unsupported currency, or an amount too large for int64.
Types ¶
type APIError ¶
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 404 from ChargePaymentMethod or RevokePaymentMethod an id that is not yours. 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. A 409 carrying ErrorCodeStorefrontNotWhitelisted or ErrorCodeStorefrontInactive, or a 400 carrying ErrorCodeStorefrontMismatch, means the storefront refused the session. Empty when the API named no code.
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 ChargeError ¶ added in v0.3.0
type ChargeError struct {
HTTPStatus int
ErrorCode string
// Charge is the charge row the gateway attached to its answer, when it did.
Charge *PaymentMethodCharge
// TransactionID is Charge.TransactionID, for polling GetStatus. Empty
// without a charge.
TransactionID string
// Raw is the whole envelope the gateway sent, for fields not modelled above.
Raw json.RawMessage
// contains filtered or unexported fields
}
ChargeError means the gateway answered a charge with an error code instead of a charge result: HTTP 409, 422, 502 or 503 with one of the ChargeError* codes on ErrorCode (see each constant for what to do). HTTPStatus carries the status, Message the gateway's own text.
Charge is the charge row the gateway attached to its answer, when it did: always for CHARGE_OUTCOME_UNKNOWN, sometimes for CHARGE_FAILED, never for the rest. TransactionID is a shortcut for Charge.TransactionID, empty when there is no charge:
charge, err := client.ChargePaymentMethod(ctx, id, params)
var chargeErr *dominaite.ChargeError
if errors.As(err, &chargeErr) && chargeErr.ErrorCode == dominaite.ChargeErrorOutcomeUnknown {
// poll client.GetStatus(ctx, chargeErr.TransactionID); do not retry under a new key
}
Only authentication (401/403, *AuthError), an id that is not yours (404, *APIError), validation (400, *APIError), rate limiting (429, *RateLimitError) and network failures or a 5xx without a code (*TransportError) keep their generic errors on this route.
type ChargePaymentMethodParams ¶ added in v0.3.0
type ChargePaymentMethodParams 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"`
Description string `json:"description,omitempty"`
// IdempotencyKey is required. Derive it from what you are charging for
// (the order, the billing period), never per attempt: retrying with the
// same key never charges the card twice, so on a timeout retry with the
// same key. It travels in the header and in the signature, never in the
// body. 1 to 100 visible ASCII characters; anything else is refused with a
// *ValidationError before anything is sent.
IdempotencyKey string `json:"-"`
}
ChargePaymentMethodParams are the parameters for Client.ChargePaymentMethod. Amount, Currency and OrderReference are required.
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"`
// StoredPaymentMethod is the card kept on file by a session created with
// SaveCard. Present once the payment is approved, and it stays present
// after a revoke with Status StoredPaymentMethodStatusRevoked; nil (absent
// on the wire) until then, for sessions without SaveCard, and for declined
// or abandoned ones. Store StoredPaymentMethod.ID against your customer -
// it is what Client.ChargePaymentMethod takes.
//
// Not to be confused with the gateway's paymentMethod field, which is the
// string category of how the payer paid ("card", "wallet", ...) and is only
// reachable through Raw.
StoredPaymentMethod *StoredPaymentMethod `json:"storedPaymentMethod,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, and when WithBaseURL was given a non-https URL outside loopback.
func (*Client) ChargePaymentMethod ¶ added in v0.3.0
func (c *Client) ChargePaymentMethod(ctx context.Context, paymentMethodID string, params ChargePaymentMethodParams) (*PaymentMethodCharge, error)
ChargePaymentMethod charges a card kept on file, off-session: no widget, no payer present.
paymentMethodID is the ID from GetStatus().StoredPaymentMethod of a session you created with SaveCard. The charge is signed like a session and carries an Idempotency-Key, which you must set (derive it from the billing period, never per attempt), so retrying after a timeout WITH THE SAME KEY never charges the card twice: the gateway replays its first answer, HTTP status included.
The HTTP status is the contract on this route. 201 (200 on a replay) returns the charge, Status ChargeStatusSucceeded, ChargeStatusPending or ChargeStatusCancelled. 402 returns the charge too: a decline is not an error, the charge has Status ChargeStatusFailed plus a DeclineClass telling you whether to give up on the card (hard), wait (soft_funds, soft_other) or bring the customer back for a hosted session (soft_sca_required). ChargeStatusPending is not terminal - poll GetStatus(charge.TransactionID).
Errors it returns:
- *ValidationError: bad arguments; nothing was sent.
- *ChargeError: 409, 422, 502 or 503 with a code; branch on ErrorCode. CHARGE_OUTCOME_UNKNOWN carries the charge row (Charge, TransactionID): poll GetStatus with it, never retry under a new key.
- *AuthError: wrong credentials, bad signature, clock off, IP not allowlisted.
- *APIError: 404 for an id that is not yours (ErrorCode PAYMENT_METHOD_NOT_FOUND), 400 validation, or an unexpected response; inspect HTTPStatus.
- *RateLimitError: HTTP 429; back off and reschedule with the same key.
- *TransportError: network failure or a 5xx without a code. Safe to retry WITH the same key.
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, including a missing IdempotencyKey; 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 and PAYMENT_PROCESSING_UNAVAILABLE, 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 gets that session back while it is still open: same TransactionID, same cashier handles. When the earlier attempt already moved money, ended, or cannot be handed back yet, the API answers with a replay refusal (*RefusalError, ErrorCode ALREADY_PROCESSED, PRIOR_ATTEMPT_FAILED or DUPLICATE_REQUEST). Recover through RefusalError.TransactionID with GetStatus when the API named one.
params.IdempotencyKey is required here as everywhere: the SDK never invents one. Derive it with OrderIdempotencyKey.
PAYMENT_PROCESSING_UNAVAILABLE is retried in both of its forms: a 503 (a *TransportError like any 5xx) and the HTTP 200 refusal the session route answers with (a *RefusalError). Either way nothing was minted and the gateway asks for a retry with the same key. If it is still unavailable after the last attempt, that refusal is what you get back.
Every other refusal, 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 ¶
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.
StoredPaymentMethod is the card kept on file by a session created with SaveCard: present once the payment is approved (and it stays after a revoke, with Status revoked), nil until then, for sessions without SaveCard and for declined or abandoned ones. Its ID is what ChargePaymentMethod and RevokePaymentMethod take.
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) 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.
- *RateLimitError: HTTP 429; back off, the SDK does not retry it for you.
- *TransportError: network failure or 5xx.
func (*Client) RevokePaymentMethod ¶ added in v0.3.0
RevokePaymentMethod revokes a card kept on file. The saved credential is deleted at the payment provider and the method's status becomes StoredPaymentMethodStatusRevoked; a later ChargePaymentMethod on it is refused with PAYMENT_METHOD_NOT_ACTIVE. Returns nil on success (HTTP 204), and again for an already revoked method, so retrying a timed-out revoke is safe. Not a payment operation: no idempotency key is signed.
Errors it returns:
- *RevokeError: the gateway refused and nothing changed; MERCHANT_API_UNAVAILABLE (503, retry later) or UPSTREAM_CONTRACT_ERROR (502, the provider refused for good - contact support with the id).
- *APIError: 404 for an id that is not yours, or an unexpected response.
- *AuthError, *RateLimitError, *TransportError: as everywhere else.
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"`
// SaveCard asks the gateway to keep the card on file once this payment is
// approved, so you can charge it again later with Client.ChargePaymentMethod.
// The stored method shows up on CheckoutStatus.StoredPaymentMethod after the
// payment succeeds; a declined first payment stores nothing. The card details
// themselves never reach you: you get an id, a brand and the last four digits.
SaveCard bool `json:"saveCard,omitempty"`
// IdempotencyKey is required. Derive it from the order with
// OrderIdempotencyKey: the same order at the same amount must produce the
// same key, so a reload, a Back button or a retry after a timeout replays
// the open session instead of opening a second payment. It travels in the
// header and in the signature, never in the body. 1 to 100 visible ASCII
// characters; anything else is refused with a *ValidationError before
// anything is sent.
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.
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 ¶
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 ¶
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 PaymentMethodCharge ¶ added in v0.3.0
type PaymentMethodCharge struct {
// ChargeID is ch_ followed by 32 hex characters. Store it against the
// order; it is what support asks for.
ChargeID string `json:"chargeId"`
// Status is one of the ChargeStatus* constants. Treat anything you do not
// recognise as still open.
Status string `json:"status"`
// DeclineClass is one of the DeclineClass* constants, set on a 402 decline.
// Empty everywhere else (the gateway omits it on the wire).
DeclineClass string `json:"declineClass,omitempty"`
// DeclineCode is the raw decline code, for your logs; branch on
// DeclineClass instead. Empty when DeclineClass is.
DeclineCode string `json:"declineCode,omitempty"`
// TransactionID is the transaction the charge created; readable with
// GetStatus.
TransactionID string `json:"transactionId"`
// Raw is the unparsed charge object, for fields this struct does not model yet.
Raw json.RawMessage `json:"-"`
}
PaymentMethodCharge is what ChargePaymentMethod returns, for a placed charge (HTTP 201) and for a provider decline (HTTP 402, Status ChargeStatusFailed) alike. Also carried on a *ChargeError when the gateway attached the charge row to its answer.
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.
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 (the ErrorCode* constants):
- PAYMENT_PROCESSING_UNAVAILABLE: card payments are off right now; retry later.
- DUPLICATE_REQUEST: a session for this idempotency key exists but cannot be handed back yet; re-POST the same key shortly.
- 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 amount, currency or card-saving choice; a re-priced order needs a new key.
- STOREFRONT_MISMATCH: the key was first used for a different storefront.
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 RevokeError ¶ added in v0.3.0
type RevokeError struct {
HTTPStatus int
ErrorCode string
// Raw is the whole envelope the gateway sent, for fields not modelled above.
Raw json.RawMessage
// contains filtered or unexported fields
}
RevokeError means the gateway refused to revoke a stored payment method: HTTP 502 or 503 with one of the RevokeError* codes on ErrorCode. Nothing changed either way. An id that is not yours is still the generic *APIError with HTTPStatus 404.
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.
type StoredPaymentMethod ¶ added in v0.3.0
type StoredPaymentMethod struct {
// ID is opaque: pm_ followed by 32 hex characters, case-sensitive. The
// handle you charge and revoke with.
ID string `json:"id"`
// Brand is the card brand as the gateway reports it, e.g. "visa", "mastercard".
Brand string `json:"brand,omitempty"`
// Last4 is the last four digits of the card number, for display only.
Last4 string `json:"last4,omitempty"`
// ExpiryMonth is 1 to 12.
ExpiryMonth int `json:"expiryMonth,omitempty"`
// ExpiryYear is four digits, e.g. 2029.
ExpiryYear int `json:"expiryYear,omitempty"`
// Status is one of the StoredPaymentMethodStatus* constants. Treat any value
// you do not recognise as not chargeable.
Status string `json:"status"`
// RetiredReason is one of the RetiredReason* constants when Status is
// StoredPaymentMethodStatusRetired, and kept if the card is revoked
// afterwards. Empty on every other card (the gateway sends null or omits it).
RetiredReason string `json:"retiredReason,omitempty"`
}
StoredPaymentMethod is a card kept on file. Never the card number, never the PSP token - only what you may show a customer. Brand, Last4 and the expiry are zero when the provider did not report them (the gateway omits null fields on the wire).
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.
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
}
Source Files
¶
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. |