# Poll the status of any v3 async operation Source: https://docs.spenza.com/api-reference/async-status/poll-the-status-of-any-v3-async-operation /openapi.yaml get /api/v3/transactions/{transactionId} Universal status poll for any async endpoint that returns a `transactionId` — plan purchase, eSIM provisioning, top-up, port-in, subscription changes. **No authentication required** — the `transactionId` itself is the bearer, matching every other endpoint that hands one out. A `FAILED` transaction is still a `200` — check `data.status`, not the HTTP status. `data.errorCode` is one of the standard `ApiErrorCode` values when the failure is classifiable; `data.error` is a short, partner-safe message. `data.timestamp` is generated fresh on every request (it is when the response was built, not when the transaction record last changed) — don't confuse it with `data.createdAt` / `data.updatedAt`. # Exchange credentials for a token Source: https://docs.spenza.com/api-reference/authentication/exchange-credentials-for-a-token /openapi.yaml post /api/v1.1/auth/token Exchange your API key and secret for a 1-hour bearer token. This endpoint itself requires no authentication — your key and secret *are* the credentials being verified. Note the response fields are **snake_case** (`access_token`, not `accessToken`) — this endpoint is deliberately OAuth2/RFC 6749-shaped so existing OAuth2 client libraries work against it. Every other endpoint in this API uses camelCase. # Add prepaid credit Source: https://docs.spenza.com/api-reference/billing/add-prepaid-credit /openapi.yaml post /api/v1.1/top-up Create a hosted Stripe checkout link to add prepaid credit. `amount` is in the currency's **major unit** (e.g. `100` = $100.00). The returned `transactionId` moves to `COMPLETED`/`FAILED` once Stripe's checkout webhook fires — poll `statusEndpoint`, not this call, for the outcome. # Download invoice PDF Source: https://docs.spenza.com/api-reference/billing/download-invoice-pdf /openapi.yaml get /api/v1.1/invoices/{id}/pdf On success, returns a `302` redirect to the PDF URL — **no JSON envelope on the 302 itself**, this is the one endpoint that writes a raw HTTP response instead of the standard envelope. Error responses are still the standard JSON envelope. Resolution precedence, in order: (1) a previously-stored S3 copy of the invoice PDF; (2) if a Stripe invoice PDF and invoice id are both on file, persist it to S3 now and use that URL, falling back to (3) the raw Stripe invoice PDF URL if that persist attempt fails; (4) the Stripe receipt URL; (5) the raw Stripe invoice PDF URL alone (no invoice id on file). The Stripe fallback URLs are temporary/time-limited by Stripe. # Get an invoice Source: https://docs.spenza.com/api-reference/billing/get-an-invoice /openapi.yaml get /api/v1.1/invoices/{id} Get a single invoice's full detail, line items, and usage breakdown. # Get credit balance Source: https://docs.spenza.com/api-reference/billing/get-credit-balance /openapi.yaml get /api/v1.1/credit-balance Available prepaid credit balance by currency. # List invoices Source: https://docs.spenza.com/api-reference/billing/list-invoices /openapi.yaml get /api/v1.1/invoices List invoices, paginated, with date filters. `from`/`to` are **date-only** (`YYYY-MM-DD`) here — unlike Orders/Transactions, which take full ISO datetimes. # Create a device-group Source: https://docs.spenza.com/api-reference/device-groups/create-a-device-group /openapi.yaml post /api/v1.1/device-groups # Delete a device-group Source: https://docs.spenza.com/api-reference/device-groups/delete-a-device-group /openapi.yaml delete /api/v1.1/device-groups/{name} # Get a device-group Source: https://docs.spenza.com/api-reference/device-groups/get-a-device-group /openapi.yaml get /api/v1.1/device-groups/{name} # List device-groups Source: https://docs.spenza.com/api-reference/device-groups/list-device-groups /openapi.yaml get /api/v1.1/device-groups # Move a device into this group Source: https://docs.spenza.com/api-reference/device-groups/move-a-device-into-this-group /openapi.yaml post /api/v1.1/device-groups/{name}/devices # Remove a device from this group Source: https://docs.spenza.com/api-reference/device-groups/remove-a-device-from-this-group /openapi.yaml delete /api/v1.1/device-groups/{name}/devices/{meid} No default device-group exists, so the device's group is simply cleared (`movedTo` is `null`). # Update a device-group Source: https://docs.spenza.com/api-reference/device-groups/update-a-device-group /openapi.yaml put /api/v1.1/device-groups/{name} # Assign a device to a user Source: https://docs.spenza.com/api-reference/devices/assign-a-device-to-a-user /openapi.yaml post /api/v1.1/devices/{imei}/assign The "user" here is a Employee — the same resource as `/api/v1.1/users` — not a Team Member/admin. # Get a device Source: https://docs.spenza.com/api-reference/devices/get-a-device /openapi.yaml get /api/v1.1/devices/{imei} Get a device's details, including who it's currently assigned to. # List devices in your catalog Source: https://docs.spenza.com/api-reference/devices/list-devices-in-your-catalog /openapi.yaml get /api/v1.1/team-devices List the phones/tablets you can hand out to your team. # Unassign a device Source: https://docs.spenza.com/api-reference/devices/unassign-a-device /openapi.yaml post /api/v1.1/devices/{imei}/unassign # Get eSIM activation QR Source: https://docs.spenza.com/api-reference/esim/get-esim-activation-qr /openapi.yaml get /api/v1.1/esim/{iccid}/qr Re-fetch the eSIM's activation QR image URL and activation code. Deliberately does not regenerate/rotate the eSIM profile on a live carrier — it's a read, not a mutation — so `activationCode` may be `null` if it was never persisted. # Provision an eSIM, optionally with a plan Source: https://docs.spenza.com/api-reference/esim/provision-an-esim-optionally-with-a-plan /openapi.yaml post /api/v1.1/esim Provision an eSIM. Omit `planId` for a bare eSIM (SIM-only provisioning is only supported for the SpenzaJ carrier family today — other carriers return `501` on the SIM-only path); include `planId` to also activate a plan in the same operation. Always asynchronous — `202` with a `transactionId`/`statusEndpoint` to poll. On completion, `result` is `{ mdn, iccid, qrCode }` (or `{ orderId }` if those aren't available). # Send an SMS Source: https://docs.spenza.com/api-reference/messaging/send-an-sms /openapi.yaml post /api/v1.1/sms Send a Mobile-Originated (MO) SMS from a number provisioned on your account. Requires the account's `Admin` role tier. **MO SMS is only implemented for some operators** (SpenzaJ today) — everyone else gets `501`. This is a synchronous endpoint that returns `201` directly (NestJS's default for `@Post()`, since the handler has no `@HttpCode` override); it does not follow the async `202` + transaction-polling pattern used elsewhere. `fromNumber`, `toNumber`, and `text` are all shown as `required` below to reflect this endpoint's actual runtime behavior — enforcement happens in controller logic, not in the underlying DTO. `toNumber` is only validated for E.164 format; it is not checked against any ownership/allow-list. # Get notification preferences Source: https://docs.spenza.com/api-reference/notifications/get-notification-preferences /openapi.yaml get /api/v1.1/notification-preferences Always returns the full preference matrix — one entry per event type, even ones you've never touched. Unset keys resolve to that key's default: `sendOnboardingNotification` defaults `true` (opt-out); every other key defaults `false` (opt-in). # List notifications Source: https://docs.spenza.com/api-reference/notifications/list-notifications /openapi.yaml get /api/v1.1/notifications List notifications for your account, newest first. `meta` carries an extra `unreadCount` field alongside the usual pagination fields — `unreadCount` is always the account-wide unread total; it is not filtered by the `status` query parameter and does not reflect the returned page's contents. # Update a notification preference Source: https://docs.spenza.com/api-reference/notifications/update-a-notification-preference /openapi.yaml put /api/v1.1/notification-preferences Enable or disable exactly one preference key per call — despite the plural resource name, this is a single-key update. Returns the full matrix so you can confirm without a follow-up GET. # Check port-in eligibility Source: https://docs.spenza.com/api-reference/numbers-&-port-in/check-port-in-eligibility /openapi.yaml post /api/v1.1/port-in/eligibility Check whether a number is eligible for port-in without submitting one — read-only, no order created. An ineligible number is a `200` with `eligible: false`, not an HTTP error. Only the **SpenzaJ** carrier actually implements this check today; every other carrier (Simetry, Soracom, EsimGo, CiscoJasper, Granite, Webbing, Boom) returns `501`. # List port-in requests Source: https://docs.spenza.com/api-reference/numbers-&-port-in/list-port-in-requests /openapi.yaml get /api/v1.1/port-ins List port-in requests and their status, paginated. # Submit a port-in Source: https://docs.spenza.com/api-reference/numbers-&-port-in/submit-a-port-in /openapi.yaml post /api/v3/port-in **The only port-in submission endpoint** — there is no `POST /api/v1.1/port-ins`. Move an existing number from another carrier into Spenza. Always asynchronous. **Two contract exceptions worth calling out:** 1. **Requires an account role**, not just a valid bearer token — `Admin`, `Super Admin`, or `Standard Admin`. 2. **Response is not on the standard envelope.** Success is a flat `{ success, transactionId, statusEndpoint, message, timestamp }` — no `data` wrapper — and `statusEndpoint` points at the **singular** legacy path `/api/v3/transaction/{id}/status` (not the plural `/api/v3/transactions/{id}` used everywhere else — both resolve, but this is the literal value returned). A synchronous validation error is `{ success: false, error: "", timestamp }` — note `error` is a bare string here, not an `{code, message}` object. Identify the target line via `plan`, or via `Operator` + `network` directly. Idempotency is supported via an `Idempotency-Key` header (handled inline, not the standard interceptor) — a replay returns the same shape with `message: "Port-in already initiated (idempotent replay)"`. # Get an order Source: https://docs.spenza.com/api-reference/orders-&-transactions/get-an-order /openapi.yaml get /api/v1.1/orders/{id} Get an order and the transactions raised against it (embedded, capped at 100 — use `GET /api/v1.1/transactions` for the full paginated history). # List orders Source: https://docs.spenza.com/api-reference/orders-&-transactions/list-orders /openapi.yaml get /api/v1.1/orders List order history, paginated. `from`/`to` are **full ISO 8601 datetimes** here (unlike Invoices' date-only filters) — a bare date parses to UTC midnight, so `from == to` collapses the range to a single instant; set `to` to end-of-day explicitly. # List transactions Source: https://docs.spenza.com/api-reference/orders-&-transactions/list-transactions /openapi.yaml get /api/v1.1/transactions Financial transaction history, paginated — charges and refunds. `type` is derived from the sign of `amount` (`REFUND` is negative), and `status` here excludes `OTHER` as a filter value even though it can appear in a response. `from`/`to` are full ISO 8601 datetimes, same same-day-collapse caveat as Orders. # Get a plan Source: https://docs.spenza.com/api-reference/plans-&-catalog/get-a-plan /openapi.yaml get /api/v1.1/plans/{planId} Get a plan's details. `planId` is the plan's `productId` as returned by the list endpoint (its value is the plan's display name, for example `"AT&T 5GB"` — there's no separate `productName` field here either). Optionally includes `tieredPricing` (only when `planType` is `PAY_AS_YOU_GO`) and/or `volumeTierPricing` (only when volume-tiered pricing is enabled for the plan) — same conditional fields as the list endpoint. # List plans Source: https://docs.spenza.com/api-reference/plans-&-catalog/list-plans /openapi.yaml get /api/v1.1/plans List the plans your account may purchase. `search` requires `searchType` to be set (otherwise the search matches nothing rather than erroring loudly). Omitting `category` restricts results to `MSP_PLAN` and `RESELLER_PLAN`; supplying it narrows to exactly that one category. `productId` carries the plan's display name (for example `"AT&T 5GB"`), not an internal identifier — there is no separate `productName` field on this endpoint or on `GET /api/v1.1/plans/{planId}`. Each plan optionally includes `tieredPricing` (only present when the plan's `planType` is `PAY_AS_YOU_GO`) and/or `volumeTierPricing` (only present when volume-tiered pricing is enabled for the plan). # List SIM products Source: https://docs.spenza.com/api-reference/plans-&-catalog/list-sim-products /openapi.yaml get /api/v1.1/sim-products List purchasable SIM products (ACTIVE only) — the physical/eSIM unit itself, separate from a data plan. `simId` carries the product's display name (for example `"AT&T eSIM"`), not an internal identifier — there is no separate `simName` field. Each SIM product optionally includes `volumeTierPricing` when volume-tiered pricing is enabled for it. # Purchase a plan (asynchronous) Source: https://docs.spenza.com/api-reference/plans-&-catalog/purchase-a-plan-asynchronous /openapi.yaml post /api/v3/plans/purchase Purchase / activate a plan for a SIM, asynchronously — always `202` with a `transactionId` to poll. A different request contract from `POST /api/v1.1/plans/purchase`: `activateNow` defaults from whether `scheduleDate` is set (rather than being required), `scheduleDate` is a full ISO 8601 datetime (not `YYYY-MM-DD`), and this endpoint accepts an optional free-form `metaData` object stored on the transaction. `202` only means the request was accepted for processing, not that the purchase succeeded — validation performed after acceptance (bad ICCID, plan not found, pricing not configured, etc.) is only visible by polling `statusEndpoint`. Throttled at 60 requests/60s specific to this route, tighter than the 120 req/60s account-wide default. # Purchase a plan (synchronous) Source: https://docs.spenza.com/api-reference/plans-&-catalog/purchase-a-plan-synchronous /openapi.yaml post /api/v1.1/plans/purchase Purchase / activate a plan for a SIM. Synchronous — blocks and returns the finished purchase. For an async variant, use `POST /api/v3/plans/purchase` instead (a different request/response contract, not an alias of this one). Throttled at 60 requests/60s specific to this route, tighter than the 120 req/60s account-wide default. A `429` can also occur when the purchase for this exact SIM+plan is momentarily lock-contended by a concurrent request — same `RATE_LIMITED` code and status, but with the message "Too many concurrent purchase requests for this account — please retry in a moment." rather than a generic throttle message. # Create a sim-group Source: https://docs.spenza.com/api-reference/sim-groups/create-a-sim-group /openapi.yaml post /api/v1.1/sim-groups # Delete a sim-group Source: https://docs.spenza.com/api-reference/sim-groups/delete-a-sim-group /openapi.yaml delete /api/v1.1/sim-groups/{name} # Get a sim-group Source: https://docs.spenza.com/api-reference/sim-groups/get-a-sim-group /openapi.yaml get /api/v1.1/sim-groups/{name} # List sim-groups Source: https://docs.spenza.com/api-reference/sim-groups/list-sim-groups /openapi.yaml get /api/v1.1/sim-groups # Move a SIM into this group Source: https://docs.spenza.com/api-reference/sim-groups/move-a-sim-into-this-group /openapi.yaml post /api/v1.1/sim-groups/{name}/sims # Remove a SIM from this group Source: https://docs.spenza.com/api-reference/sim-groups/remove-a-sim-from-this-group /openapi.yaml delete /api/v1.1/sim-groups/{name}/sims/{iccid} The SIM moves back to the account's default sim-group — `movedTo` is the literal string `"default"`, not that group's actual name. # Update a sim-group Source: https://docs.spenza.com/api-reference/sim-groups/update-a-sim-group /openapi.yaml put /api/v1.1/sim-groups/{name} # Assign a SIM to a user Source: https://docs.spenza.com/api-reference/sims/assign-a-sim-to-a-user /openapi.yaml post /api/v1.1/sims/{iccid}/assign Assign or reassign the SIM to a user, identified by email. Reassigning an already-assigned SIM is supported. If no user exists for that email and `name` is supplied, the user is auto-created; if the user already exists and `name` differs, the profile name is synced best-effort. # Enable or disable voice, SMS, and/or data on a SIM Source: https://docs.spenza.com/api-reference/sims/enable-or-disable-voice-sms-andor-data-on-a-sim /openapi.yaml patch /api/v1.1/sims/{iccid}/service-state Enable or disable voice, SMS, and/or data on a SIM's line without canceling its subscription. Provide at least one of `voice`, `sms`, `data` — omitting all three is a `400`; each field is independently optional, so a request can target just one. Toggling `voice`/`sms` also requires the SIM's active (or cancel-scheduled) plan to include that capability — a plan with no voice allowance can't have voice toggled here, regardless of the operator's own support for it. `data` isn't actionable by any operator yet: a request containing **only** `data` returns `501`, and a mixed request (e.g. `voice` + `data`) applies the supported fields and reports `data` back in a `warnings` array instead of silently dropping it. `serviceState.voice`/`.sms` in the response reflect the operator's **full current state** after the update, not just what this call changed — persist it directly rather than merging locally. `serviceState.data` is always `null` today, since no operator can report it. # Get a SIM by ICCID Source: https://docs.spenza.com/api-reference/sims/get-a-sim-by-iccid /openapi.yaml get /api/v1.1/sims/{iccid} Get a single SIM by ICCID, account-scoped — another account's SIM reports the same 404 as a nonexistent one. # Get a SIM's current service state Source: https://docs.spenza.com/api-reference/sims/get-a-sims-current-service-state /openapi.yaml get /api/v1.1/sims/{iccid}/service-state Get the SIM's current voice/SMS service state, as last persisted by a `PATCH` to this same endpoint. This is always a fast, cached read — it never calls the operator live and never charges the action fee `PATCH` does. `serviceState.voice`/`.sms` are `null` until the line's state has been toggled at least once via `PATCH`. `.data` is always `null` today, since no operator can report it. `updatedAt` is `null` until the first toggle, then reflects the most recent one. # Get SIM usage Source: https://docs.spenza.com/api-reference/sims/get-sim-usage /openapi.yaml get /api/v1.1/sims/{iccid}/usage Data / voice / SMS usage for the SIM's current billing cycle. `data.used` is decimal GB (1 GB = 1e9 bytes) sourced from the invoice; `history` is `[]` unless `history=true`, and is empty even then for a SIM not covered by the usage-snapshot pipeline. # List SIMs Source: https://docs.spenza.com/api-reference/sims/list-sims /openapi.yaml get /api/v1.1/sims List the SIMs on your account, paginated, with live status and assignment. # Request a new phone number Source: https://docs.spenza.com/api-reference/sims/request-a-new-phone-number /openapi.yaml post /api/v1.1/sims/{iccid}/renew-number Request a new phone number for the SIM. Rate-limited (a burst backstop — your plan's real monthly quota is enforced separately). # Delete your SIP gateway configuration Source: https://docs.spenza.com/api-reference/sip-gateway/delete-your-sip-gateway-configuration /openapi.yaml delete /api/v1/customer/register-sip Remove the configuration and turn SIP off. On the next routing sync your lines go back to Spenza's normal call handling. Returns `200` even when nothing was configured. Needs an **Admin-tier** API key, and the response is **not** on the standard envelope. # Get your SIP gateway configuration Source: https://docs.spenza.com/api-reference/sip-gateway/get-your-sip-gateway-configuration /openapi.yaml get /api/v1/customer/register-sip Your current SIP gateway configuration. When SIP is off — never registered, deleted, or registered with `isSIPEnabled: false` — this returns `{ isSIPEnabled: false, sipConfig: null }`, even if a configuration is stored. Needs an **Admin-tier** API key, and the response is **not** on the standard envelope — see **Register or update your SIP gateway** for both. # Register or update your SIP gateway Source: https://docs.spenza.com/api-reference/sip-gateway/register-or-update-your-sip-gateway /openapi.yaml post /api/v1/customer/register-sip Send inbound calls for your lines to your own SIP gateway — a PBX, contact-centre platform or SBC you run. Once registered, when someone calls one of your lines, Spenza's voice nodes send the SIP `INVITE` to `sipIngressIp:sipPort` over `transport` instead of ringing the SIM. **Each call replaces the whole configuration.** Nothing is merged: an optional field you leave out goes back to its default, so send the full configuration every time. **Which lines are routed** - Every line on your account that has a phone number, narrowed by `didRanges`. Leave `didRanges` empty to route them all. - A line bound to an AI voice agent stays with the agent. - A number that two accounts both claim is never routed. - Changes reach Spenza's voice nodes on their next routing sync, typically within seconds. **Destination rules.** `sipIngressIp` must be a public IPv4 address — hostnames aren't accepted yet. Private, loopback, link-local, carrier-grade NAT, multicast, broadcast, reserved and documentation ranges (such as `203.0.113.0/24`) are refused, as are Spenza's own ranges. `sipPort` must be 1024–65535. Spenza doesn't send SIP credentials to your gateway, so restrict it by source address instead — ask support@spenza.com for the addresses Spenza's voice nodes call from. **Contract exceptions** 1. Needs an **Admin-tier** API key. A token from a read-only or read-write key gets `401` `Access to this endpoint is forbidden`. 2. **Not on the standard envelope.** Success is a flat `{ message, sipConfig, isSIPEnabled }`, and errors use the shapes shown below rather than `{ success: false, error }`. 3. A refused destination currently comes back as **`500`** with the reason in `message`, not `400`. Treat a `500` whose `message` starts with `SIP destination` or `SIP port` as a validation error and fix the request. # Cancel a subscription Source: https://docs.spenza.com/api-reference/subscriptions/cancel-a-subscription /openapi.yaml post /api/v1.1/subscriptions/{iccid}/cancel Cancel the SIM's subscription. Always cancels at end of the current billing period (`cancelNow: false` under the hood) — an `ACTIVE` subscription typically comes back `CANCEL_SCHEDULED`, not `CANCELLED`. Synchronous. Returns **`201`** (not `200`) on success. # Get a SIM's subscription Source: https://docs.spenza.com/api-reference/subscriptions/get-a-sims-subscription /openapi.yaml get /api/v1.1/sims/{iccid}/subscription Get the subscription attached to a SIM. Falls back to the newest `SCHEDULED` subscription if there's no currently-serving one, so a subscription you can list is never a surprise 404 here. # List subscriptions Source: https://docs.spenza.com/api-reference/subscriptions/list-subscriptions /openapi.yaml get /api/v1.1/subscriptions List subscriptions across the account, paginated. `status=ACTIVE` (the default) is widened to also include `PENDING` and `CANCEL_SCHEDULED` — the still-serving set. Every other filter value is an exact match. # Get a team member Source: https://docs.spenza.com/api-reference/team-members/get-a-team-member /openapi.yaml get /api/v1.1/team-members/{email} # Invite a teammate as an admin Source: https://docs.spenza.com/api-reference/team-members/invite-a-teammate-as-an-admin /openapi.yaml post /api/v1.1/team-members # List team members Source: https://docs.spenza.com/api-reference/team-members/list-team-members /openapi.yaml get /api/v1.1/team-members Team members are account **admins** (Auth0-backed dashboard/API login), a different resource from `/api/v1.1/users` (end users who hold SIMs/plans). # Remove a team member Source: https://docs.spenza.com/api-reference/team-members/remove-a-team-member /openapi.yaml delete /api/v1.1/team-members/{email} # Update a team member Source: https://docs.spenza.com/api-reference/team-members/update-a-team-member /openapi.yaml put /api/v1.1/team-members/{email} `email` itself isn't updatable. # Create a user-group Source: https://docs.spenza.com/api-reference/user-groups/create-a-user-group /openapi.yaml post /api/v1.1/user-groups # Delete a user-group Source: https://docs.spenza.com/api-reference/user-groups/delete-a-user-group /openapi.yaml delete /api/v1.1/user-groups/{name} # Get a user-group Source: https://docs.spenza.com/api-reference/user-groups/get-a-user-group /openapi.yaml get /api/v1.1/user-groups/{name} # List user-groups Source: https://docs.spenza.com/api-reference/user-groups/list-user-groups /openapi.yaml get /api/v1.1/user-groups A "user-group" is a Department under the hood — a separate collection from SIM/device groups, with its own independent name uniqueness. # Move a user into this group Source: https://docs.spenza.com/api-reference/user-groups/move-a-user-into-this-group /openapi.yaml post /api/v1.1/user-groups/{name}/members # Remove a user from this group Source: https://docs.spenza.com/api-reference/user-groups/remove-a-user-from-this-group /openapi.yaml delete /api/v1.1/user-groups/{name}/members/{email} The user's department is cleared (`movedTo` is `null` — unlike sim-groups, there's no default user-group fallback). # Update a user-group Source: https://docs.spenza.com/api-reference/user-groups/update-a-user-group /openapi.yaml put /api/v1.1/user-groups/{name} # Create a user Source: https://docs.spenza.com/api-reference/users/create-a-user /openapi.yaml post /api/v1.1/users Create a user under your account. `department` is created automatically if it doesn't already exist. # Delete a user Source: https://docs.spenza.com/api-reference/users/delete-a-user /openapi.yaml delete /api/v1.1/users/{email} Remove a user. Fails if the user still has devices assigned, or is the account's default user. # Get a user Source: https://docs.spenza.com/api-reference/users/get-a-user /openapi.yaml get /api/v1.1/users/{email} Get a user by email. A malformed email in the path is treated as not-found, not a validation error. # List users Source: https://docs.spenza.com/api-reference/users/list-users /openapi.yaml get /api/v1.1/users List users (end users / employees) on your account, paginated. # Update a user Source: https://docs.spenza.com/api-reference/users/update-a-user /openapi.yaml put /api/v1.1/users/{email} Update a user. Any subset of the mutable fields — `email` itself is not updatable. Passing an empty `department` clears it. # Delete a voice quality webhook Source: https://docs.spenza.com/api-reference/voice-quality/delete-a-voice-quality-webhook /openapi.yaml delete /api/v1.1/voice-quality/webhooks/{id} Stop deliveries to this webhook. Needs a **read-write** key. Results already delivered are unaffected. # Get a voice quality webhook Source: https://docs.spenza.com/api-reference/voice-quality/get-a-voice-quality-webhook /openapi.yaml get /api/v1.1/voice-quality/webhooks/{id} One webhook. The signing secret is never returned here. # List voice quality webhooks Source: https://docs.spenza.com/api-reference/voice-quality/list-voice-quality-webhooks /openapi.yaml get /api/v1.1/voice-quality/webhooks Webhooks registered on your account for voice quality test results. Any key tier can read. Uses a bearer token from `POST /api/v1.1/auth/token`. # Register a voice quality webhook Source: https://docs.spenza.com/api-reference/voice-quality/register-a-voice-quality-webhook /openapi.yaml post /api/v1.1/voice-quality/webhooks Register an HTTPS endpoint to receive `voice.test.completed` when a line on your account calls a Spenza test number. Needs a **read-write** key. - The URL must be `https`, on port 443, and publicly reachable — private, loopback and link-local addresses are refused. - Up to **10** webhooks per account. Every active webhook receives every result. - The response carries `signingSecret` **once**. Store it to verify `X-Spenza-Signature` on deliveries. # Voicetestcompleted Source: https://docs.spenza.com/api-reference/voice-quality/voicetestcompleted /openapi.yaml webhook voice.test.completed Sent to every active voice quality webhook on your account when a line on your account finishes a call to a Spenza test number. **Headers:** `X-Spenza-Event`, `X-Spenza-Delivery`, `X-Spenza-Timestamp`, and `X-Spenza-Signature: t=,v1=` — HMAC-SHA256 of `.` keyed with your `signingSecret`. Reject timestamps older than 5 minutes. **Success** is any `2xx` within 10 seconds. Failed deliveries are retried after 30 seconds, 2 minutes and 10 minutes (4 attempts in total); `410 Gone` stops retries. Delivery is at least once — dedupe on `id`. # Delete a webhook registration Source: https://docs.spenza.com/api-reference/webhooks/delete-a-webhook-registration /openapi.yaml delete /api/v1.1/webhooks/{id} # Get a webhook registration Source: https://docs.spenza.com/api-reference/webhooks/get-a-webhook-registration /openapi.yaml get /api/v1.1/webhooks/{id} # List webhook deliveries Source: https://docs.spenza.com/api-reference/webhooks/list-webhook-deliveries /openapi.yaml get /api/v1.1/webhook-deliveries List recent webhook delivery attempts, newest first. Never includes the delivered payload, response body, or raw partner-endpoint error text. # List webhook registrations Source: https://docs.spenza.com/api-reference/webhooks/list-webhook-registrations /openapi.yaml get /api/v1.1/webhooks List webhook registrations, paginated in memory. # Redeliver a webhook event Source: https://docs.spenza.com/api-reference/webhooks/redeliver-a-webhook-event /openapi.yaml post /api/v1.1/webhook-deliveries/{id}/redeliver Queue a redelivery of a past event to its original endpoint, using the stored URL and body of the original attempt (not a regenerated event). Runs on a queue consumer, never in the request cycle — poll the deliveries list for the outcome. # Register or update a webhook Source: https://docs.spenza.com/api-reference/webhooks/register-or-update-a-webhook /openapi.yaml post /api/v1.1/webhooks Register a webhook for operator SMS/voice events. At most **one registration per (account, operator, network)** — `eventType` is not part of that key, so registering a second event type for the same operator+network replaces the first. Registering again for an existing combination without `update: true` is a `409`. `eventType: voice` (or `both`) registers successfully as long as the operator/network combination itself is valid — there is no registration-time check that voice is actually enabled, unlike `sms`. Voice events only fire for a line whose active plan includes voice support; a line on a plan with no voice allowance won't produce voice events even with a registered webhook. This applies to `voiceStreamUrl` too — there's no separate "voice streaming" plan capability, it's gated by the same voice allowance as `voiceUrl`/`callbackVoiceUrl`. `voiceStreamUrl` is delivered differently from every other field here: instead of an HTTP POST, Spenza opens an outbound WebSocket connection to it (accepts `ws://`, `wss://`, `http://`, or `https://`) whenever a live voice call starts on that operator/network, sends a JSON handshake frame, then streams binary PCM audio (8kHz, 16-bit, mono) in real time for the duration of the call. It's never used as a `POST .../webhooks/{id}/test` target (see that operation). **`signingSecret` is returned only from this creation path** (format `whsec_<64 hex chars>`) — no read endpoint ever returns it again. Store it immediately; losing it means re-registering. Use it to verify the `X-Spenza-Signature` header on every delivery (see the Webhooks guide). # Send a test event Source: https://docs.spenza.com/api-reference/webhooks/send-a-test-event /openapi.yaml post /api/v1.1/webhooks/{id}/test Send a signed synthetic test event to the registered endpoint. One attempt, no retries. The attempt is recorded in `GET /api/v1.1/webhook-deliveries` but deliberately does **not** count toward the 10-consecutive-failure auto-suspend threshold. Target URL priority (fixed, not event-derived): `messageUrl` → `callbackMessageUrl` → `voiceUrl` → `callbackVoiceUrl` (`voiceStreamUrl` is never a test target). This route has its own stricter rate limit — **10 requests / 60s**, on top of (not instead of) the account-wide default — since it POSTs to an arbitrary partner-supplied URL. # Update a webhook registration Source: https://docs.spenza.com/api-reference/webhooks/update-a-webhook-registration /openapi.yaml put /api/v1.1/webhooks/{id} # Authentication Source: https://docs.spenza.com/authentication Exchanging your API key and secret for a bearer token, and using it on every request. The Partner API uses **bearer token authentication**. You exchange a long-lived API key/secret pair for a short-lived access token, then send that token on every authenticated request. ## 1. Exchange credentials for a token ```http theme={null} POST /api/v1.1/auth/token Content-Type: application/json ``` ```json theme={null} { "key": "your-api-key", "secret": "your-api-secret" } ``` This endpoint itself requires no authentication — your key and secret *are* the credentials being verified. On success (`200`): ```json theme={null} { "success": true, "data": { "access_token": "eyJhbGciOiJI…", "token_type": "Bearer", "expires_in": 3600, "expires_at": "2026-07-31T12:00:00.000Z" }, "meta": { "timezone": "UTC" } } ``` > [!NOTE] > > These response fields are **snake\_case** (`access_token`, not `accessToken`) — a deliberate exception so existing OAuth2 client libraries work against it. Every other endpoint in this API is camelCase. ## 2. Send the token on every request ```http theme={null} Authorization: Bearer Content-Type: application/json ``` ```bash theme={null} curl "https://api.spenza.com/api/v1.1/sims" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` Two categories of endpoint don't need this header at all: * The **async status poll** (`GET /api/v3/transactions/{transactionId}`) — the transaction ID itself is the credential. * `POST /api/v1.1/port-in/eligibility` and `POST /api/v3/port-in` use `security: []`/role-based auth respectively rather than the standard bearer check — see the API Reference for each. Every other endpoint requires the bearer token. Any valid token for your account can call any endpoint — there's no per-key permission scoping today. `POST /api/v1.1/sms` and the SIP gateway endpoints (`/api/v1/customer/register-sip`) are exceptions: they additionally require the account's `Admin` role tier. ## Token expiry Tokens are short-lived (1 hour) — check `expires_at` on the token response and request a new one before it passes. The API doesn't document a separate refresh-token grant; re-running the key/secret exchange is how you obtain a new token. Build your client to catch a `401 UNAUTHORIZED` and transparently re-authenticate rather than hardcoding a refresh interval, since that's the behavior guaranteed by the contract. ## Credential security * **The secret never appears in a response after the initial issuance** — treat it like a password, not a lookup value. * **Server-side only.** Never put your API key/secret (or a long-lived bearer token) in a browser, mobile app, or any client an end user can inspect. Exchange for a token on your backend and proxy authenticated calls through it. * **One secret manager, not `.env` in git.** Store credentials in your platform's secrets manager (or at minimum an untracked `.env`) — see **[Security & Best Practices](/security)**. * **Rotate on suspicion.** If a key/secret may have leaked, contact Spenza support immediately to have it rotated; there is no self-service rotation endpoint in this API. ## Common authentication errors | HTTP | `error.code` | Cause | Fix | | - | - | - | - | | 400 | `VALIDATION_ERROR` | `key` or `secret` omitted from the token request body. | Send both fields. | | 401 | `UNAUTHORIZED` | Key/secret pair is wrong at the token exchange, or a bearer token is missing/malformed/expired on a later request. | Double-check the credentials, or re-authenticate for a fresh token. | | 403 | `FORBIDDEN` | Your account's plan doesn't include API access, or the token lacks the role tier an endpoint requires. | Upgrade your plan, or use an account/token with the required role. | See **[Errors](/errors)** for the complete error-code reference. ## Next steps * **[Quickstart](/quickstart)** — authenticate and make your first real call end to end. * **API Reference → Authentication** (sidebar) — the full `POST /api/v1.1/auth/token` operation spec. # Core Concepts Source: https://docs.spenza.com/core-concepts The entities, relationships and patterns that repeat across every endpoint. Every endpoint in the Partner API follows the same handful of patterns. Learning them once here means you won't have to re-learn them per-endpoint in the reference. ## Entities and terminology | Term | Meaning | | - | - | | **SIM** | A physical or eSIM identified by its **ICCID**. The unit everything else attaches to. | | **Subscription** | The data/voice/SMS plan currently active on a SIM, with a status and billing cycle. | | **Plan** (product) | A catalog item you can purchase and attach to a SIM as a subscription — identified by `productId` (its display name, e.g. `"AT&T 5GB"`). | | **SIM product** | A catalog item for the *physical or eSIM unit itself* (separate from the data plan) — what you purchase to provision a new SIM. Identified by `simId` (its display name, e.g. `"AT&T eSIM"`). | | **User** | An end user on your account that SIMs and devices are assigned to. Identified by **email** — there is no separate user ID exposed today. Don't key persistent storage off email: it's a mutable lookup value, not a stable primary key. | | **Team member** | An **admin** on your account (a different resource from User) — someone who manages the account itself, with a role tier (`Admin`, `RW Admin`, `RO Admin`, `Standard Admin`). Identified by email. | | **Device** | A phone/tablet in your device catalog, assignable to a User. Identified by its **IMEI**. | | **Order** | A record of a purchase (a plan purchase, eSIM purchase, port-in, and so on). | | **Transaction** (financial) | A charge, refund or other financial movement tied to an order — **not** the same thing as the async `transactionId` below, despite the shared name. | | **Invoice** | A billing document for a period, with line items and a usage summary. | | **Port-in** | A request to bring an existing phone number from another carrier onto a Spenza SIM. | | **Device Group / SIM Group / User Group** | A named group (with an optional spend limit and data quota) that devices, SIMs, or users can be moved into and out of. | | **Webhook registration** | Your configuration telling Spenza where and how to deliver operator SMS/voice events. | > [!NOTE] > > **Two different things are both called "transaction."** `GET /api/v1.1/transactions` is your account's *financial* transaction ledger — charges, refunds, and their status. The `transactionId` returned by an async operation (`POST /api/v1.1/esim`, `POST /api/v3/plans/purchase`, and others) is unrelated — it's a handle for polling that one operation's progress via `GET /api/v3/transactions/{transactionId}`. They happen to share a name; nothing else connects them. ## How resources relate ```text theme={null} User (email) └─ assigned ─▶ SIM (iccid) ├─ has ─▶ Subscription (plan/product) └─ has ─▶ Usage (current billing cycle) User (email) └─ assigned ─▶ Device SIM / Device / User └─ organized into ─▶ SIM Group / Device Group / User Group Order └─ produces ─▶ Transaction(s) (financial ledger entries) Invoice └─ summarizes ─▶ a billing period's Orders/Subscriptions/Usage ``` A SIM is the anchor: it's assigned to a user, has a subscription, accrues usage against that subscription's billing cycle, and its purchase/port-in/plan-change events show up as orders and financial transactions. ## The success/error envelope Every response is JSON with a `success` boolean at the top: ```json theme={null} { "success": true, "data": { "...": "..." }, "meta": { "page": 1, "pageSize": 25, "total": 240, "totalPages": 10 } } ``` * `data` is an **object** for a single-resource response, or an **array** for a list. * `meta` is present only on list responses, and carries pagination totals. ```json theme={null} { "success": false, "error": { "code": "SIM_NOT_FOUND", "message": "No SIM found.", "details": {} } } ``` On failure, `success` is `false` and `error.code` is a stable, machine-readable string from a fixed taxonomy — see **[Errors](/errors)**. > [!NOTE] > > **Documented exceptions.** `GET /api/v1.1/invoices/{id}/pdf` returns a raw `302` redirect on success, not this envelope. `POST /api/v3/port-in` and the SIP gateway endpoints (`/api/v1/customer/register-sip`) aren't on this envelope at all — see **[Environments & Versioning](/environments-versioning#documented-exceptions)**. ## Pagination List endpoints accept: | Parameter | Default | Notes | | - | - | - | | `page` | `1` | **1-indexed** — the first page is `1`, not `0`. | | `pageSize` | `25` | Max `100`. | The response's `meta` echoes `page`/`pageSize` back and adds `total` (matching records) and `totalPages`. ## Field conventions Fields are camelCase throughout (the one exception is `POST /api/v1.1/auth/token`'s response, which is deliberately snake\_case to match OAuth2 conventions), with one spelling per concept across every endpoint that returns it — `iccid`, `operator`, `phoneNumber` mean the same thing everywhere they appear. ## Idempotency Many write endpoints (SIM assignment, plan/eSIM purchase, subscription cancel, group membership changes, webhook registration and more — check each operation's page) accept an optional `Idempotency-Key` request header: * **Omit it** — the call behaves exactly as it always has; nothing changes. * **Send it, and retry with the same key + same request body** — the original response is replayed verbatim, with an `Idempotency-Replayed: true` response header. No side effect runs twice. * **Reuse the key with a different body, or against a different route** — `409 IDEMPOTENCY_KEY_REUSED`. * **Retry while the original call is still in flight** — `409 CONFLICT`. Wait for the first call to finish and reuse the same key. There's no fixed format required for the key — any string unique to that logical request (a UUID is the common choice) works. ## Async operations A handful of endpoints don't return the finished resource directly — they return `202` (or, for `POST /api/v1.1/top-up`, `201`) with a `transactionId` and a `statusEndpoint`: ```json theme={null} { "success": true, "data": { "transactionId": "64f1a2b3c4d5e6f7a8b9c0d1", "statusEndpoint": "/api/v3/transactions/64f1a2b3c4d5e6f7a8b9c0d1" } } ``` Poll `statusEndpoint` — **no authentication required**, the `transactionId` itself is the credential — until `status` leaves the in-flight states: ```text theme={null} PENDING → PROCESSING → COMPLETED | FAILED | SCHEDULED ``` `data.result` on a `COMPLETED` transaction holds the operation-specific payload (for example, the provisioned `iccid`/`qrCode` from an eSIM). A `FAILED` transaction is still a `200` from the status endpoint — check `data.status` and `data.errorCode`, not the HTTP status of the poll itself. See **[Guides → Handling async operations](/guides#handling-async-operations)** for a full polling example. Endpoints that always return this shape: `POST /api/v1.1/esim`, `POST /api/v3/plans/purchase`, `POST /api/v1.1/top-up`, `POST /api/v3/port-in`. Every other endpoint blocks and returns its finished resource directly. ## Sandbox vs. production > [!WARNING] > > **No sandbox yet.** There's a single base URL for the Partner API today — `https://api.spenza.com` (see **[Environments & Versioning](/environments-versioning)**). Every request you make against it acts on real account data. A sandbox is planned, but until it ships, confirm with your Spenza account representative before assuming any environment other than production exists for your account. ## Next steps * **[Authentication](/authentication)** — the token exchange in full detail. * **[Quickstart](/quickstart)** — put these concepts together into a working integration. * **API Reference** (sidebar) — every endpoint that implements this contract. # Environments & Versioning Source: https://docs.spenza.com/environments-versioning Base URLs, how endpoint versioning works, and the paths that don't follow the standard contract. ## Base URL | Environment | Base URL | | - | - | | Production | `https://api.spenza.com` | > [!WARNING] > > **No sandbox environment yet.** A separate sandbox/staging base URL isn't available yet. Until it ships, every request in this documentation — and every request your integration makes — hits production. See **[Guides → Testing and validation guidance](/guides#testing-and-validation-guidance)** for how to validate an integration safely without one. ## How versioning works The current, canonical surface lives under **`/api/v1.1`** — nearly every endpoint in the API Reference is on this path. There is no `Prefer`-header async negotiation and no separate `/api/v1` (non-`.1`) surface; that design was proposed at one point but was never built, so don't look for it. The one `/api/v1` path in the API Reference — SIP gateway configuration — is a standalone exception, described [below](#sip-gateway-configuration). A small number of operations instead live on **`/api/v3`** — these are the **asynchronous variant** of an operation that also has a synchronous `v1.1` counterpart with a different request/response contract: | Synchronous (`/api/v1.1`) | Asynchronous (`/api/v3`) | | - | - | | `POST /api/v1.1/plans/purchase` — blocks, returns the finished subscription | `POST /api/v3/plans/purchase` — returns `202` + `transactionId` immediately | eSIM provisioning (`POST /api/v1.1/esim`) is a partial exception: it's the current canonical path, but it's **always** asynchronous (`202` + `transactionId`) regardless of path — there's no synchronous eSIM provisioning endpoint. See **[Core Concepts → Async operations](/core-concepts#async-operations)** for the full `transactionId`/polling model. ## Documented exceptions Two resources don't follow the standard contract. ### Port-in submission `POST /api/v3/port-in` (submitting a port-in) doesn't follow the standard contract at all: * It requires an **account role** (`Admin`, `Super Admin`, or `Standard Admin`) rather than just a valid bearer token. * Its response is a **flat** `{ success, transactionId, statusEndpoint, message, timestamp }` — no `data` wrapper. * A synchronous validation error's `error` field is a **plain string**, not `{ code, message }`. This isn't a bug carried over from an old version — it's simply never been migrated onto the standard envelope. See the operation's page in the API Reference for its exact shape, and **[Numbers & Port-in](/guides#porting-in-an-existing-number)** in the Guides. ### SIP gateway configuration `GET`, `POST` and `DELETE /api/v1/customer/register-sip` sit outside the standard contract too: * They need an **Admin-tier** API key. A token from a read-only or read-write key gets `401` `Access to this endpoint is forbidden`. * Responses are **flat** — `{ message, sipConfig, isSIPEnabled }` and similar — with no `success`/`data` wrapper. * Errors are not `{ success: false, error }`. A field-validation failure is `400` `{ statusCode, message: [...], error }`, and a refused SIP destination is currently `500` `{ message }`. See **[Routing calls to your own SIP gateway](/guides#routing-calls-to-your-own-sip-gateway)** in the Guides. ## Backward compatibility The response envelope (`{ success, data, meta }` / `{ success: false, error }`), pagination shape, and field-naming conventions are consistent by design across every standard endpoint — see **[Core Concepts](/core-concepts)**. No formal backward-compatibility guarantee (for example, "fields are never removed within a version") is published for field-level payload changes — check the API Reference against your integration periodically rather than only at initial build time. ## Next steps * **[Core Concepts](/core-concepts)** for the envelope, pagination, and async pattern that stay constant across endpoints. * **API Reference** (sidebar) for the current, canonical set of endpoints. # Errors Source: https://docs.spenza.com/errors The standard error envelope, the full error-code taxonomy, and how to handle each one. ## The error envelope Every failed request returns the same shape, regardless of endpoint: ```json theme={null} { "success": false, "error": { "code": "SIM_NOT_FOUND", "message": "We couldn't find a SIM with that ICCID on your account.", "details": { "field": "iccid" } } } ``` * **`success`** is always `false` on an error. * **`error.code`** is a stable, machine-readable string — branch your error handling on this, not on `message`. * **`error.message`** is human-readable and safe to log or surface in a UI, but isn't guaranteed to be stable wording across API versions. * **`error.details`** is present on some `4xx` errors (for example a list of missing fields) and always **absent on any `5xx`** — Spenza never includes structured internal detail in a server-error response. ## Error codes Generic, HTTP-status-driven codes used across most endpoints: | HTTP | `error.code` | Meaning | | - | - | - | | 400 | `VALIDATION_ERROR` | A field failed a format/constraint check, or (on some endpoints) a business-rule check like a bad date range. | | 400 | `MISSING_FIELDS` | One or more required fields are absent — check `error.details` when present. | | 401 | `UNAUTHORIZED` | The bearer token is missing, malformed, or expired — or, at the token-exchange step, the key/secret pair was wrong. | | 403 | `FORBIDDEN` | Your account's plan doesn't include this feature, or the token lacks the role tier the endpoint requires. | | 404 | `NOT_FOUND` | Generic "doesn't exist under your account" — used where no more specific code applies (for example `GET /api/v1.1/orders/{id}`). | | 409 | `CONFLICT` | A state conflict — for example a user with that email already exists, or a device is already assigned. | | 409 | `IDEMPOTENCY_KEY_REUSED` | An `Idempotency-Key` was reused with a different request body, or against a different route. | | 429 | `RATE_LIMITED` | You've exceeded a per-endpoint or account-wide rate limit. | | 500 | `INTERNAL_ERROR` | An unexpected server-side error. | | 501 | `NOT_IMPLEMENTED` | The action isn't supported for this account's carrier/operator (for example outbound SMS on a carrier that doesn't support it). | Domain-specific `404` codes, one per resource: `SIM_NOT_FOUND`, `SUBSCRIPTION_NOT_FOUND`, `PLAN_NOT_FOUND`, `INVOICE_NOT_FOUND`, `USER_NOT_FOUND`, `DEVICE_NOT_FOUND`, `WEBHOOK_NOT_FOUND`, `DELIVERY_NOT_FOUND`, `NOTIFICATION_NOT_FOUND`, `ADMIN_NOT_FOUND`, `SIM_GROUP_NOT_FOUND`, `DEVICE_GROUP_NOT_FOUND`, `USER_GROUP_NOT_FOUND`. Group and membership codes: `SIM_GROUP_ALREADY_EXISTS` / `SIM_GROUP_NOT_EMPTY` / `SIM_NOT_IN_GROUP`, `DEVICE_GROUP_ALREADY_EXISTS` / `DEVICE_GROUP_NOT_EMPTY` / `DEVICE_NOT_IN_GROUP`, `USER_GROUP_ALREADY_EXISTS` / `USER_GROUP_NOT_EMPTY` / `USER_NOT_IN_GROUP`, `CANNOT_DELETE_DEFAULT_GROUP`. Device codes: `DEVICE_ALREADY_ASSIGNED`, `DEVICE_NOT_ASSIGNED`. Team Member (admin) codes: `INVALID_ROLE` (422), `INVALID_DEPARTMENT` (422), `ADMIN_ALREADY_EXISTS` (409), `CANNOT_DEMOTE_LAST_ADMIN` (400), `CANNOT_REMOVE_LAST_ADMIN` (400), `CANNOT_REMOVE_SELF` (400). Webhook delivery codes: `DELIVERY_FAILED` (502 — your endpoint didn't respond successfully to a test), `DELIVERY_ALREADY_IN_PROGRESS` (409). Billing/purchase code: `PRICING_NOT_CONFIGURED` — the plan has no usable price configured for your account; this is a merchant-configuration gap, not something your request caused. Contact support. > [!NOTE] > > This is the exception-driven subset actually thrown by the API today. `GET /api/v3/transactions/{transactionId}` (the async status poll) can surface any of the domain-specific `404` codes above as a `FAILED` transaction's `errorCode`, plus `VALIDATION_ERROR`, `MISSING_FIELDS`, `CONFLICT`, `RATE_LIMITED`, `NOT_IMPLEMENTED`, `PRICING_NOT_CONFIGURED`, or the default `INTERNAL_ERROR`. ## Troubleshooting by code **`400 MISSING_FIELDS` / `VALIDATION_ERROR`** Read `error.details` when present — it often names the offending field(s). Cross-check the field against the **Body**/**Query**/**Path parameters** tables on that operation's reference page for the correct type, required-ness, and enum values. These are client-side bugs; fix the request rather than retrying it unchanged. **`401 UNAUTHORIZED`** Either your key/secret pair was wrong at `POST /api/v1.1/auth/token`, or your bearer token is missing, malformed, or past its `expires_at` on a later call. See **[Authentication](/authentication)**. **`403 FORBIDDEN`** Either your account's plan doesn't include this capability, or your token doesn't have the role tier the endpoint needs. Contact Spenza support to confirm what your account/integration needs. **`404 *_NOT_FOUND`** The identifier in your path doesn't exist under your account. Confirm you're using the right identifier (users and team members are looked up by **email**, groups by **name**, not an internal ID) and that the resource wasn't already deleted/removed by a prior call. Most `404`s here are deliberately indistinguishable between "doesn't exist" and "belongs to another account" — this is an intentional account-enumeration guard, not a bug. **`409 CONFLICT`** Something you're trying to create already exists, or the resource is in a state that blocks the action (a duplicate user email, an already-assigned device, an already-cancelled subscription). Fetch the current state instead of retrying blindly. **`409 IDEMPOTENCY_KEY_REUSED`** You reused an `Idempotency-Key` with a different request body (or on a different route) from the original call that used it. Generate a new key per logical request — see **[Core Concepts → Idempotency](/core-concepts#idempotency)**. **`429 RATE_LIMITED`** Back off and retry later — see **[Rate Limits](/rate-limits)** for the recommended strategy. Don't tighten a retry loop in response to this; that makes it worse. **`500 INTERNAL_ERROR`** An unexpected failure on Spenza's side. Safe to retry with backoff for read (`GET`) requests. For write requests, prefer sending an `Idempotency-Key` up front so a retry is safe by construction — see below. ## Retry recommendations | Status | Retry? | Notes | | - | - | - | | 400, 403, 404, 409 (not `IDEMPOTENCY_KEY_REUSED`) | **No** | These indicate a problem with the request or your account state, not a transient failure. Fix and resend. | | 401 (expired token) | **Yes, after re-authenticating** | Not a blind retry — get a fresh token first. | | 429 | **Yes, with backoff** | See **[Rate Limits](/rate-limits)**. | | 500 | **Yes, with backoff — GET requests safely; POST/PUT/DELETE with an `Idempotency-Key`** | See below. | > [!TIP] > > **Use `Idempotency-Key` instead of guessing.** Many write endpoints (purchases, assignments, group membership changes, and more — see each operation's page) accept an `Idempotency-Key` header, which makes a retry after a timeout or `5xx` safe by construction: the same key + same body replays the original result rather than repeating the action. Where an endpoint doesn't support it, check current state first (for example, `GET /api/v1.1/sims/{iccid}/subscription` before retrying a plan purchase) rather than re-issuing the write unconditionally. ## Next steps * **[Rate Limits](/rate-limits)** for backoff strategy detail. * **[Core Concepts → Idempotency](/core-concepts#idempotency)** for the full retry-safety mechanism. * **[FAQ & Troubleshooting](/faq)** for setup and integration issues beyond individual error codes. * **[Support](/support)** if you're stuck on an error this page doesn't explain. # FAQ & Troubleshooting Source: https://docs.spenza.com/faq Answers to common setup, authentication, and integration questions. ## Setup ### How do I get API credentials? There's no self-serve signup — your API key and secret are issued when Spenza provisions your partner account. Contact [support@spenza.com](mailto:support@spenza.com) or your account representative. See **[Getting Started](/getting-started)**. ### Is there a sandbox I can test against? Not yet — the only base URL today is `https://api.spenza.com`, which is production. A sandbox is planned; see **[Guides → Testing and validation guidance](/guides#testing-and-validation-guidance)** for how to validate safely without one. ### Where do I find the full list of endpoints and fields? The API Reference (sidebar) — every operation, parameter, request/response schema and error code, generated directly from the OpenAPI spec. You can also download the spec itself at [`/openapi.yaml`](/openapi.yaml). ## Authentication ### My token request returns `UNAUTHORIZED` Your `key`/`secret` pair is wrong at the `POST /api/v1.1/auth/token` step. Double-check you're using the credentials issued for this account (not credentials from a different system or a copy-paste with trailing whitespace). ### My subsequent requests return `UNAUTHORIZED` Your bearer token is missing, malformed, or past its `expires_at`. Confirm you're sending `Authorization: Bearer ` (not just the raw token, and not `Bearer: `), and re-authenticate if it's expired. See **[Authentication](/authentication)**. ### A request returns `FORBIDDEN` even though my token is valid The token doesn't carry the role tier that endpoint requires, or your account's plan doesn't include that capability. This is an account permissions/plan issue, not a request bug — contact [Support](/support) to confirm what your token can and can't do. ## Invalid payloads ### I get `MISSING_FIELDS` but I think I sent everything Check `error.details` when it's present — it often lists exactly which fields were missing or invalid. A common cause is sending the field with the wrong name or nesting (for example, sending `iccid` at the top level when the operation expects it nested under a `user` object, or vice versa) — compare your body against the **Body** table on that operation's reference page field by field. ### I get `VALIDATION_ERROR` on a field that looks correct Check the field's `enum` values and type in the reference — a common mismatch is sending a string where a boolean/number is expected (`"true"` instead of `true`), or an enum value in the wrong case. ### Can I retry a failed write safely? If the endpoint supports it, send an `Idempotency-Key` header — then yes, unconditionally; a retry with the same key and body replays the original result instead of repeating it. If it doesn't, only retry if you're sure the original request didn't already partially succeed. See **[Errors → Retry recommendations](/errors#retry-recommendations)**. ## Environment mismatches ### My request works in one script but fails in another with the same code Check the base URL your HTTP client actually sent — a copy-pasted example with a placeholder host, a stale environment variable, or a leftover `http://` instead of `https://` are the usual culprits. There's only one documented environment (`https://api.spenza.com`), so "it worked from curl but not from my app" is almost always a client configuration difference, not an API difference. ### An endpoint I'm calling isn't in this documentation It likely predates the Partner API standardization and isn't part of this contract — ask [Support](/support) for the current equivalent rather than continuing to build against it. ## Debugging an integration 1. **Isolate with cURL first.** Reproduce the failing call outside your application code using the exact cURL sample from the reference page — this rules out bugs in your HTTP client/serialization. 2. **Check `error.code`, not just the HTTP status.** The status tells you the category; the code tells you the specific cause — see **[Errors](/errors)**. 3. **Diff your request against the reference example field by field.** Most failures are a missing/misnamed/mistyped field, not an API bug. 4. **For async operations, check the transaction, not just the initial response.** A `202 Accepted` only means the operation started — poll `statusEndpoint` and inspect `status`/`result`/`errorCode` for the actual outcome. See **[Guides → Handling async operations](/guides#handling-async-operations)**. 5. **Still stuck?** See **[Support](/support)** for what to include when you reach out. # Getting Started Source: https://docs.spenza.com/getting-started Prerequisites, credentials, and configuring your environment before your first call. ## Prerequisites * **A Spenza partner account.** The Partner API is provisioned per account by Spenza — self-serve signup isn't available yet. If you don't have an account yet, contact [support@spenza.com](mailto:support@spenza.com) or your Spenza account representative. * **An API key and secret** for that account (see below). * **An HTTPS client.** Any language that can make HTTPS requests and parse JSON works — the examples throughout these docs use cURL, JavaScript (`fetch`) and Python (`requests`). > [!NOTE] > > **No sandbox environment yet.** Every example in this documentation targets `https://api.spenza.com` — the only base URL available for the Partner API today. A sandbox is planned; until it ships, confirm with your Spenza account representative before writing code against production if you expect a separate test environment. See **[Environments & Versioning](/environments-versioning)**. ## Obtaining API credentials Your API **key** and **secret** are issued by Spenza when your partner account is set up. They identify your account and are the only credentials you use to obtain a bearer token — there's no separate developer-portal signup step in this API. Treat the secret like a password: * Never commit it to source control or client-side (browser/mobile) code. * Store it in a secrets manager or environment variable on your server. * If you believe it's been exposed, contact Spenza support to have it rotated. See **[Security & Best Practices](/security)** for more on credential handling. ## Environment configuration Set your credentials as environment variables rather than hardcoding them: ```bash theme={null} export SPENZA_API_KEY="your-api-key" export SPENZA_API_SECRET="your-api-secret" ``` Every code sample in these docs assumes `SPENZA_TOKEN` holds a valid bearer token obtained from the exchange described below — treat it as a short-lived value you refresh, not something you export once and forget. ## Making your first API request Every call starts by exchanging your key and secret for a bearer token: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/auth/token" \ -H "Content-Type: application/json" \ -d '{ "key": "'"$SPENZA_API_KEY"'", "secret": "'"$SPENZA_API_SECRET"'" }' ``` ## Verifying the response A successful exchange returns `200 OK` with an access token and its expiry — the response fields are deliberately **snake\_case** (OAuth2-style), unlike every other endpoint in this API: ```json theme={null} { "success": true, "data": { "access_token": "eyJhbGciOiJI…", "token_type": "Bearer", "expires_in": 3600, "expires_at": "2026-07-31T12:00:00.000Z" }, "meta": { "timezone": "UTC" } } ``` Save `data.access_token` and send it as `Authorization: Bearer ` on every subsequent request. Request a fresh token before `expires_at` passes — this endpoint doesn't currently document a separate refresh-token flow, so re-authenticating with your key/secret is the way to get a new one. If you get an error instead, `success` is `false` and `error.code` tells you what went wrong — most commonly `UNAUTHORIZED` (bad key/secret) or `VALIDATION_ERROR` (key or secret omitted from the body). See **[Authentication](/authentication)** and **[Errors](/errors)** for the full picture. ## Next steps * Walk through a complete integration in the **[Quickstart](/quickstart)**. * Understand the envelope, pagination and async patterns in **[Core Concepts](/core-concepts)**. * Browse every endpoint in the API Reference (sidebar). # Guides Source: https://docs.spenza.com/guides Deeper, task-oriented walkthroughs for the most common integration scenarios. These guides build on the **[Quickstart](/quickstart)** and assume you can already authenticate and make a basic call. Each one is a self-contained scenario you can implement independently. ## Handling async operations Some operations don't complete instantly — provisioning an eSIM involves an operator round-trip that can take **up to \~45 minutes**; a port-in depends on the losing carrier's response time. Both of those, plus the asynchronous purchase variants and top-up, return a `transactionId` immediately instead of blocking: 1. **Call the endpoint.** You get back `202` (or `201` for top-up) with `{ transactionId, statusEndpoint }`. 2. **Poll `statusEndpoint`** (`GET /api/v3/transactions/{transactionId}`). No auth header needed — the transaction ID is itself the credential. 3. **Stop polling once `status` is terminal.** `COMPLETED`, `FAILED`, or `SCHEDULED` are terminal; `PENDING` and `PROCESSING` mean keep polling. ```js theme={null} async function pollTransaction(statusEndpoint, { intervalMs = 5000, timeoutMs = 60 * 60 * 1000 } = {}) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const res = await fetch(`https://api.spenza.com${statusEndpoint}`); const { data } = await res.json(); if (data.status === "COMPLETED") return data.result; if (data.status === "FAILED") throw new Error(`Transaction failed: ${data.errorCode} — ${data.error}`); if (data.status === "SCHEDULED") return data; // scheduled for a future date, not an error await new Promise((r) => setTimeout(r, intervalMs)); } throw new Error("Timed out waiting for transaction to complete"); } ``` > [!NOTE] > > Poll every \~5 seconds for most operations; eSIM provisioning and port-in are slower-moving, so a \~30 second interval is more appropriate for those to avoid hammering the endpoint for no benefit. ## Provisioning an eSIM end-to-end One endpoint provisions the eSIM, with or without a plan attached — include `planId` to assign one in the same operation instead of purchasing it separately afterward. **This endpoint is always asynchronous**, regardless of whether a plan is included: **eSIM only** (SIM-only provisioning is currently supported for the SpenzaJ carrier family only — other carriers return `501 NOT_IMPLEMENTED` on this branch): ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/esim" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "imei": "356938035643809", "simId": "BIB009A", "email": "jane@example.com" }' ``` **eSIM + plan in one operation:** ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/esim" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "imei": "356938035643809", "simId": "BIB009A", "planId": "AT0001", "activateNow": true, "user": { "name": "Jane Doe", "email": "jane@example.com", "zipcode": "10011" } }' ``` Both return `202 Accepted` with `{ transactionId, statusEndpoint }`. Poll it with the pattern above; the completed `result` gives you the provisioned line: ```json theme={null} { "mdn": "+12792044584", "iccid": "89012345678901234567", "qrCode": "https://…/qrcode.png" } ``` Once provisioning completes, fetch the QR code / activation code again at any time — useful if the user needs to re-scan on a new device: ```bash theme={null} curl "https://api.spenza.com/api/v1.1/esim/89012345678901234567/qr" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` ## Managing the SIM lifecycle A typical SIM's lifecycle through the API: ```text theme={null} purchase/provision → assign to user → subscribe to a plan → monitor usage → (renew number | cancel plan) → unassign/deactivate ``` * **Assign** — `POST /api/v1.1/sims/{iccid}/assign`. Reassigning an already-assigned SIM is supported directly — the previous holder is replaced, not blocked. * **Subscribe** — `POST /api/v1.1/plans/purchase` (synchronous) or `POST /api/v3/plans/purchase` (asynchronous, different request contract — see the API Reference). * **Monitor** — `GET /api/v1.1/sims/{iccid}/usage` for the current cycle; pass `history=true` for prior cycles. * **Renew the phone number** — `POST /api/v1.1/sims/{iccid}/renew-number` if the assigned number needs to change. This is rate-limited (20/min) — handle `429 RATE_LIMITED` gracefully rather than retrying immediately. * **Toggle voice/SMS/data** — `PATCH /api/v1.1/sims/{iccid}/service-state` to enable or disable voice, SMS, and/or data on the line without cancelling the subscription itself. Each is independently optional (send just the ones you want to change), but toggling `voice`/`sms` still requires the active plan to include that capability, and `data` isn't controllable by any operator yet — see the API Reference for the exact `warnings` behavior on a mixed request. * **Cancel a subscription** — `POST /api/v1.1/subscriptions/{iccid}/cancel`. Synchronous; cancels at end of the current billing period by default, so an `ACTIVE` subscription typically comes back `CANCEL_SCHEDULED` rather than `CANCELLED` immediately. Note this endpoint returns `201`, not `200`, on success. ## Organizing your fleet with groups SIMs, devices, and users can each be organized into named groups (with an optional `spendLimit`, `dataQuota`, `currency`, and `dataUnit`) — separate resources under `/api/v1.1/sim-groups`, `/api/v1.1/device-groups`, and `/api/v1.1/user-groups`: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/sim-groups" \ -H "Authorization: Bearer $SPENZA_TOKEN" -H "Content-Type: application/json" \ -d '{ "name": "Sales Team", "spendLimit": 1000, "dataQuota": 100, "currency": "USD", "dataUnit": "GB" }' curl -X POST "https://api.spenza.com/api/v1.1/sim-groups/Sales%20Team/sims" \ -H "Authorization: Bearer $SPENZA_TOKEN" -H "Content-Type: application/json" \ -d '{ "iccid": "8901260853182965429" }' ``` A group's `name` is its identifier in the URL — URL-encode it if it contains spaces or special characters, and note it **can't be renamed** once created (the update endpoints don't accept a new `name`). Removing a SIM from its group moves it back to the account's default sim-group (`movedTo: "default"`); removing a device or user from its group simply clears the assignment (`movedTo: null`) — there's no default group for those two. ## Porting in an existing number Check eligibility first — it's a read-only call, no order is created: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/port-in/eligibility" \ -H "Authorization: Bearer $SPENZA_TOKEN" -H "Content-Type: application/json" \ -d '{ "portInNumber": "+15555551234", "plan": "AT0001" }' ``` > [!NOTE] > > Only the **SpenzaJ** carrier currently implements this check — every other carrier returns `501 NOT_IMPLEMENTED`, so don't treat that as a hard failure signal for carriers you know support port-in generally. Submitting the port-in itself is a documented exception to the rest of this API — there is no `POST /api/v1.1/port-ins`. The only submission endpoint is: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v3/port-in" \ -H "Content-Type: application/json" \ -d '{ "plan": "AT0001", "portInNumber": "+15555551234", "currentCarrierName": "Verizon", "currentAccountNumber": "1234567890", "currentAccountPassword": "1234", "currentBillingAddress": { "street1": "123 Main St", "city": "New York", "state": "NY", "zip": "10011" }, "employeeEmail": "jane@example.com", "employeeName": "Jane Doe" }' ``` This one requires your account's `Admin`/`Super Admin`/`Standard Admin` role rather than just a valid bearer token, and its success response is a **flat** shape — `{ success, transactionId, statusEndpoint, message, timestamp }`, no `data` wrapper — pointing at the legacy singular status path. See **[Environments & Versioning → Port-in submission](/environments-versioning#port-in-submission)** before you build against it. `currentAccountPassword` is the losing carrier's account PIN required for FCC-compliant number portability (LNP) — handle it with the same care as any other credential; never log it. Track status separately with: ```bash theme={null} curl "https://api.spenza.com/api/v1.1/port-ins?status=IN_PROGRESS" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` ## Reconciling billing Pull invoices on a schedule (for example, monthly) to reconcile against your own finance system. `from`/`to` here are **date-only** (`YYYY-MM-DD`) — unlike Orders/Transactions, which take full datetimes: ```bash theme={null} curl "https://api.spenza.com/api/v1.1/invoices?from=2026-06-01&to=2026-06-30" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` Each invoice includes `lineItems` and a `usageSummary`. To get the underlying PDF, follow the redirect from `GET /api/v1.1/invoices/{id}/pdf` — it 302s to a signed download URL (an S3-hosted PDF, or a Stripe receipt URL as a fallback when no stored PDF exists yet). Check prepaid credit and top it up the same way: ```bash theme={null} curl "https://api.spenza.com/api/v1.1/credit-balance" -H "Authorization: Bearer $SPENZA_TOKEN" curl -X POST "https://api.spenza.com/api/v1.1/top-up" \ -H "Authorization: Bearer $SPENZA_TOKEN" -H "Content-Type: application/json" \ -d '{ "amount": 100, "currency": "usd" }' ``` `top-up` returns a `checkoutUrl` (hosted checkout) alongside a `transactionId`/`statusEndpoint` — redirect the user there to complete payment; poll the transaction to confirm it landed. ## Integrating webhooks Register a webhook, then verify every delivery's signature before trusting it — see **[Webhooks](/webhooks)** for the full registration flow, the delivery-signing scheme, and how to inspect/redeliver past events. ## Testing call quality Find out how good a real phone call from one of your lines is. Register a webhook, call a Spenza test number from a line on your account, and when the call ends Spenza sends a scored report — packet loss, jitter, round-trip time and a MOS score for each direction of the audio — to your webhook. > [!NOTE] > > Spenza only **receives** test calls; it never calls your lines. A report is delivered only when the calling number is a line on **your** account — a call from any other number is measured but never sent to you. **1. Register a webhook.** Needs a read-write API key. The URL must be `https` on port 443 and publicly reachable; you can register up to 10. ```bash theme={null} curl -s -X POST "https://api.spenza.com/api/v1.1/voice-quality/webhooks" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 3f29b6a1-4b8e-4f0a-9c2e-8e6b1d2a7c44" \ -d '{ "url": "https://partner.example.com/hooks/voice-quality", "events": ["voice.test.completed"] }' ``` The response carries `signingSecret` **once** — store it to verify deliveries. **2. Call the test number.** Call **+1 279 204 4328** from a line on your account and stay on the line for about 20 seconds; a call too short to measure comes back `INCONCLUSIVE`. **3. Receive `voice.test.completed`.** Shortly after you hang up: ```json theme={null} { "id": "evt_3f2a9c1e5b7d4e8a9c217d4e5f6a8b90", "type": "voice.test.completed", "api_version": "2026-10-01", "created_at": "2026-10-07T12:24:40.000Z", "data": { "test_id": "vqt_3f2a9c1e5b7d4e8a9c217d4e5f6a8b90", "source_number": "+12792043120", "test_destination": "+12792044328", "verdict": "PASS", "headline": "PASS — Good voice quality", "quality_class": "Excellent", "mos_cqe": 4.4, "score": 93, "confidence": "high", "report": { "quality": [ { "path": "node_to_caller", "packetLossPercent": 0, "jitterMsMax": 0, "jitterMsMean": 0, "rttMsMean": 44.22, "reportCount": 4, "rating": { "rFactor": 92.67, "mosCqe": 4.4, "category": "best", "delayMs": 22.1 } } ] } } } ``` Deliveries are signed exactly like operator webhooks — verify `X-Spenza-Signature` as described in **[Verifying delivery signatures](/webhooks#verifying-delivery-signatures)**, using this webhook's `signingSecret`. Success is any `2xx` within 10 seconds; a failed delivery is retried after 30 seconds, 2 minutes and 10 minutes (4 attempts), and `410 Gone` stops retries. Dedupe on `id`. **Reading the report.** `node` is Spenza's voice server and `caller` is the phone that dialled, so `node_to_caller` is the audio Spenza sent towards your line and `caller_to_node` is the audio your line sent to Spenza. | Field | What it means | Good | | - | - | - | | `verdict` | `PASS`, `WARNING`, `FAIL`, or `INCONCLUSIVE` when there wasn't enough media to judge. | `PASS` | | `packetLossPercent` | Share of audio packets that never arrived — each one is a tiny gap in the sound. | 0%; 1–3% sounds choppy; above 5% is bad | | `jitterMsMax` / `jitterMsMean` | How unevenly packets arrived (worst / average), in ms. | Under 30 ms | | `rttMsMean` | Round-trip time to the far end and back, in ms. | Under 150 ms; above \~300 ms people talk over each other | | `reportCount` | Quality reports received during the call, about one every 5 seconds. | 3 or more | | `rating.rFactor` | ITU-T G.107 transmission rating, 0–100. | 90+ best, 80–90 high, 70–80 medium | | `rating.mosCqe` | The same rating on the 1–5 call-quality scale; **4.4 is the maximum** for standard phone audio. | Above 4.0 | | `confidence` | `high` when enough of the call was measured, `low` when it was too short. | `high` | The score is calculated from how the audio packets travelled, not from listening to the call, so a faulty microphone or speaker isn't detected. It measures as far as the carrier equipment on your line's side. A jitter of exactly `0` usually means your carrier recalculates these reports rather than passing raw figures through — that's normal. Place test calls one after another rather than all at once. ## Routing calls to your own SIP gateway If you run your own phone system — a PBX, a contact-centre platform or an SBC — Spenza can hand inbound calls for your lines to it over SIP instead of ringing the SIM. Register your gateway once, and every call to a matching line arrives at your gateway as a SIP `INVITE`. > [!NOTE] > > These endpoints sit outside the standard contract: they need an **Admin-tier** API key, and requests and responses are flat JSON without the `success`/`data` envelope. See **[Environments & Versioning → SIP gateway configuration](/environments-versioning#sip-gateway-configuration)**. **1. Register your gateway.** Only `sipIngressIp` is required. It must be your gateway's public IPv4 address. Hostnames aren't accepted, and private, loopback, carrier-grade NAT and documentation ranges are refused. ```bash theme={null} curl -s -X POST "https://api.spenza.com/api/v1/customer/register-sip" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "sipIngressIp": "44.205.10.20", "sipPort": 5060, "transport": "udp", "didRanges": ["+14155550123", "+1628555*"] }' ``` ```json theme={null} { "message": "SIP configuration registered successfully", "sipConfig": { "sipIngressIp": "44.205.10.20", "sipPort": 5060, "transport": "udp", "codecs": ["ulaw", "alaw"], "didRanges": ["+14155550123", "+1628555*"], "allowedSourceIps": [] }, "isSIPEnabled": true } ``` **2. Choose which lines to route.** `didRanges` takes exact E.164 numbers (`+14155550123`) and prefixes ending in `*` (`+1628555*` matches every number starting `+1628555`). Leave it empty to route every line on your account that has a number. Entries in any other form, such as `+1415000xxxx`, match nothing. Two kinds of line are never sent to your gateway: a line bound to an AI voice agent stays with the agent, and a number that two accounts both claim isn't routed at all. **3. Open your firewall to Spenza.** Spenza doesn't send SIP credentials, so restrict your gateway by source address instead. Ask [support@spenza.com](mailto:support@spenza.com) for the addresses Spenza's voice nodes call from. The change reaches Spenza's voice nodes on their next routing sync, typically within seconds. Check what's saved with `GET /api/v1/customer/register-sip`, and turn routing off with `DELETE` on the same path. **Things to know before you build against it:** * **Every `POST` replaces the whole configuration.** Fields you leave out reset to their defaults (`5060`, `udp`, `["ulaw","alaw"]`, `[]`), so send the full configuration on every update, not just the field that changed. * `"isSIPEnabled": false` saves the configuration without routing calls. While SIP is off, `GET` returns `sipConfig: null` even though the configuration is stored. * `codecs` and `allowedSourceIps` are saved and returned but **not applied yet**. Calls are offered with the voice node's standard codec set, and inbound source filtering is up to your firewall. * A refused destination currently returns **`500`**, not `400`, with the reason in `message` (for example `SIP destination cannot be a private address`). Show that message to whoever entered the address rather than retrying. ## Testing and validation guidance There's no separate sandbox documented for this API (see **[Environments & Versioning](/environments-versioning)**), so validate your integration carefully against production: * Start with **read-only** calls (`GET /api/v1.1/sims`, `GET /api/v1.1/plans`) to confirm authentication and pagination before writing any code that mutates state. * Use a small number of real-but-low-value test resources (a single spare SIM, a test user) rather than scripting bulk writes against production inventory. * Use an `Idempotency-Key` on write calls that support it — see **[Core Concepts → Idempotency](/core-concepts#idempotency)** — so a client-side retry after a timeout can't duplicate the action. * Validate request bodies client-side against the field tables in the API Reference — a `400 VALIDATION_ERROR`/`MISSING_FIELDS` on a write call is cheaper to catch locally than after Spenza has already tried to place an order. * For destructive or billable actions (plan purchases, top-ups, port-ins), gate them behind an explicit confirmation step in your own tooling until you're confident in the integration. ## Production-readiness checklist * [ ] Credentials are stored in a secrets manager, not in code or `.env` files committed to git. * [ ] Your client re-authenticates automatically on `401 UNAUTHORIZED` rather than crashing. * [ ] Every write call has retry logic for `429`/`5xx` with backoff (see **[Rate Limits](/rate-limits)**), and does **not** blindly retry `4xx` validation errors. * [ ] Write calls that support it send an `Idempotency-Key`, so a retry after a timeout can't duplicate a purchase. * [ ] Async operations are polled with a bounded timeout, not an infinite loop. * [ ] Webhook endpoints (if used) verify `X-Spenza-Signature` and are idempotent against redelivery — see **[Webhooks](/webhooks)**. * [ ] You have a support contact path for issues — see **[Support](/support)**. # Introduction Source: https://docs.spenza.com/introduction What the Spenza Partner API is, who it's for, and what you can build with it. Spenza operates the connectivity behind mobile lines — SIMs, eSIMs, data/voice/SMS plans, phone numbers, billing and the users those lines are assigned to. The **Spenza Partner API** gives you programmatic access to that same connectivity layer so you can manage it from your own systems instead of a manual admin console. Every partner account gets one API key/secret pair and one consistent contract across the whole surface: * A predictable `{ success, data, meta }` response envelope on every call. * One `page` / `pageSize` pagination scheme on every list endpoint. * One error-code taxonomy (`SIM_NOT_FOUND`, `RATE_LIMITED`, and so on) instead of ad hoc messages per endpoint. * An optional `Idempotency-Key` header on write endpoints, so a retried call replays instead of repeating. * One async pattern for anything that takes real-world time (provisioning an eSIM, a checkout session): the call returns a `transactionId` immediately that you poll a single status endpoint with until it resolves. > **Base URL** > > `https://api.spenza.com` ## What you can build > **Fleet management** > > List and inspect the SIMs on your account, see live usage against the current billing cycle, and assign or reassign SIMs to users. > **Self-serve provisioning** > > Purchase and activate plans, provision eSIMs (with an activation QR code), and check eligibility / port existing numbers in from another carrier. > **Billing integrations** > > Pull invoices and usage summaries into your own finance tooling, check prepaid credit balance, and create top-up checkout sessions. > **[Team & fleet organization](/api-reference)** > > Organize SIMs, devices, and users into named groups with spend limits and data quotas; manage the device catalog and who it's assigned to. > **[Account administration](/api-reference)** > > Invite and manage Team Members (account admins) with role tiers, and configure account-wide notification preferences. > **[Voice / SMS & webhooks](/api-reference)** > > Send outbound SMS from a provisioned number, and register webhooks (with payload signing) for inbound SMS/voice events. > **[Quickstart](/quickstart)** > > A complete, copy-ready integration flow from token to first purchase. ## How the API is organized | Resource | What it covers | | - | - | | **SIMs** | Inventory, live status, usage, assignment, number renewal | | **Subscriptions** | The plan currently attached to a SIM — list, cancel | | **Plans & Catalog** | Browse purchasable plans and SIM products; purchase a plan (sync or async) | | **eSIM** | Provision an eSIM (with an optional plan) and fetch its activation QR code | | **Billing** | Invoices, PDF download, prepaid credit balance and top-up | | **Users** | The end users on your account that SIMs/devices are assigned to | | **Orders & Transactions** | Order history and the underlying financial transactions | | **Numbers & Port-in** | Check port-in eligibility and bring an existing phone number in from another carrier | | **Messaging** | Send outbound SMS from a provisioned number | | **Webhooks** | Register endpoints to receive operator SMS/voice events, inspect and redeliver past deliveries | | **Notifications** | In-account notifications and delivery preferences | | **Device / SIM / User Groups** | Organize your fleet into named groups with spend/data limits | | **Devices** | The device catalog (phones/tablets) and their assignment to users | | **Team Members** | Admins who manage your account itself, with role tiers | | **Async Status** | The universal poll for any operation that returns a `transactionId` | ## Where to go next * New to the API? Start with **[Getting Started](/getting-started)** to get credentials and configure your environment. * Want the mental model first? Read **[Core Concepts](/core-concepts)** for the envelope, pagination, and async pattern used everywhere. * Ready to write code? Jump to the **[Quickstart](/quickstart)** for a complete, copy-ready integration flow. * Looking for a specific endpoint? Browse the **API Reference** in the sidebar. # Postman Collection Source: https://docs.spenza.com/postman-collection Import a ready-to-use Postman collection for the Partner API — every endpoint, pre-wired authentication, and idempotent-by-default write requests. Skip writing requests by hand: import the full Partner API into Postman in one step. It's generated directly from the same OpenAPI spec that powers the **API Reference**, so it's always in sync with what's documented here. ## Import it **1. Import the collection** In Postman, **Import → Link**, and paste: ``` https://gist.githubusercontent.com/midhunspenza/81b9a55ba05001d8dd76bd9355986bc3/raw/spenza-partner-api.postman_collection.json ``` Or open that URL directly and use your browser's save/download option, then **Import → File** in Postman instead. **2. Import the environment (optional)** Same method, using: ``` https://gist.githubusercontent.com/midhunspenza/81b9a55ba05001d8dd76bd9355986bc3/raw/spenza-partner-api.postman_environment.json ``` Pre-configures `baseUrl` and empty `apiKey`/`apiSecret`/`accessToken` slots — or just use the collection's own **Variables** tab if you'd rather not add an environment. **3. Set your credentials** Fill in `apiKey`/`apiSecret` with your partner credentials, wherever you put the variables in step 2. **4. Authenticate once** Run **Authentication → Exchange credentials for a token**. Its test script saves the returned token into the `accessToken` variable automatically — every other request inherits it via collection-level bearer auth. **5. Start calling endpoints** Every operation in the **API Reference** is here too, organized into the same folders (SIMs, Plans & Catalog, eSIM, Billing, Webhooks, and so on), with realistic example request bodies already filled in. ## What's pre-wired * **Auth handled for you.** Collection-level bearer auth reads from the `accessToken` variable, so you only authenticate once per session (tokens last 1 hour — re-run the auth request to refresh). * **Idempotency by default.** Every write request that accepts an `Idempotency-Key` header has it pre-filled with Postman's dynamic `{{$guid}}` variable, so each send automatically uses a fresh key — retries are safe out of the box. * **Correct no-auth exceptions.** `POST /api/v1.1/auth/token` and `GET /api/v3/transactions/{transactionId}` are explicitly set to no-auth, matching their real behavior — no confusing 401s from a missing token where none is needed. * **Port-in submission's role requirement.** `POST /api/v3/port-in` needs a token whose account role is `Admin`, `Super Admin`, or `Standard Admin` — a lower-privilege token gets a well-formed `403 FORBIDDEN`, not a broken request. ## Next steps * **[Quickstart](/quickstart)** if you'd rather follow the same flow in `curl`/Node.js first. * **[Authentication](/authentication)** for the full token-exchange contract this collection automates. * **API Reference** (sidebar) for the field-level schema behind every request in the collection. # Quickstart Source: https://docs.spenza.com/quickstart Authenticate, browse the catalog, provision an eSIM with a plan, then confirm usage — end to end. This walks through the fastest path to a working, billable line: authenticate, see what's purchasable, provision a new eSIM with a plan in one call, then confirm usage once it's live. Every request/response shown here is copy-ready — swap in your own credentials and IDs. ## 1. Authenticate ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/auth/token" \ -H "Content-Type: application/json" \ -d '{ "key": "'"$SPENZA_API_KEY"'", "secret": "'"$SPENZA_API_SECRET"'" }' ``` ```json theme={null} { "success": true, "data": { "access_token": "eyJhbGciOiJI…", "token_type": "Bearer", "expires_in": 3600, "expires_at": "2026-07-31T12:00:00.000Z" }, "meta": { "timezone": "UTC" } } ``` ```bash theme={null} export SPENZA_TOKEN="eyJhbGciOiJI…" ``` ## 2. Browse the catalog Two separate catalogs feed a provision call: SIM products (the physical/eSIM unit itself) and plans (the data/voice/SMS product you attach to it). ```bash theme={null} curl "https://api.spenza.com/api/v1.1/sim-products?pageSize=10" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` ```json theme={null} { "success": true, "data": [ { "simId": "AT&T eSIM", "description": "eSIM, bulk pricing available", "price": 5, "currency": "usd", "operator": "AT&T", "network": "AT&T", "isEsim": true, "inStock": 500, "minOrderQuantity": 1, "maxOrderQuantity": 10 } ], "meta": { "page": 1, "pageSize": 10, "total": 1, "totalPages": 1 } } ``` ```bash theme={null} curl "https://api.spenza.com/api/v1.1/plans?pageSize=10" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` ```json theme={null} { "success": true, "data": [ { "productId": "AT&T 5GB", "description": "Unlimited talk & text + 5GB data", "price": 49.99, "currency": "usd", "validityDays": 30, "data": { "value": 5, "unit": "GB" }, "voiceMinutes": 1000, "smsCount": 500, "operator": "AT&T", "network": "AT&T", "isEsim": false, "planType": "FLAT_RATE", "recurring": true } ], "meta": { "page": 1, "pageSize": 10, "total": 1, "totalPages": 1 } } ``` Take note of `simId` (`"AT&T eSIM"`) and `productId` (`"AT&T 5GB"`) — you'll pass them as `simId`/`planId` in the next step. ## 3. Provision an eSIM with a plan One call both provisions the eSIM and activates the plan on it. This endpoint is **always asynchronous** — it returns `202` immediately with a `transactionId`, not the finished SIM: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/esim" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "imei": "356938035643809", "simId": "AT&T eSIM", "planId": "AT&T 5GB", "email": "jane@example.com" }' ``` ```json theme={null} { "success": true, "data": { "transactionId": "64f1a2b3c4d5e6f7a8b9c0d1", "statusEndpoint": "/api/v3/transactions/64f1a2b3c4d5e6f7a8b9c0d1" } } ``` Poll `statusEndpoint` — no auth header needed, the `transactionId` itself is the credential — until `status` leaves `PENDING`/`PROCESSING`: ```bash theme={null} curl "https://api.spenza.com/api/v3/transactions/64f1a2b3c4d5e6f7a8b9c0d1" ``` ```json theme={null} { "success": true, "data": { "transactionId": "64f1a2b3c4d5e6f7a8b9c0d1", "status": "COMPLETED", "message": "Transaction completed successfully", "timestamp": "2026-07-31T10:32:00.500Z", "result": { "mdn": "+12792044584", "iccid": "8901260853182965429", "qrCode": "https://…/qrcode.png" }, "createdAt": "2026-07-31T10:30:00.000Z", "updatedAt": "2026-07-31T10:32:00.000Z" } } ``` Take note of `result.iccid` — that's the identifier for every SIM-scoped call from here on, including the usage check below. > [!NOTE] > > See **[Core Concepts → Async operations](/core-concepts#async-operations)** for the full polling contract, including what a `FAILED` transaction looks like. ## 4. Confirm usage ```bash theme={null} curl "https://api.spenza.com/api/v1.1/sims/8901260853182965429/usage" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` ```json theme={null} { "success": true, "data": { "iccid": "8901260853182965429", "cycle": { "start": "2026-07-31T00:00:00.000Z", "end": "2026-08-31T00:00:00.000Z" }, "data": { "used": 0, "allowance": 5, "unit": "GB" }, "voice": { "usedMinutes": 0, "allowanceMinutes": 1000 }, "sms": { "used": 0, "allowance": 500 }, "history": [] } } ``` ## The same flow in Node.js ```js theme={null} const BASE = "https://api.spenza.com"; async function pollTransaction(statusEndpoint, { intervalMs = 5000, timeoutMs = 60 * 60 * 1000 } = {}) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const res = await fetch(`${BASE}${statusEndpoint}`); const { data } = await res.json(); if (data.status === "COMPLETED") return data.result; if (data.status === "FAILED") throw new Error(`${data.errorCode}: ${data.error}`); await new Promise((r) => setTimeout(r, intervalMs)); } throw new Error("Timed out waiting for provisioning to finish."); } async function main() { const authRes = await fetch(`${BASE}/api/v1.1/auth/token`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: process.env.SPENZA_API_KEY, secret: process.env.SPENZA_API_SECRET, }), }); const authBody = await authRes.json(); if (!authBody.success) throw new Error(authBody.error.message); const headers = { Authorization: `Bearer ${authBody.data.access_token}`, "Content-Type": "application/json", }; const provisionRes = await fetch(`${BASE}/api/v1.1/esim`, { method: "POST", headers, body: JSON.stringify({ imei: "356938035643809", simId: "BIB010A", planId: "AT0001", email: "jane@example.com", }), }); const provisionBody = await provisionRes.json(); if (!provisionBody.success) throw new Error(provisionBody.error.message); const { iccid } = await pollTransaction(provisionBody.data.statusEndpoint); const usageRes = await fetch(`${BASE}/api/v1.1/sims/${iccid}/usage`, { headers }); const usage = await usageRes.json(); console.log(usage.data); } main().catch(console.error); ``` ## What you just did 1. Exchanged credentials for a bearer token. 2. Browsed the SIM-product and plan catalogs your account can purchase. 3. Provisioned a new eSIM with a plan attached in one call, then polled the returned `transactionId` to completion. 4. Checked usage against the new SIM's billing cycle. ## Next steps * **[Guides](/guides)** for deeper walkthroughs — SIM-only provisioning, port-in, billing, and webhook integration. * **API Reference** (sidebar) for every field, enum and error on every endpoint. * **[Errors](/errors)** for how to handle failures in each of these steps. # Rate Limits Source: https://docs.spenza.com/rate-limits The published per-endpoint and account-wide limits, and how to back off when you hit one. ## Limit behavior Every request is subject to an **account-wide default of 120 requests per 60-second window**. A handful of endpoints carry a **tighter, endpoint-specific** limit on top of that default, because they're either expensive, carrier-facing, or an abuse surface: | Endpoint | Limit | | - | - | | `POST /api/v1.1/sims/{iccid}/renew-number` | 20 / 60s | | `POST /api/v1.1/subscriptions/{iccid}/cancel` | 30 / 60s | | `POST /api/v1.1/plans/purchase` | 60 / 60s | | `POST /api/v3/plans/purchase` | 60 / 60s | | `POST /api/v1.1/esim` | 60 / 60s | | `POST /api/v1.1/sms` | 30 / 60s | | `POST /api/v1.1/top-up` | 20 / 60s | | `POST /api/v1.1/port-in/eligibility` | 20 / 60s | | `POST /api/v1.1/team-members` | 20 / 60s | | `POST /api/v1.1/webhooks/{id}/test` | 10 / 60s | Every other endpoint is subject only to the 120/60s account-wide default. When you exceed a limit, the request fails with: ```json theme={null} { "success": false, "error": { "code": "RATE_LIMITED", "message": "ThrottlerException: Too Many Requests" } } ``` ```http theme={null} HTTP/1.1 429 Too Many Requests ``` > [!NOTE] > > These are the limits **coded today** — they can change, and a limit tied to your specific account plan may differ. Read the rate-limit headers at runtime rather than hardcoding these numbers into alerting thresholds. ## Relevant headers **A `429` response itself only carries one header: `Retry-After`** (seconds until you can retry). The `X-RateLimit-*` headers below are only sent on requests that succeeded (i.e. weren't throttled) — read them to see how close you are to the limit *before* you hit it, not as part of handling the 429 itself: | Header | Meaning | Present on | | - | - | - | | `Retry-After` | Seconds until you can retry. | The `429` response only. | | `X-RateLimit-Limit` | Requests allowed in the current window. | Successful (non-429) responses only. | | `X-RateLimit-Remaining` | Requests remaining in the current window. | Successful (non-429) responses only. | | `X-RateLimit-Reset` | Seconds until the window resets. | Successful (non-429) responses only. | ## Handling throttling * Treat `429 RATE_LIMITED` as a **signal to slow down**, not a bug to route around by hammering the endpoint faster. * Apply backoff **per endpoint** — a limit on `renew-number` doesn't mean your other calls are also throttled, so don't globally pause your whole integration in response to one endpoint's `429`. * Never retry a `429` immediately in a tight loop; it will not succeed sooner and behaves poorly for every other caller sharing your account's limit. ## Recommended backoff strategy `Retry-After` (on the `429` itself) tells you when to retry — prefer waiting at least that long. As a general-purpose fallback (or when you want to smooth out repeated throttling rather than waiting for one window), use **exponential backoff with jitter**: ```js theme={null} async function withRetry(fn, { maxAttempts = 5, baseDelayMs = 1000 } = {}) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await fn(); } catch (err) { const retryable = err.status === 429 || err.status >= 500; if (!retryable || attempt === maxAttempts) throw err; const delay = baseDelayMs * 2 ** (attempt - 1) * (0.5 + Math.random()); await new Promise((r) => setTimeout(r, delay)); } } } ``` Bound `maxAttempts` — an unbounded retry loop against a sustained `429` just extends an outage into your own system. ## Next steps * **[Errors](/errors)** for the full status-code and retry matrix. * **[Security & Best Practices](/security)** for how rate-limit handling fits into a production-ready client. # SDKs & Code Examples Source: https://docs.spenza.com/sdks No official client libraries are published yet — here's how to integrate directly and how to generate your own typed client. > [!NOTE] > > **Official SDKs aren't available yet.** Official client libraries for the Partner API aren't published yet. Every operation in the API Reference includes ready-to-use cURL, JavaScript, and Python samples generated directly from the API's OpenAPI spec in the meantime — for most integrations, that's a complete starting point without needing a dedicated package. ## Calling the API directly The three languages shown throughout this documentation cover the common cases: **cURL** — for exploring an endpoint or debugging from a terminal. ```bash theme={null} curl "https://api.spenza.com/api/v1.1/sims" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` **JavaScript (`fetch`)** — no dependency needed in Node.js 18+ or any modern browser/edge runtime. ```js theme={null} const res = await fetch("https://api.spenza.com/api/v1.1/sims", { headers: { Authorization: `Bearer ${token}` }, }); const { data, meta } = await res.json(); ``` **Python (`requests`)** ```python theme={null} import requests res = requests.get( "https://api.spenza.com/api/v1.1/sims", headers={"Authorization": f"Bearer {token}"}, ) data = res.json()["data"] ``` Every operation's page in the reference has these three pre-filled with that operation's actual path, parameters and body — copy them directly rather than retyping from this page. ## Generating a typed client from the OpenAPI spec The full API surface is published as an OpenAPI 3.1 document at **[`/openapi.yaml`](/openapi.yaml)**. You can point standard, widely-used open-source generators at it to get a typed client in your language without waiting on an official SDK: ```bash theme={null} # TypeScript types only (lightweight, no runtime dependency) npx openapi-typescript ./openapi.yaml -o spenza-api.d.ts # Full client generation (many languages: TypeScript, Python, Go, Java, ...) npx @openapitools/openapi-generator-cli generate \ -i ./openapi.yaml \ -g typescript-fetch \ -o ./generated/spenza-client ``` These are general-purpose, third-party tools — not something Spenza maintains or supports directly — but because the spec is the same source of truth this documentation is generated from, a client built from it stays in sync with what's actually documented here. ## Next steps * **[Quickstart](/quickstart)** for a complete flow using the raw-HTTP approach. * **API Reference** (sidebar) for every endpoint's pre-built code samples. # Security & Best Practices Source: https://docs.spenza.com/security Protecting credentials, handling sensitive data, and building a resilient client. ## Protecting your API key and secret * **Server-side only.** Your API key/secret and any bearer token derived from them must never reach a browser, mobile app, or other client an end user can inspect. Exchange for a token on a server you control and proxy authenticated calls through it. * **Secrets manager, not source control.** Store the key/secret in your platform's secrets manager (AWS Secrets Manager, GCP Secret Manager, Vault, or equivalent) or, at minimum, an untracked `.env` file. Never commit them. * **Transport security.** Only ever call `https://api.spenza.com` over TLS — never construct a plain-HTTP variant of the base URL. ## Secret rotation There is no self-service key/secret rotation endpoint in this API. If a credential may have been exposed (checked into a public repo, logged accidentally, shared over an insecure channel), contact [Support](/support) immediately to have it rotated — don't wait to confirm the exposure was exploited. ## Webhook credentials Webhook registrations carry two separate secrets — don't conflate them: * **`authentication`** (the credential you configure) protects **your** endpoint from unauthorized callers — Spenza presents it when calling you. * **`signingSecret`** (returned once, at registration) is what you use to verify a delivery actually came from Spenza, via the `X-Spenza-Signature` header. See **[Webhooks → Verifying delivery signatures](/webhooks#verifying-delivery-signatures)**. Store both like any other credential — a secrets manager, never source control — and treat a lost `signingSecret` as a reason to re-register (there's no way to retrieve it again). ## Logging and sensitive-data handling Several fields that pass through this API are sensitive and should be excluded from application logs, error-tracking tools, and analytics: * **Credentials** — your API secret, any bearer token, a webhook's `authentication` credential and `signingSecret`. * **Port-in carrier credentials** — `currentAccountPassword` (the losing carrier's account PIN) is functionally a password; never log the request body of a port-in call unredacted. * **Personal data** — names, emails, phone numbers and billing addresses flow through the Users, SIMs, Devices, and Port-in surfaces. Handle this like any other customer PII in your systems: minimize retention, restrict access, and exclude it from third-party logging/analytics tools that don't need it. If you build request/response logging for debugging, redact these fields (or the whole body on auth/port-in endpoints) before writing them anywhere persistent. ## Idempotency Many write endpoints accept an `Idempotency-Key` request header — use it on anything that spends money or has a side effect you can't cheaply reverse (purchases, assignments, group membership changes). It's the difference between "safe to retry blindly" and "must check state first." See **[Core Concepts → Idempotency](/core-concepts#idempotency)** and **[Errors → Retry recommendations](/errors#retry-recommendations)** for the full mechanics. Not every endpoint supports it — check each operation's page in the API Reference. ## Handling rate limits `429 RATE_LIMITED` means back off, not retry immediately — see **[Rate Limits](/rate-limits)** for the full strategy (exponential backoff with jitter, applied per endpoint) and the published per-endpoint thresholds. ## Request retries Retry `429` and `5xx` responses with backoff; don't retry `4xx` responses unchanged — they mean the request itself needs to change. Prefer sending an `Idempotency-Key` on write calls over guessing whether a retry is safe. The full matrix is in **[Errors → Retry recommendations](/errors#retry-recommendations)**. ## Timeout recommendations * **Synchronous endpoints** (most `GET`/`POST`/`PUT`/`DELETE` calls) typically resolve quickly; a client timeout in the 10–30 second range is a reasonable general default. This isn't a number Spenza publishes — size it to your own latency tolerance and adjust if you observe slower calls in practice. * **Async calls** (`POST /api/v1.1/esim`, the `/api/v3` purchase variants, top-up, port-in) return immediately with a `transactionId` — don't hold a long-lived connection waiting for the transaction to finish. eSIM provisioning specifically can take **up to \~45 minutes** end to end; poll `GET /api/v3/transactions/{transactionId}` on the interval described in **[Guides → Handling async operations](/guides#handling-async-operations)** instead of waiting on the original request. ## Next steps * **[Errors](/errors)** for the full error taxonomy and retry matrix. * **[Rate Limits](/rate-limits)** for throttling behavior. * **[Webhooks](/webhooks)** for securing inbound webhook delivery specifically. # API Status & Maintenance Source: https://docs.spenza.com/status Check whether the Spenza API is up, see planned maintenance before it happens, and get notified about incidents. **[status.spenza.com](https://status.spenza.com)** is the source of truth for the Spenza API's availability. It's monitored independently of the API, so it stays up when the API doesn't. Check it before you start debugging a sudden spike in errors, and before you schedule anything time-critical. > **[Current status](https://status.spenza.com)** > > Live state of each service, with 90 days of uptime history. > **[Scheduled maintenance](https://status.spenza.com/maintenance)** > > Planned work, listed by month for the months ahead. > **[Previous incidents](https://status.spenza.com/incidents)** > > What went wrong, when, and how it was resolved. ## What's monitored | Service | What it covers | | - | - | | **API** | Spenza API availability: `https://api.spenza.com`, every endpoint in this documentation. | | **Website** | Spenza's website. | Each service shows its current status and a 90-day uptime bar. Hover over a day for that day's details. ## What each status means for your integration | Status | What it means | What to do | | - | - | - | | **Operational** | The service is up and responding normally. | Nothing. If you're still seeing errors, the problem is probably in your request or your network. See [Is it an outage or my integration?](#is-it-an-outage-or-my-integration) below. | | **Degraded** | The service is up, but slower than normal or failing some requests. | Expect timeouts and intermittent `5xx`. Retry with backoff, and hold off on bulk jobs until it recovers. | | **Downtime** | The service is unavailable. | Stop sending new work, and queue it on your side. Don't retry in a tight loop — back off until the status changes. | | **Maintenance** | Planned work is in progress. | Treat it as downtime for the announced window. Resume once it's over. | | **Not monitored** | No monitoring data for this period. | Not a signal either way. | | **Recovered** | An earlier problem has been resolved. | Resume normal traffic, and replay anything you queued. | ## Planned maintenance Planned work is announced on **[status.spenza.com/maintenance](https://status.spenza.com/maintenance)**, grouped by month for the current month and the months ahead. Each entry gives the window and which service is affected. Check it before you: * launch an integration or roll out a release that depends on the API, * run a bulk job such as mass eSIM provisioning, plan purchases or user imports, * schedule a customer-facing event that relies on activations or number assignments going through. During a maintenance window, API requests can fail or time out. Pause billable and state-changing work (purchases, top-ups, port-ins, provisioning) until the window closes, rather than relying on retries to get through it. > [!NOTE] > > The months shown say **No maintenance scheduled** when nothing is planned. If you need a quiet period guaranteed around a launch, email [support@spenza.com](mailto:support@spenza.com) in advance. ## Get notified The status page publishes incident and maintenance announcements as an RSS feed: ``` https://status.spenza.com/feed.rss ``` Add it to a feed reader, an RSS connector in Slack or Microsoft Teams, or your own monitoring, which can poll it every few minutes and raise an internal alert when a new item appears. The feed is meant for those tools. Opening it in a browser shows raw XML or downloads a file. > [!NOTE] > > **The feed is empty until the first announcement.** It lists only incidents and planned maintenance, so it has no items until one is posted, and some readers show an empty feed as "no updates" or refuse to add it. Email and SMS subscriptions aren't offered on the status page today. Until the feed has history, bookmark **[status.spenza.com](https://status.spenza.com)** and check it as described below. ## Is it an outage or my integration? 1. **Check [status.spenza.com](https://status.spenza.com).** If the API is shown as **Degraded**, **Downtime** or **Maintenance**, you're probably affected by that. Back off and wait for it to recover. 2. **Look at the status code.** `400`, `401`, `403`, `404` and `409` come from the request itself and won't fix themselves. Check the `error.code` against **[Errors](/errors)**. `429` means you've hit a rate limit (see **[Rate Limits](/rate-limits)**), not that the API is down. 3. **The status page says Operational but you're getting repeated `5xx` or timeouts?** Retry a `GET` with backoff. If it keeps failing, email [support@spenza.com](mailto:support@spenza.com) with the details listed on **[Support](/support#what-to-include-when-you-report-an-issue)**: the request, the response, and a UTC timestamp. ## Building for resilience Plan for outages up front, so an incident slows your integration down rather than breaking it: * **Retry `5xx`, timeouts and `429` with exponential backoff and jitter**, and give up after a bounded number of attempts. Don't retry other `4xx` responses unchanged. See **[Errors → Retry recommendations](/errors#retry-recommendations)** and **[Rate Limits → Recommended backoff strategy](/rate-limits#recommended-backoff-strategy)**. * **Send an `Idempotency-Key` on writes** that support it, so a retry after a timeout can't buy, provision or top up twice. See **[Core Concepts → Idempotency](/core-concepts#idempotency)**. * **Keep polling async operations.** A `transactionId` stays valid through a blip, so resume polling `GET /api/v3/transactions/{transactionId}` instead of resubmitting the original request. * **Queue work during an outage** and replay it once the status page shows the API as recovered, rather than dropping it or hammering the API. * **Use a circuit breaker.** After repeated failures, stop calling for a short cool-down and show your users a clear "temporarily unavailable" state. ## Contact The **Get in touch** link on the status page goes to [support@spenza.com](mailto:support@spenza.com), the same address as **[Support](/support)**. Use it to report a problem the status page doesn't show yet. # Support Source: https://docs.spenza.com/support How to reach Spenza API support and what to include for a fast resolution. ## How to get help Email **[support@spenza.com](mailto:support@spenza.com)** for API support — account provisioning, credential issues, questions about a specific endpoint's behavior, or anything this documentation doesn't answer (including the gaps called out throughout — webhook payload schemas, sandbox access, and specific rate-limit thresholds, for example). Check **[status.spenza.com](https://status.spenza.com)** first if you suspect an outage or degraded service rather than a bug in your own integration. See **[API Status & Maintenance](/status)** for what each status means, where planned maintenance is announced, and how to subscribe to updates. For general product/account questions unrelated to the API itself, use your existing Spenza account representative if you have one. > [!NOTE] > > **More support channels are being decided.** A community forum or chat support for the Partner API aren't set up yet. Until that's settled, treat `support@spenza.com` as the reliable default. ## What to include when you report an issue The faster you can give this, the faster it's actionable: * **What you were trying to do** — the endpoint (method + path) and a summary of the goal, not just "it's broken." * **The exact request** — method, full path, headers (**redact your bearer token and any secrets**), and body. Copying the cURL sample from the reference page and adjusting it is often the clearest way to share this. * **The exact response** — status code and full response body, especially `error.code` and `error.message`. * **A timestamp** (with timezone/UTC offset) and, if relevant, your account/partner identifier — this lets Spenza correlate your report against server-side logs. * **For async operations** — the `transactionId`, not just the call that created it. That's the fastest way to look up what actually happened server-side. * **Whether it's reproducible** — a one-off blip vs. a consistent failure point you can trigger on demand changes how it gets triaged. > [!WARNING] > > **Never include credentials in a support request.** Redact your API secret, bearer tokens, and any webhook `authentication` credentials before sharing a request. If you believe a credential was exposed, say so explicitly and ask for rotation — see **[Security & Best Practices → Secret rotation](/security#secret-rotation)** — rather than pasting the value itself for reference. ## Before you reach out Many issues are answered faster by checking these first: * **[Errors](/errors)** — the full error-code taxonomy and what each one means. * **[FAQ & Troubleshooting](/faq)** — common setup, auth, and payload issues. * **API Reference** (sidebar) — the exact field/parameter contract for the endpoint you're calling. # Webhooks Source: https://docs.spenza.com/webhooks Register endpoints to receive operator SMS and voice events, verify their signature, and inspect deliveries. Spenza can push operator-originated SMS and voice events to a URL you control, instead of you polling for them. You manage this through a REST collection — register a webhook, list your registrations, update or delete them — and every delivery is signed so you can verify it actually came from Spenza. > [!NOTE] > > This page covers **operator SMS and voice event** webhooks. **Call-quality test results** use their own webhook, `POST /api/v1.1/voice-quality/webhooks`, with a fixed `voice.test.completed` payload signed the same way — see **[Testing call quality](/guides#testing-call-quality)**. ## The event model You register **one webhook per operator + network combination**, choosing which event category it covers: | `eventType` | Delivers | | - | - | | `sms` | Inbound SMS events for that operator/network. | | `voice` | Inbound voice events for that operator/network. | | `both` | Both. | There's at most one registration per (account, operator, network) — `eventType` isn't part of that key, so registering a second event type for the same operator+network **replaces** the first rather than adding a second registration. Registering again for an existing combination without `update: true` in the body returns `409 CONFLICT`. > [!NOTE] > > Registering `voice` (or `both`) always succeeds if the operator/network combination itself is valid — there's no registration-time check that voice is actually enabled the way there is for `sms`. But you won't actually **receive** voice events for a line unless that line's active plan includes voice support (a plan with no voice allowance leaves voice disabled on the number). Make sure the SIMs you expect voice events for are on a voice-capable plan before assuming a registered `voice` webhook is misbehaving if nothing arrives. This applies to `voiceStreamUrl` (see [Streaming live voice media](#streaming-live-voice-media)) as well — there's no separate "voice streaming" plan capability, it rides on the same voice allowance as `voiceUrl`/`callbackVoiceUrl`. ## Registering a webhook ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/webhooks" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "operator": "SpenzaJ", "network": "T-Mobile", "eventType": "sms", "authentication": { "type": "bearer", "token": "a-secret-you-choose" }, "webhookUrls": { "messageUrl": "https://partner.example.com/hooks/sms" }, "retryPolicy": { "maxAttempts": 5, "backoffStrategy": "exponential", "initialDelaySeconds": 5, "maxDelaySeconds": 300 }, "status": "active" }' ``` The response echoes your registration back with credential fields masked as `"***ENCRYPTED***"`, **plus a one-time `signingSecret`** (format `whsec_<64 hex chars>`) — see [Verifying delivery signatures](#verifying-delivery-signatures) below. ## Streaming live voice media `webhookUrls.voiceStreamUrl` is a different kind of field from `messageUrl`/`voiceUrl`/etc. — instead of an HTTP POST per event, Spenza opens an **outbound WebSocket connection** to it whenever a live voice call starts on that operator/network: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/webhooks" \ -H "Authorization: Bearer $SPENZA_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "operator": "SpenzaJ", "network": "T-Mobile", "eventType": "voice", "authentication": { "type": "bearer", "token": "a-secret-you-choose" }, "webhookUrls": { "voiceStreamUrl": "wss://partner.example.com/hooks/voice-stream" }, "status": "active" }' ``` * Accepts `ws://`, `wss://`, `http://`, or `https://` (Spenza always connects over WebSocket regardless of scheme). * On connect, Spenza sends a JSON handshake frame first, then streams binary PCM audio (8kHz, 16-bit, mono) frames in real time for the duration of the call. * It's independent of `voiceUrl`/`callbackVoiceUrl` — you can set any combination of the three on a `voice`/`both` registration, including `voiceStreamUrl` alone. * It only ever activates if that line's active plan includes voice support, same as any other voice delivery — see the note above. * It's **never** used as a `POST /api/v1.1/webhooks/{id}/test` target — see [Testing a registration](#testing-a-registration). Manage registrations as a normal REST collection: ```bash theme={null} curl "https://api.spenza.com/api/v1.1/webhooks" -H "Authorization: Bearer $SPENZA_TOKEN" curl "https://api.spenza.com/api/v1.1/webhooks/{id}" -H "Authorization: Bearer $SPENZA_TOKEN" curl -X PUT "https://api.spenza.com/api/v1.1/webhooks/{id}" -H "Authorization: Bearer $SPENZA_TOKEN" -d '{ }' curl -X DELETE "https://api.spenza.com/api/v1.1/webhooks/{id}" -H "Authorization: Bearer $SPENZA_TOKEN" ``` None of the read/list/get calls ever return `signingSecret` again — only the create/upsert response does. Store it the moment you get it; losing it means re-registering. ## How your endpoint authenticates the caller Separately from payload signing, `authentication` (`type: basic | bearer | api_key | none`) protects **your** webhook URL — Spenza presents this credential when it calls you, so your endpoint can reject callers that don't have it. Set it to `bearer` or `basic`, not `none`, so your endpoint isn't open to anyone who discovers its URL. ## Verifying delivery signatures Every delivery (including test events) carries two headers: ```http theme={null} X-Spenza-Signature: t=1719792000,v1=9f8b3c2e1a4d6f7b8c9e0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d X-Spenza-Timestamp: 1719792000 ``` `X-Spenza-Timestamp` is Unix seconds. The `v1` value in `X-Spenza-Signature` is an HMAC-SHA256 computed over the exact string `${timestamp}.${rawBody}`, keyed with your registration's `signingSecret` — a Stripe-compatible scheme, chosen so most partners can reuse an existing verifier: ```js theme={null} const crypto = require("crypto"); function verifySpenzaSignature(rawBody, signatureHeader, timestampHeader, signingSecret) { const expected = crypto .createHmac("sha256", signingSecret) .update(`${timestampHeader}.${rawBody}`) .digest("hex"); const provided = signatureHeader.split(",").find((p) => p.startsWith("v1="))?.slice(3); return provided && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(provided)); } ``` Compare against `rawBody` (the exact bytes received), not a re-serialized version of the parsed JSON — re-serialization can silently change key order or whitespace and break the comparison. A 5-minute tolerance window on `X-Spenza-Timestamp` is documented convention (`WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300`) — Spenza doesn't enforce it on the sending side; it's your endpoint's own replay-protection check to make if you want it. ## Retry behavior Delivery retries are configurable per registration via `retryPolicy`: | Field | Purpose | Default | | - | - | - | | `maxAttempts` | How many times Spenza retries a failed delivery (1–10). | `3` | | `backoffStrategy` | `fixed`, `exponential`, or `linear`. | `exponential` | | `initialDelaySeconds` | Delay before the first retry (1–60). | `5` | | `maxDelaySeconds` | Ceiling on the delay between retries (60–3600). | `300` | A delivery is considered successful when your endpoint returns **any `2xx` response** — respond fast and do your processing after responding, not before. After **10 consecutive delivery failures**, a registration's `status` automatically flips to `suspended`; check `GET /api/v1.1/webhooks` periodically, or the `status` field on `GET /api/v1.1/webhooks/{id}`, to catch this. ## Testing a registration Send a one-off synthetic event without waiting for a real operator event: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/webhooks/{id}/test" \ -H "Authorization: Bearer $SPENZA_TOKEN" -H "Content-Type: application/json" \ -d '{ "eventType": "webhook.test" }' ``` This sends one attempt (no retries) to whichever URL is configured, in priority order `messageUrl` → `callbackMessageUrl` → `voiceUrl` → `callbackVoiceUrl` (`voiceStreamUrl` is never a test target — there's no synthetic way to rehearse the WebSocket relay). It's recorded in the deliveries list but **doesn't** count toward the 10-consecutive-failure auto-suspend threshold, so you can rehearse your handler without risking a live registration's status. ## Inspecting and redelivering past events ```bash theme={null} curl "https://api.spenza.com/api/v1.1/webhook-deliveries?webhookId={id}&status=FAILED" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` This never returns the delivered payload, response body, or raw error text — just status/timing metadata (`deliveryId`, `webhookId`, `eventType`, `status`, `responseCode`, `attempt`, `deliveredAt`). If you find a `FAILED` delivery worth retrying manually (after fixing your handler, for example), redeliver the **original** event and body to its original endpoint: ```bash theme={null} curl -X POST "https://api.spenza.com/api/v1.1/webhook-deliveries/{deliveryId}/redeliver" \ -H "Authorization: Bearer $SPENZA_TOKEN" ``` This queues the redelivery and returns `202` immediately with a new `PENDING` delivery record — it runs on a background queue, not the request cycle, so poll the deliveries list for the outcome. ## Idempotency > [!WARNING] > > **No delivery/event ID for dedup yet.** There's no dedicated event ID field in the delivered payload itself. Retries (both automatic and manual redelivery) mean **a given event may be delivered more than once**; design your handler to be safe to run twice — for example, keying off whatever naturally-unique fields the payload contains (message SID, timestamp + from/to number) once you've inspected a real payload, and ignoring exact duplicates. ## Example payloads > [!NOTE] > > **Payload schema is being published.** The exact JSON body sent to `messageUrl`/`voiceUrl` on a real inbound SMS or voice event isn't published yet. Until then, register a webhook against a test endpoint (a request-inspection tool) and use `POST /api/v1.1/webhooks/{id}/test` or a real event to capture the actual shape before writing a parser. ## Next steps * **[Security & Best Practices](/security)** for handling the credentials in `authentication` and `signingSecret`. * **API Reference → Webhooks** (sidebar) for the full field-level schema of the registration and delivery objects.