satim-module - v1.0.0
    Preparing search index...

    Class Satim

    SATIM REST API client.

    Construction binds credentials to a module-private WeakMap entry (see SatimConfig.initFromCredentials). The HTTP client is either caller-injected or built with the provided options.

    Instances are safe to share across concurrent requests because every fluent setter returns a clone — no caller can mutate state observed by another caller.

    Hierarchy

    • SatimConfig
      • Satim
    Index

    Constructors

    Properties

    httpClientService: HttpClientService
    testMode: boolean = false
    _language: Language = "FR"
    _currency: CurrencyCode = "012"
    _amount?: number
    _failUrl?: string
    _returnUrl?: string
    _dynamicCallbackUrl?: string
    _description?: string
    _orderNumber?: string
    _sessionTimeoutSecs?: number
    _idempotencyKey?: string
    _userDefinedFields: Record<string, string> = {}

    Accessors

    • get username(): string

      Returns string

      Merchant username. Protected — never exposed publicly.

    • get password(): string

      Returns string

      Merchant password. Protected — never exposed publicly.

    • get terminalId(): string

      Returns string

      Merchant terminal ID. Protected — never exposed publicly.

    Methods

    • Override to rebuild the default HTTP client when testMode changes (the base URL is baked in at construction). A caller-injected client is preserved verbatim — switching testMode will not replace it.

      Parameters

      • isEnabled: boolean

      Returns this

      Clone with testMode set and (if applicable) a fresh default HttpClientService matching the new mode.

    • Override to copy transport-related state alongside config state.

      The base SatimConfig.clone only knows about config fields; the Satim subclass owns httpClientService and two private flags that must also propagate. Uses cast-to-any because the fields are declared readonly — only the clone's constructor-equivalent (this method) may set them.

      Returns this

    • Register a pre-authorization (fund hold) via /registerPreAuth.do.

      Holds the funds on the customer's card without capturing. Capture later via confirm() or release via reverseOrder().

      Same preconditions, postconditions, retry semantics, and exceptions as register.

      Returns Promise<RegisterResponse>

    • Confirm (deposit) a payment via /public/acknowledgeTransaction.do.

      Preconditions: orderId matches the strict order-ID format; expectedAmount passes assertConfirmAmount (finite, positive, ≤ MAX_SAFE_AMOUNT, ≤ 2 decimal places).

      Postcondition: returns a ConfirmResponse. When the response satisfies isSuccessful(), verifyAmount(expectedAmount) has already run — a mismatch throws before this method returns.

      Retry: disabled. A retry could double-fire merchant side effects derived from observing the success state.

      Security: this is the only safe path to confirm a payment. The automatic amount check defends against partial-capture manipulation; the call must happen server-side, never from the customer's browser.

      Complexity: O(network).

      Parameters

      • orderId: string
      • expectedAmount: number

      Returns Promise<ConfirmResponse>

      SatimInvalidArgumentError on malformed orderId or expectedAmount.

      SatimUnexpectedResponseError on amount mismatch (carries the expected vs actual minor-unit values).

      Any gateway/transport exception per handleApiRequest.

    • Query order status via /getOrderStatus.do.

      Idempotent — automatically retried on transient failures (5xx, timeout). Concurrent calls for the same orderId are collapsed into a single in-flight request — the second caller receives the first's response without a second round trip.

      Preconditions: orderId matches the strict order-ID format.

      Complexity: O(network) — but up to 1 + maxRetries round trips on transient errors.

      Parameters

      • orderId: string

      Returns Promise<ConfirmResponse>

      SatimInvalidArgumentError on malformed orderId.

      Any gateway/transport exception per handleApiRequest.

    • Query multiple orders in parallel via concurrent /getOrderStatus.do calls.

      Fires all queries simultaneously. Concurrent calls for the same orderId are deduplicated by HttpClientService — passing duplicates in the array does not multiply requests.

      Rejects with the first error encountered; all in-flight requests still run to completion (standard Promise.all semantics).

      Parameters

      • orderIds: string[]

      Returns Promise<ConfirmResponse[]>

      SatimInvalidArgumentError on any malformed orderId.

      Any gateway/transport exception per handleApiRequest.

    • Pre-warm the TCP+TLS connection to the SATIM gateway.

      Call this once during application startup (or just before a checkout flow begins) to avoid paying the TCP handshake + TLS negotiation cost (~50–200 ms) on the first real payment request.

      Sends a single probe request to /getOrderStatus.do with a known-unknown order ID. The gateway responds immediately with ErrorCode 6; the connection is then established and kept alive for subsequent requests.

      This method never throws — if the probe fails (network down, gateway unreachable) the error is silently discarded. The only consequence is that the first real request will incur the normal handshake cost.

      Returns Promise<void>

    • Refund a captured payment via /refund.do.

      Retry: disabled. A retry could double-refund.

      Preconditions: orderId valid; amount passes assertRefundAmount (finite, positive, ≤ MAX_SAFE_AMOUNT, ≤ 2 decimal places, ≥ 1 minor unit after conversion).

      Parameters

      • orderId: string
      • amount: number

      Returns Promise<ConfirmResponse>

      SatimInvalidArgumentError on malformed inputs.

      Any gateway/transport exception per handleApiRequest.

    • Void a pre-settlement payment via /reverse.do.

      Cheaper than refund — cancels the authorization before the acquirer settles, avoiding processing fees. Applies to status 1 (pre-authorized) and 2 (deposited but not yet settled) orders.

      Retry: disabled.

      Parameters

      • orderId: string

      Returns Promise<ConfirmResponse>

      SatimInvalidArgumentError on malformed orderId.

      Any gateway/transport exception per handleApiRequest.

    • Register with automatic idempotency.

      Derives a deterministic externalRequestId and orderNumber from merchantRef, then calls register. Safe to retry — the gateway deduplicates on the derived key.

      If the gateway returns ErrorCode: "1" (duplicate order with a conflicting amount/currency for the same merchantRef), the SatimGatewayError is translated to SatimDuplicateOrderError so callers can recover via status(originalOrderId) from their own persistence layer.

      Preconditions: merchantRef is a non-empty string after trim; _returnUrl and _amount set.

      Postcondition: same as register.

      Parameters

      • merchantRef: string

      Returns Promise<RegisterResponse>

      SatimInvalidArgumentError when merchantRef is empty.

      SatimMissingDataError when registration prerequisites missing.

      SatimDuplicateOrderError on conflicting prior registration.

      Any other exception register() can throw.

    • Pre-authorization variant of safeRegister.

      Domain-separated from safeRegister via the "preauth" mode tag in the derived key — a register key never collides with a preauth key for the same merchantRef.

      Parameters

      • merchantRef: string

      Returns Promise<RegisterResponse>

    • Bind credentials to this instance via the module-private WeakMap.

      Preconditions: this instance has no credentials currently bound; all three fields are non-empty strings after trim, with username and password ≤ 100 chars and terminalId ≤ 16 chars.

      Runtime type guards reject objects that satisfy SatimCredentials structurally but carry non-string payloads. Cannot be called twice on the same instance.

      Parameters

      Returns void

      SatimInvalidArgumentError when credentials are already bound, any field is non-string, or length limits (AN.100 / AN.16) are exceeded.

      SatimMissingDataError when any field is empty after trim.

    • Set the payment amount in major currency units (whole DA for register).

      Parameters

      • amount: number

      Returns this

      Clone with the amount set.

      SatimInvalidArgumentError via assertRegisterAmount on shape violations, sub-50-DA values, or fractional dinars.

    • Set the payment-page description (SATIM AN.600).

      Parameters

      • description: string

      Returns this

      SatimInvalidArgumentError on non-string, overlong, or markup-bearing input.

    • Set the payment currency by ISO 3-letter code.

      Parameters

      • curr: "DZD" | "USD" | "EUR"

        One of "DZD", "USD", "EUR". Mapped to numeric ISO 4217 internally.

      Returns this

      SatimInvalidArgumentError on unsupported currencies.

    • Set the URL the customer is redirected to on payment failure. Falls back to returnUrl when sent to the gateway if not set.

      Parameters

      • url: string

      Returns this

      SatimInvalidArgumentError via assertSafeUrl.

    • Set the URL the customer is redirected to after payment.

      Parameters

      • url: string

      Returns this

      SatimInvalidArgumentError via assertSafeUrl.

    • Set the server-to-server webhook URL the gateway POSTs status changes to.

      Parameters

      • url: string

      Returns this

      SatimInvalidArgumentError via assertSafeUrl.

    • Set a custom 1-10 character alphasatim-module order number. Defaults to a CSPRNG-generated 10-digit value if unset at register time.

      Parameters

      • orderNumber: string | number

      Returns this

      SatimInvalidArgumentError on format violations.

    • Set a single jsonParams key/value pair.

      Reserved keys (force_terminal_id, __proto__, constructor, prototype) are rejected here as the first line of defence against terminal-ID injection and prototype pollution. The Satim.buildData method strips force_terminal_id again before send, providing defence in depth.

      Parameters

      • key: string
      • value: string

      Returns this

      SatimInvalidArgumentError on reserved keys, malformed keys, non-string values, or values exceeding 20 characters.

    • Set multiple jsonParams key/value pairs.

      Iterates own enumerable properties only; inherited and symbol-keyed properties are ignored. Each pair is validated as if passed to userDefinedField.

      Complexity: O(n) where n is the number of fields.

      Parameters

      • fields: Record<string, string>

      Returns this

      SatimInvalidArgumentError on the first invalid entry.

    • Set the payment session timeout in seconds ([600, 86400]).

      Parameters

      • seconds: number

      Returns this

      SatimInvalidArgumentError on out-of-range or non-integer input.

    • Set the idempotency key (externalRequestId).

      Setting an idempotency key enables automatic retries for register() and registerPreAuth() — see Satim.registerAt. Without a key, registration is not retried because a retry after a timeout could create a duplicate order on the gateway.

      Use deriveIdempotencyKey to derive a stable key from your internal order reference, or call safeRegister(merchantRef) for a one-shot wrapper that does the derivation.

      Parameters

      • key: string

      Returns this

      SatimInvalidArgumentError on format violations.

    • Custom JSON serializer that redacts credentials.

      Called automatically by JSON.stringify(satim). Returns a snapshot with username, password, terminalId replaced by "[REDACTED]" and all other configuration state intact (for debugging).

      Returns Record<string, unknown>

    • Stringification — never reveals credentials.

      Returns string

    • Primitive coercion hook — delegates to toString.

      Returns string