# Introduction

Build Lightning-powered SMS, number-rental, and email activation workflows with sms4sats API v2.

Use sms4sats to receive one-time SMS codes, rent temporary phone numbers, or receive email activation codes. Those products use per-order Bitcoin Lightning payments—no customer account or prepaid balance required. For outgoing messages, see the separate [Send SMS](https://docs.sms4sats.com/send-sms/send-sms) section, including legacy-compatible prepaid balances and top-ups.

Prefer a user interface? Open the [sms4sats web app](https://sms4sats.com).

{% hint style="warning" %}
**API v2 cutover:** `https://api.sms4sats.com` is the canonical API. The legacy service is offline. Receive-SMS, rentals and email integrations use the endpoints documented here; the [Send SMS](https://docs.sms4sats.com/send-sms/send-sms) compatibility API retains its original endpoint paths on the canonical origin.
{% endhint %}

## Choose your integration

| API                                                                                        | Best for                                 | Payment model                     | Order access                                         |
| ------------------------------------------------------------------------------------------ | ---------------------------------------- | --------------------------------- | ---------------------------------------------------- |
| [Bearer-token API](https://docs.sms4sats.com/getting-started/api-options#bearer-token-api) | Web, mobile, backend apps, and most bots | Lightning hold invoice            | Opaque bearer token returned at creation             |
| [L402 API](https://docs.sms4sats.com/getting-started/api-options#l402-api)                 | AI agents and Lightning-native services  | BOLT11 invoice + payment preimage | L402 macaroon and preimage                           |
| [Email API](https://docs.sms4sats.com/api-reference/emails)                                | Temporary email activation codes         | Lightning hold invoice            | Bearer token when the capability header is requested |

All APIs use this origin:

```
https://api.sms4sats.com
```

## Fastest path: receive an SMS

1. Discover service codes with [`GET /v2/receive-sms/catalog`](https://docs.sms4sats.com/api-reference/catalog-and-quotes).
2. Get a live quote with [`POST /v2/receive-sms/quote`](https://docs.sms4sats.com/api-reference/catalog-and-quotes#quote-a-receive-sms-order).
3. Create an idempotent order with [`POST /v2/receive-sms/orders`](https://docs.sms4sats.com/api-reference/create-order).
4. Save the returned `orderId` and `accessToken`, then pay the invoice.
5. Poll [`GET /v2/receive-sms/orders/{orderId}`](https://docs.sms4sats.com/api-reference/get-order) every 5–10 seconds.
6. Stop when the order reaches a [terminal state](https://docs.sms4sats.com/api-reference/order-states).

{% hint style="success" %}
Receive-SMS and email orders use **hold invoices**. Payment remains held while fulfillment is in progress and is settled on successful fulfillment. Cancellation and failure behavior depends on the product; see [Hold Invoices & Payment Safety](https://docs.sms4sats.com/getting-started/hold-invoices).
{% endhint %}

## Live discovery

```bash
curl -sS https://api.sms4sats.com/health
curl -sS https://api.sms4sats.com/v2/browser
curl -sS https://api.sms4sats.com/v2/l402
```

## Support

| Channel  | Contact                                                                      |
| -------- | ---------------------------------------------------------------------------- |
| Telegram | [@sms4sats](https://t.me/sms4sats) or [@pseudozach](https://t.me/pseudozach) |
| Email    | <support@sms4sats.com>                                                       |
| Sales    | <sales@sms4sats.com>                                                         |
| X        | [@sms4sats](https://twitter.com/sms4sats)                                    |


# Quickstart

Create, pay, and poll your first sms4sats API v2 order.

This example uses the bearer-token receive-SMS API. It is the simplest integration for web apps, mobile apps, backend services, and bots.

## 1. Discover a service

```bash
curl -sS 'https://api.sms4sats.com/v2/receive-sms/catalog?country=auto'
```

Use a `services[].code` value in the next requests. `country=auto` selects an available country automatically.

## 2. Request a live quote

```bash
curl -sS -X POST https://api.sms4sats.com/v2/receive-sms/quote \
  -H 'Content-Type: application/json' \
  -d '{"country":"auto","service":"tg"}'
```

```json
{
  "type": "receive-sms",
  "country": "151",
  "service": "tg",
  "durationMinutes": null,
  "availability": 120,
  "priceSats": 1000
}
```

A quote is side-effect free: it does not create an invoice or reserve inventory. Price and availability may change before creation.

## 3. Create the order

Generate a new UUID v4 once and reuse it only when retrying this exact request.

```bash
curl -sS -X POST https://api.sms4sats.com/v2/receive-sms/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 17165eb7-d770-4a21-abd4-90295ac15252' \
  -d '{"country":"auto","service":"tg"}'
```

```json
{
  "orderId": "<payment-hash>",
  "accessToken": "<opaque-token>",
  "orderReference": "<payment-hash>.<opaque-token>",
  "invoice": "lnbc...",
  "priceSats": 1000,
  "status": "pending_payment"
}
```

{% hint style="danger" %}
Store `accessToken` securely when it is returned. Treat it like a password: anyone who has it can read or cancel that order. Do not log it, place it in a URL, or expose it in analytics.
{% endhint %}

## 4. Pay and poll

Pay `invoice` with a Lightning wallet, then poll every 5–10 seconds:

```bash
curl -sS https://api.sms4sats.com/v2/receive-sms/orders/ORDER_ID \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

A successful order normally progresses through:

```
pending_payment → paid → allocating → waiting_for_sms → code_received → completed
```

The assigned `phoneNumber` appears after allocation. Delivered SMS content appears in `messages`.

## 5. Handle completion or cancellation

Stop polling on `completed`, `cancelled`, `expired`, or `failed`. If no message arrives, use the response's `cancellation.eligible` and `cancellation.availableAt` fields rather than a client-side guess.

```bash
curl -sS -X POST \
  https://api.sms4sats.com/v2/receive-sms/orders/ORDER_ID/cancel \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

Continue with [Catalog & Quotes](https://docs.sms4sats.com/api-reference/catalog-and-quotes) or review [Errors, Limits & Retries](https://docs.sms4sats.com/api-reference/errors) before shipping.


# Choose an API

Choose the right sms4sats API v2 payment and authentication model.

sms4sats exposes two SMS integration styles plus a dedicated email API. Choose the payment proof and credentials that fit your integration.

## Bearer-token API

**Recommended for most integrations.**

Endpoints:

```
/v2/receive-sms/*
/v2/rent-numbers/*
```

Creation returns a BOLT11 hold invoice and a one-time `accessToken`. Poll and cancellation requests use:

```http
Authorization: Bearer <accessToken>
```

Choose this API when:

* your wallet does not expose payment preimages;
* you want payment release instead of a separate refund payment;
* you need UUID-based idempotent creation;
* you are integrating a browser, mobile client, conventional backend, or bot.

## L402 API

Endpoints:

```
/v2/l402/*
```

Creation intentionally returns `402 Payment Required`, an invoice, and a macaroon. After payment, use the macaroon and payment preimage as a scoped credential:

```http
Authorization: L402 <serialized-macaroon>:<preimage-hex>
```

Choose L402 when your agent or service can pay Lightning invoices programmatically and retrieve the settlement preimage. See the complete [L402 guide](https://docs.sms4sats.com/api-reference/l402).

## Email API

Endpoint family:

```
/v2/emails/*
```

Email activation orders use hold invoices. For the protected flow documented here, creation must include `X-SMS4SATS-Email-Capability: v1`; the response then returns the bearer order token required for polling, reordering, and cancellation. Domain availability and pricing are queried before creation. See [Email Activations](https://docs.sms4sats.com/api-reference/emails).

## Product comparison

| Product          | API          | Payment outcome                                                                   | Manual cancellation                                             |
| ---------------- | ------------ | --------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| One-time SMS     | Bearer-token | Hold settles after SMS fulfillment; otherwise releases                            | After 3 minutes when eligible                                   |
| Number rental    | Bearer-token | Hold settles after successful number allocation                                   | Unpaid orders only; any paid rental is not manually cancellable |
| One-time SMS     | L402         | Standard payment; eligible failure/cancel refunds to a supplied no-amount invoice | After 3 minutes when eligible                                   |
| Number rental    | L402         | Standard payment; no rental refund flow                                           | Not supported after payment                                     |
| Email activation | Email API    | Hold settles when fulfillment succeeds; failure paths attempt release             | After 2 minutes when eligible                                   |


# Hold Invoices & Payment Safety

Understand when sms4sats Lightning hold invoices settle or release.

A Lightning hold invoice lets the receiver accept a payment without immediately settling it. The funds remain locked until sms4sats either settles the invoice with its preimage or releases it.

{% hint style="info" %}
The hold-invoice model applies to bearer-token receive-SMS orders, bearer-token rental orders, and email activations. L402 uses standard Lightning invoices. Receive-SMS and reactivation orders use a separate refund-invoice flow; paid L402 rentals have no refund flow.
{% endhint %}

## Receive SMS

```
invoice paid
  → number allocated
  → SMS received
  → hold settled
```

If allocation fails, the order expires, or an eligible cancellation completes, the held payment is released after the order outcome is confirmed. Keep polling while the order remains pending.

## Email activation

```
invoice paid
  → email assigned
  → provider returns a code or message
  → hold settled; order completed
```

Allocation failure, cancellation, and timeout can release the hold. A successful manual cancellation confirms the payment release. Poll the order and check your wallet rather than assuming release from elapsed time alone.

## Number rentals

The rental hold invoice settles when the number is allocated—not when a later SMS arrives. Manual cancellation is available only before payment; any paid browser rental is not manually cancellable.

## What “released” means

A released hold was never finally transferred to sms4sats. Most wallets restore the amount to the spendable balance automatically. Wallet interfaces may briefly show the payment as pending while the release propagates.

## Integration rules

1. Display `priceSats` from the creation response, not a locally calculated price.
2. Treat payment as pending until the order API reports progress.
3. Follow server-provided state and cancellation fields.
4. Keep polling through transitional states such as `settlement_pending`, `release_pending`, and `cancelling`.
5. Stop only on a terminal state.
6. For bearer-token SMS/rental creation only, retry an ambiguous response with the same idempotency key. Email and L402 creation do not support idempotency keys and must not be retried blindly.


# Wallets & Payments

Pay sms4sats BOLT11 invoices with a Lightning wallet, Lightning Pay Kit, or a supported swap route.

sms4sats returns standard BOLT11 Lightning invoices. Any compatible Lightning wallet can pay them.

## Lightning Pay Kit

sms4sats uses our open-source **Lightning Pay Kit** on invoice screens to help users find a suitable wallet, payment app, exchange, or swap route. Developers can add the same payment helper to any React application.

{% embed url="<https://pseudozach.github.io/lightning-pay-kit/>" %}
Try Lightning Pay Kit
{% endembed %}

{% embed url="<https://github.com/pseudozach/lightning-pay-kit>" %}
Lightning Pay Kit source code
{% endembed %}

## Lightning wallets

{% embed url="<https://lightsats.com/guide/wallets>" %}
Lightning wallet guide
{% endembed %}

{% embed url="<https://darth-coin.github.io/wallets/lightning-wallets-comparison-en.html>" %}
Lightning wallet comparison
{% endembed %}

## Paying from another asset

If you hold ETH or another supported asset, FixedFloat can swap it to Bitcoin over Lightning for payment of a BOLT11 invoice.

{% embed url="<https://fixedfloat.com/ETH/BTCLN?ref=pmdxabka>" %}
Swap ETH to Lightning BTC with FixedFloat
{% endembed %}

This is a referral link, so sms4sats may receive a referral reward. FixedFloat controls its own availability, rates, and fees.

## L402 wallet requirement

L402 clients must retrieve the **payment preimage** after payment. Many consumer wallets do not expose it. Use an L402-capable client or a Lightning node/API that returns the 32-byte preimage; otherwise use the bearer-token API.


# Lightning Node

Connect directly to the sms4sats Lightning node for reliable payment routing.

High-volume partners may open a direct channel to improve routing reliability. Contact us if you need a balanced channel or routing assistance.

{% embed url="<https://amboss.space/node/035b04e00521a8d50894e813c72576d2a03a09cd940be074b7f2e35e0a01d7d12d>" %}
sms4sats on Amboss
{% endembed %}

| Field      | Value                                                                                                          |
| ---------- | -------------------------------------------------------------------------------------------------------------- |
| Public key | `035b04e00521a8d50894e813c72576d2a03a09cd940be074b7f2e35e0a01d7d12d`                                           |
| Explorer   | [View on Amboss](https://amboss.space/node/035b04e00521a8d50894e813c72576d2a03a09cd940be074b7f2e35e0a01d7d12d) |

For channel coordination, contact <support@sms4sats.com> or [@sms4sats](https://t.me/sms4sats).


# Overview

Complete endpoint map and conventions for sms4sats API v2.

## Base URL

```
https://api.sms4sats.com
```

Requests and responses use JSON unless otherwise noted. Send `Content-Type: application/json` with JSON bodies.

## Documented client integration endpoints

### Service discovery

| Method | Path                         | Purpose                    |
| ------ | ---------------------------- | -------------------------- |
| `GET`  | `/health`                    | API and database health    |
| `GET`  | `/v2/browser`                | Bearer-token API discovery |
| `GET`  | `/v2/l402`                   | L402 API discovery         |
| `GET`  | `/.well-known/l402-services` | L402 service discovery     |

### Bearer-token SMS

| Method | Path                                 | Purpose                   |
| ------ | ------------------------------------ | ------------------------- |
| `GET`  | `/v2/receive-sms/catalog`            | Supported service codes   |
| `POST` | `/v2/receive-sms/quote`              | Live receive-SMS quote    |
| `POST` | `/v2/receive-sms/orders`             | Create hold-invoice order |
| `GET`  | `/v2/receive-sms/orders/{id}`        | Poll protected order      |
| `POST` | `/v2/receive-sms/orders/{id}/cancel` | Cancel eligible order     |

### Bearer-token rentals

| Method | Path                                  | Purpose                                    |
| ------ | ------------------------------------- | ------------------------------------------ |
| `GET`  | `/v2/rent-numbers/catalog`            | Rental countries, availability, and prices |
| `POST` | `/v2/rent-numbers/quote`              | Live rental quote                          |
| `POST` | `/v2/rent-numbers/orders`             | Create rental order                        |
| `GET`  | `/v2/rent-numbers/orders/{id}`        | Poll rental order                          |
| `POST` | `/v2/rent-numbers/orders/{id}/cancel` | Cancel an unpaid rental                    |

### Email activations

| Method   | Path                        | Purpose                                                                   |
| -------- | --------------------------- | ------------------------------------------------------------------------- |
| `GET`    | `/v2/emails/domains?site=…` | Available domains and prices                                              |
| `POST`   | `/v2/emails`                | Create hold-invoice email order                                           |
| `GET`    | `/v2/emails/{id}`           | Poll protected email order                                                |
| `POST`   | `/v2/emails/{id}/reorder`   | Reuse an assigned email for another activation                            |
| `POST`   | `/v2/emails/{id}/cancel`    | Cancel an eligible email order                                            |
| `DELETE` | `/v2/emails/{id}`           | Server-side cancellation alias; browser CORS permits `POST`, not `DELETE` |

### L402

| Method | Path                         | Purpose                                      |
| ------ | ---------------------------- | -------------------------------------------- |
| `GET`  | `/v2/l402/services`          | Service codes                                |
| `GET`  | `/v2/l402/catalog`           | Cached receive-SMS and reactivation offers   |
| `POST` | `/v2/l402/order`             | Create an L402 order/challenge               |
| `GET`  | `/v2/l402/order/{id}`        | Authenticate, allocate, and poll             |
| `POST` | `/v2/l402/order/{id}/cancel` | Cancel and refund eligible receive-SMS order |

Use only the documented endpoints for customer integrations.

## Global limits

* Global rate limit: **300 requests per minute per client**.
* Bearer-token order creation: **60 requests per minute per client**.
* JSON request bodies are limited to **200 KB**.
* Rate-limit responses use HTTP `429` and standard rate-limit headers.

## Health response

```json
{
  "status": "ok",
  "orderStatus": "healthy",
  "dbStatus": "up",
  "timestamp": "2026-09-30T19:00:00.000Z"
}
```


# Catalog & Quotes

Discover service codes and request current quotes before creating an order.

Catalog requests are read-only. Quote requests check live inventory and pricing but do not issue invoices or reserve a number. Objects that contain `country` also include `countryName`, `countryCallingCode` and `countryIsoCode`, all null before allocation. Read the allocated values from the [protected order snapshot](https://docs.sms4sats.com/api-reference/get-order#country-metadata); do not treat a quoted route as an allocated country. Existing country IDs and request bodies are unchanged.

## Minimum order price

New API V2 Receive SMS, number rental, and email orders have a **1000-sat minimum**. The same server-side floor applies to browser and L402 quotes/catalog prices and newly created invoices. Display the returned `priceSats` without adding another multiplier or floor. Higher-priced routes keep their existing pricing. Existing orders/invoices and independently priced legacy Send SMS/prepaid endpoints are unchanged.

## Receive-SMS countries

<mark style="color:blue;">`GET`</mark> `/v2/receive-sms/countries`

Use this public endpoint to populate a receive-SMS country picker. No authentication, order token, or query parameters are required. It reads bundled country metadata only: no database/provider requests, invoices, reservations, or payments.

```bash
curl -sS 'https://api.sms4sats.com/v2/receive-sms/countries'
```

Response shape (the real response includes the complete country list):

```json
{
  "type": "receive-sms",
  "defaultCountry": "auto",
  "legacyCountryAliases": { "999": "auto" },
  "countries": [
    { "id": "auto", "name": "Auto-select" },
    { "id": "74", "name": "Afghanistan" }
  ]
}
```

* Use `countries[].name` as the display label and pass `countries[].id` as the string `country` value to catalog, quote, and create-order requests.
* Auto-select is first; the remaining countries are sorted by English name. IDs are stable SMS4Sats country identifiers, **not telephone calling codes or ISO numeric codes**.
* `defaultCountry: "auto"` means the server selects a country when quoting an order. A quote or order response may therefore contain a concrete country ID instead of `"auto"`.
* **Legacy migration:** normalize saved country `999` (number or string) to `"auto"` before calling v2. `legacyCountryAliases` describes this client-side conversion; it does not change existing endpoints to accept `999` as an Auto alias. All other picker IDs remain unchanged.
* This country list is reference metadata, not a stock promise. Request `/v2/receive-sms/catalog?country={id}` to populate verified purchasing services for the selected country, then quote before checkout.

```js
const country = picker.legacyCountryAliases[String(savedCountry)]
  ?? String(savedCountry);
```

## Receive-SMS catalog

<mark style="color:blue;">`GET`</mark> `/v2/receive-sms/catalog?country={country}`

`country` accepts `auto`, a supported numeric country ID, ISO alpha-2 code, or country name. It defaults to `auto`.

```bash
curl -sS 'https://api.sms4sats.com/v2/receive-sms/catalog?country=auto'
```

```json
{
  "type": "receive-sms",
  "country": "auto",
  "countryName": null,
  "countryCallingCode": null,
  "countryIsoCode": null,
  "services": [
    {
      "code": "tg",
      "name": "Telegram"
    },
    {
      "code": "go",
      "name": "Google,youtube,Gmail"
    }
  ],
  "updatedAt": "2026-11-07T12:00:00.000Z",
  "availability": {
    "status": "available",
    "coverage": "partial",
    "checkedAt": "2026-11-07T12:00:00.000Z",
    "validUntil": "2026-11-07T12:01:00.000Z"
  }
}
```

The purchase catalog is **stock-filtered by default**. For a selected country, `services` contains only canonical services with positive stock and a positive valid price recently verified through at least one enabled supplier. A name in the reference dictionary is not enough. Results merge suppliers, so secondary-supplier-only stock is retained. Stock is not reserved: request a quote and handle `409 UNAVAILABLE` if it sells out before checkout.

Inventory observations expire after **60 seconds**, without relabeling older quote-cache data as fresh. `updatedAt` and `availability.checkedAt` are the oldest relevant observation time; `availability.validUntil` is its expiry. Repeated cache hits retain those timestamps. The service performs bounded, coalesced country reads rather than one quote per service or an unfiltered global feed.

* `availability.status: "available"`: at least one verified option is returned.
* `availability.status: "empty"`, `coverage: "complete"`: every enabled supplier was checked for that country and no usable stock was found; `services` is empty.
* `coverage: "partial"`: only verified options are returned, but a supplier check or the global country scan is incomplete. Missing names are not proof of worldwide unavailability.
* No verified options and incomplete/failed checks: **503 `METADATA_NOT_READY`**, with `Retry-After: 15`. Back off; do not substitute the full name dictionary or treat the failure as confirmed zero stock.

`country=auto` is a **partial union of verified concrete-country snapshots**. It warms a bounded set of countries and also includes fresh snapshots discovered through explicit-country requests. It never claims an exhaustive global stock scan. An explicit-country catalog is the appropriate way to discover options for that country.

## Reference service names (not inventory)

`GET /v2/receive-sms/metadata` returns the full canonical `{code,name}` service dictionary with `availabilityChecked: false`, without supplier or database calls. Use it for labels, not purchasing options. `/v2/receive-sms/countries` remains reference country metadata; populate purchasable services from `/catalog` for the selected country. Existing IDs, aliases, prices, quote/order bodies, payment behavior and allocated-country fields are unchanged.

## Quote a receive-SMS order

<mark style="color:green;">`POST`</mark> `/v2/receive-sms/quote`

| Body field        | Type   | Required | Description                                      |
| ----------------- | ------ | -------- | ------------------------------------------------ |
| `country`         | string | Yes      | `auto`, numeric ID, ISO code, or country name    |
| `service`         | string | Yes      | Catalog code or recognized service name          |
| `referral`        | string | No       | Referral metadata, maximum 320 characters        |
| `clientRequestId` | string | No       | Client correlation value, maximum 200 characters |

```bash
curl -sS -X POST https://api.sms4sats.com/v2/receive-sms/quote \
  -H 'Content-Type: application/json' \
  -d '{"country":"auto","service":"tg"}'
```

```json
{
  "type": "receive-sms",
  "country": "151",
  "countryName": null,
  "countryCallingCode": null,
  "countryIsoCode": null,
  "service": "tg",
  "durationMinutes": null,
  "availability": 120,
  "priceSats": 1000
}
```

`country` may differ from the request when `auto` selects a country. Quotes may be up to five minutes old and do not guarantee availability. Always use the creation response's `priceSats` for payment UI.

## Rental catalog

<mark style="color:blue;">`GET`</mark> `/v2/rent-numbers/catalog?service={service}&durationMinutes={minutes}`

* `service` defaults to `full`.
* `durationMinutes` is normalized upward to a whole hour with a minimum of 120 and a maximum request value of 43,200.

```json
{
  "type": "rent-number",
  "service": "full",
  "durationMinutes": 120,
  "countries": [
    {
      "country": "1",
      "countryName": null,
      "countryCallingCode": null,
      "countryIsoCode": null,
      "availability": 3,
      "durationMinutes": 120,
      "priceSats": 1800
    }
  ],
  "updatedAt": "2026-09-30T19:00:00.000Z"
}
```

An empty `countries` array means no matching rental is currently available.

## Quote a rental

<mark style="color:green;">`POST`</mark> `/v2/rent-numbers/quote`

```bash
curl -sS -X POST https://api.sms4sats.com/v2/rent-numbers/quote \
  -H 'Content-Type: application/json' \
  -d '{"country":"1","service":"full","durationMinutes":120}'
```

The response has the same fields as a receive-SMS quote, with `type: "rent-number"` and a normalized `durationMinutes`.

{% hint style="info" %}
Availability is inherently volatile. Handle `409 UNAVAILABLE` even when a quote succeeded moments earlier.
{% endhint %}


# Create a Bearer-Token Order

Create an idempotent receive-SMS or rental order and receive its hold invoice and access token.

{% tabs %}
{% tab title="Receive SMS" %} <mark style="color:green;">`POST`</mark> `/v2/receive-sms/orders`
{% endtab %}

{% tab title="Rent Number" %} <mark style="color:green;">`POST`</mark> `/v2/rent-numbers/orders`
{% endtab %}
{% endtabs %}

## Headers

| Header                           | Required | Description                                   |
| -------------------------------- | -------- | --------------------------------------------- |
| `Content-Type: application/json` | Yes      | JSON request body                             |
| `Idempotency-Key: <UUID v4>`     | Yes      | Random UUID v4 scoped to the selected product |

`X-Idempotency-Key` is accepted as an equivalent header. Prefer `Idempotency-Key`.

## Body

| Field             | Type    | Receive      | Rental   | Description                                           |
| ----------------- | ------- | ------------ | -------- | ----------------------------------------------------- |
| `country`         | string  | Required     | Required | `auto`, numeric ID, ISO code, or country name         |
| `service`         | string  | Required     | Required | Service code or recognized name                       |
| `durationMinutes` | integer | Ignored/omit | Optional | 1–43,200; normalized to at least 120 and a whole hour |
| `referral`        | string  | Optional     | Optional | Maximum 320 characters                                |
| `clientRequestId` | string  | Optional     | Optional | Client correlation value, maximum 200 characters      |

The endpoint path determines the product type. Do not send a conflicting `type` field.

## Example

```bash
curl -sS -X POST https://api.sms4sats.com/v2/receive-sms/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 17165eb7-d770-4a21-abd4-90295ac15252' \
  -d '{"country":"US","service":"tg","clientRequestId":"checkout-123"}'
```

Response: HTTP `201 Created`

```json
{
  "orderId": "<payment-hash>",
  "accessToken": "<opaque-token>",
  "orderReference": "<payment-hash>.<opaque-token>",
  "invoice": "lnbc...",
  "priceSats": 1000,
  "status": "pending_payment"
}
```

## Idempotent retries

* Same key + same normalized body: returns the original order and invoice.
* Same key + different body: `409 IDEMPOTENCY_CONFLICT`.
* Concurrent retry while creation is running: `409 IDEMPOTENCY_IN_PROGRESS`; retry the same request and key after a short delay.
* Network timeout or ambiguous `5xx`: retry the same request and key. Never generate a new key until you know the original request did not create an order.

{% hint style="danger" %}
`accessToken` is returned as a secret order capability. Persist it before navigating away. `orderReference` packages the order ID and token for client-side portability; it is equally sensitive.
{% endhint %}


# Poll an Order

Poll a protected receive-SMS or rental order and read its messages and cancellation state.

{% tabs %}
{% tab title="Receive SMS" %} <mark style="color:blue;">`GET`</mark> `/v2/receive-sms/orders/{orderId}`
{% endtab %}

{% tab title="Rent Number" %} <mark style="color:blue;">`GET`</mark> `/v2/rent-numbers/orders/{orderId}`
{% endtab %}
{% endtabs %}

```http
Authorization: Bearer <accessToken>
```

```bash
curl -sS https://api.sms4sats.com/v2/receive-sms/orders/ORDER_ID \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

## Representative response

```json
{
  "id": "<payment-hash>",
  "orderId": "<payment-hash>",
  "type": "receive-sms",
  "country": "39",
  "countryName": "Argentina",
  "countryCallingCode": "+54",
  "countryIsoCode": "AR",
  "service": "tg",
  "status": "waiting_for_sms",
  "orderStatus": "waiting_for_sms",
  "priceSats": 1000,
  "phoneNumber": "+54...",
  "messages": [],
  "durationMinutes": null,
  "createdAt": "2026-09-30T19:00:00.000Z",
  "updatedAt": "2026-09-30T19:01:10.000Z",
  "paidAt": "2026-09-30T19:01:00.000Z",
  "expiresAt": "2026-09-30T19:21:00.000Z",
  "completedAt": null,
  "cancelledAt": null,
  "failedAt": null,
  "cancellation": {
    "eligible": false,
    "availableAt": "2026-09-30T19:04:00.000Z"
  }
}
```

A delivered message appears as:

```json
{
  "id": "<message-id>",
  "code": "123456",
  "content": "Your verification code is 123456",
  "receivedAt": "2026-09-30T19:02:00.000Z"
}
```

## Country metadata

`country` is the existing SMS4Sats country ID and remains unchanged for backward compatibility. It is **not** a calling code: Argentina is `"39"`, while its calling code is `"+54"`.

| Field                | Type           | Description                                                     |
| -------------------- | -------------- | --------------------------------------------------------------- |
| `countryName`        | string or null | English name of the allocated number's country.                 |
| `countryCallingCode` | string or null | International calling code including `+`.                       |
| `countryIsoCode`     | string or null | Uppercase ISO 3166-1 alpha-2 code, suitable for flag rendering. |

All three new fields are **null until a phone number is allocated**, regardless of the selected country. Before allocation, display Country — without a flag or calling-code copy action. After allocation, read these server fields directly; no client lookup table or number-detection library is needed. They describe the allocated number, including when the request used Auto, rather than the original selection.

The fields apply to both Receive-SMS and rental snapshots and to the full snapshot returned by cancellation. Existing stored orders are enriched on read without a migration. If a country cannot be determined safely, its name/ISO stays null; a known calling code may still be returned. United States and Canada share `+1`, so that prefix alone is not a country identifier. Never display a guessed flag.

Creation acknowledgements do not contain `country` and retain their existing shape. Catalogs and quotes with `country` include the new fields as null because no number has been allocated. These are response fields only; do not add them to create/quote request bodies. L402, email and legacy APIs are unchanged.

## Polling rules

* Poll every **5–10 seconds**.
* Treat `status` and `orderStatus` as equivalent lifecycle fields.
* Do not infer success from the presence of a phone number; wait for a message and terminal state.
* Stop on `completed`, `cancelled`, `expired`, or `failed`.
* Keep polling transitional states rather than creating a replacement order.

See [Order States](https://docs.sms4sats.com/api-reference/order-states) for the complete state machine.


# Cancel an Order

Cancel an eligible bearer-token order and safely release its held payment.

{% tabs %}
{% tab title="Receive SMS" %} <mark style="color:green;">`POST`</mark> `/v2/receive-sms/orders/{orderId}/cancel`
{% endtab %}

{% tab title="Rent Number" %} <mark style="color:green;">`POST`</mark> `/v2/rent-numbers/orders/{orderId}/cancel`
{% endtab %}
{% endtabs %}

```http
Authorization: Bearer <accessToken>
```

The response is the latest full [order snapshot](https://docs.sms4sats.com/api-reference/get-order), including `countryName`, `countryCallingCode` and `countryIsoCode` beside the unchanged `country`. The new fields are null before allocation; cancellation does not erase country metadata for a retained allocated number.

## Receive-SMS eligibility

* An unpaid order may be cancelled immediately.
* A paid order becomes eligible **three minutes after payment** only after it reaches `waiting_for_sms`.
* Cancellation is rejected during allocation or after any SMS data has been received.
* Use `cancellation.eligible` and `cancellation.availableAt` from the order response.

For an eligible paid order, successful cancellation releases the Lightning hold. If the response is ambiguous or the order remains in a transitional state, poll for its final status before taking further action.

## Rental eligibility

* An unpaid rental may be cancelled.
* Any paid rental is not manually cancellable, including while allocation is still in progress.

## Example

```bash
curl -sS -X POST \
  https://api.sms4sats.com/v2/receive-sms/orders/ORDER_ID/cancel \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

{% hint style="warning" %}
A `409 CANCEL_NOT_AVAILABLE_YET` or `409 ORDER_NOT_CANCELLABLE` is authoritative. Fetch the order again instead of repeatedly submitting cancellation.
{% endhint %}


# Rent Numbers

Rent a temporary number for multiple incoming SMS messages.

Rentals keep a number active for a selected period and can collect multiple messages.

## Workflow

1. Query [`GET /v2/rent-numbers/catalog`](https://docs.sms4sats.com/api-reference/catalog-and-quotes#rental-catalog).
2. Request a live quote.
3. Create an order with a UUID v4 idempotency key.
4. Pay the hold invoice.
5. Poll with the bearer token while status is `rent_active`. The [order snapshot](https://docs.sms4sats.com/api-reference/get-order#country-metadata) includes `countryName`, `countryCallingCode` and `countryIsoCode` beside the unchanged `country`; the three fields are null before allocation.
6. Read every delivered entry from `messages` until the rental completes.

## Create example

```bash
curl -sS -X POST https://api.sms4sats.com/v2/rent-numbers/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 61cc8d9b-2761-48dc-8ac5-e4d3ba20e8c6' \
  -d '{"country":"US","service":"full","durationMinutes":120}'
```

Rental durations are normalized to at least two hours and then upward to a whole hour. The maximum request value is 43,200 minutes.

## Payment and cancellation

A rental hold invoice settles when the number is successfully allocated. The order then enters `rent_active`, includes an end time, and may accumulate multiple messages. Manual cancellation is available only before payment; any paid rental is not manually cancellable.

{% hint style="info" %}
For Lightning-native agents, rentals are also available through the [L402 API](https://docs.sms4sats.com/api-reference/l402). A paid L402 rental has no refund flow, including if allocation fails.
{% endhint %}


# L402 API

Integrate sms4sats with L402 payment challenges, macaroons, and Lightning preimages.

L402 combines a Lightning invoice with a resource-scoped macaroon. It is designed for AI agents and services that can pay invoices and retrieve payment preimages programmatically.

## Discovery

```bash
curl -sS https://api.sms4sats.com/v2/l402
curl -sS https://api.sms4sats.com/v2/l402/services
curl -sS https://api.sms4sats.com/v2/l402/catalog
```

| Endpoint                | Response                                 |
| ----------------------- | ---------------------------------------- |
| `GET /v2/l402/services` | `{ "services": [{ "code", "name" }] }`   |
| `GET /v2/l402/catalog`  | `{ "items": [...], "updatedAt": "..." }` |

The catalog lists receive-SMS and reactivation offers and may be empty. Listed availability is not guaranteed until the order is allocated after payment; a paid receive-SMS allocation failure follows the refund flow.

## Create an order

<mark style="color:green;">`POST`</mark> `/v2/l402/order`

### Order types

{% tabs %}
{% tab title="Receive SMS" %}

```json
{
  "type": "receive-sms",
  "country": "auto",
  "service": "tg",
  "refundInvoice": "lnbc1..."
}
```

`refundInvoice` is required. It must be a valid **no-amount** BOLT11 invoice with at least 30 minutes of validity remaining when the order is created. That is only the validation floor: choose an invoice whose expiry covers payment delay, the full fulfillment timeout, and routing headroom. If it expires before a refund is attempted, the order can end in `refund_failed`.
{% endtab %}

{% tab title="Reactivate" %}

```json
{
  "type": "receive-sms-reactivate",
  "country": "US",
  "service": "tg",
  "refundInvoice": "lnbc1...",
  "reactivationOfActivationId": "123456789"
}
```

`reactivationOfActivationId` is required and may be a string or number. Reactivation uses the same required refund-invoice flow as a one-time receive-SMS order. Availability depends on the original activation ID.
{% endtab %}

{% tab title="Rent Number" %}

```json
{
  "type": "rent-number",
  "country": "US",
  "service": "tg",
  "durationMinutes": 120
}
```

Do not send `refundInvoice` for a rental. Once its L402 invoice is paid, the rental has no refund flow, including if allocation fails.
{% endtab %}
{% endtabs %}

`country` and `service` are required strings of 1–64 characters. Country accepts `auto`, supported numeric country ID, ISO alpha-2 code, or recognized English name. Service accepts a code from `/v2/l402/services` or a recognized name; `other` maps to `ot`. Rental `durationMinutes`, when supplied, must be a positive integer. It defaults to 120 minutes; pricing and allocation use a two-hour minimum and round upward to a whole hour.

{% hint style="warning" %}
A paid L402 rental has no refund path, including if provider allocation fails. Use current discovery data and accept this risk before paying a rental invoice.
{% endhint %}

### Payment challenge

Creation returns HTTP `402 Payment Required` and a `WWW-Authenticate` header.

```json
{
  "error": "PAYMENT_REQUIRED",
  "orderId": "<payment-hash>",
  "priceSats": 1000,
  "invoice": "lnbc...",
  "macaroon": "<serialized-macaroon>",
  "orderStatus": "pending_payment"
}
```

```http
WWW-Authenticate: L402 macaroon="...", invoice="lnbc..."
```

Pay `invoice`, retrieve its 32-byte preimage, and retain all three credentials: `orderId`, `macaroon`, and the preimage. The macaroon carries an `expires_at` caveat (currently 3,600 seconds after creation) and has no refresh route. Polling and cancellation fail with `EXPIRED_MACAROON` after that deadline.

**Rental access limitation:** L402 credentials expire after one hour, before the minimum two-hour rental finishes, and cannot be refreshed. You cannot continue retrieving messages through this API after credential expiry. Prefer the bearer-token rental API for access throughout a rental.

{% hint style="warning" %}
L402 creation does not accept an idempotency key. Do not blindly repeat `POST /v2/l402/order` after an ambiguous network response; each successful creation can issue a separate invoice. Preserve the first successful challenge response and poll its `orderId`.
{% endhint %}

## Authenticate and poll

<mark style="color:blue;">`GET`</mark> `/v2/l402/order/{orderId}`

```bash
curl -sS https://api.sms4sats.com/v2/l402/order/ORDER_ID \
  -H 'Authorization: L402 <serialized-macaroon>:<preimage-hex>'
```

The first valid authenticated request proves payment, marks the order paid, and starts allocation. Poll every 5–10 seconds. The response includes order state, assigned `phoneNumber`, timestamps, and `messages` when available.

```json
{
  "id": "<payment-hash>",
  "type": "receive-sms",
  "country": "85",
  "service": "tg",
  "status": "waiting_for_sms",
  "orderStatus": "waiting_for_sms",
  "fulfillmentStatus": "waiting_for_sms",
  "amountSats": 350,
  "refundAmountSats": null,
  "phoneNumber": "+1...",
  "messages": [],
  "createdAt": "2026-09-30T19:00:00.000Z",
  "updatedAt": "2026-09-30T19:01:10.000Z",
  "paidAt": "2026-09-30T19:01:00.000Z",
  "expiresAt": "2026-09-30T19:21:00.000Z",
  "completedAt": null,
  "refundedAt": null,
  "failedAt": null
}
```

{% hint style="danger" %}
The macaroon and preimage together authorize the order. Treat the complete `Authorization` value as a secret and never log or expose it.
{% endhint %}

## Cancel and refund

<mark style="color:green;">`POST`</mark> `/v2/l402/order/{orderId}/cancel`

Use the same L402 authorization header. Cancellation is available for paid `receive-sms` and `receive-sms-reactivate` orders at least three minutes after payment and before any SMS arrives. Rentals cannot use this cancellation flow. Eligible cancellations refund to the supplied no-amount `refundInvoice`.

Refunds can be slightly lower than `priceSats` because of routing fees.

Orders without an SMS follow the refund flow when they time out. Do not assume a timeout or network error is final—poll the existing order.


# Email Activations

Discover domains, create email activation orders, poll messages, reorder, and cancel safely.

Create a temporary email address for a target site, receive its code or message, and optionally reuse the same assigned address for another activation.

## 1. List available domains

<mark style="color:blue;">`GET`</mark> `/v2/emails/domains?site={hostname}`

`site` is required and must be a valid hostname such as `telegram.com`. Do not include a scheme, path, port, or IP address. Invalid hostnames, including target sites rejected by the provider’s hostname validation, return `400 INVALID_SITE`; they are not server errors.

```bash
curl -sS 'https://api.sms4sats.com/v2/emails/domains?site=telegram.com'
```

```json
{
  "data": [
    { "name": "example.com", "priceSats": 1000 }
  ]
}
```

An empty `data` array means no qualifying domain is currently available.

## 2. Create an order

<mark style="color:green;">`POST`</mark> `/v2/emails`

Both JSON fields are required, trimmed strings of 1–255 characters:

| Field    | Meaning                                                      |
| -------- | ------------------------------------------------------------ |
| `site`   | Valid target hostname, matching the domain-discovery request |
| `domain` | Exact available email domain selected from `data[].name`     |

The protected v2 flow requires `X-SMS4SATS-Email-Capability: v1`. The exact value `v1` tells the server to mint and return an independent bearer capability for the new order.

```bash
curl -sS -X POST https://api.sms4sats.com/v2/emails \
  -H 'Content-Type: application/json' \
  -H 'X-SMS4SATS-Email-Capability: v1' \
  -d '{"site":"telegram.com","domain":"example.com"}'
```

Select a domain returned by discovery. Creation revalidates current provider availability and may return `409 EMAIL_DOMAIN_UNAVAILABLE` if inventory changed.

```json
{
  "status": "OK",
  "orderId": "<payment-hash>",
  "accessToken": "<opaque-token>",
  "payreq": "lnbc...",
  "priceSats": 1000,
  "orderStatus": "pending_payment",
  "fulfillmentType": "new",
  "reorderOfOrderId": null
}
```

Store `accessToken` securely and pay `payreq`.

{% hint style="warning" %}
Email creation and reorder do not accept idempotency keys. Do not blindly repeat either `POST` after an ambiguous network response; a successful retry can issue another invoice. Preserve each successful response and continue with its `orderId`.
{% endhint %}

## 3. Poll the order

<mark style="color:blue;">`GET`</mark> `/v2/emails/{orderId}`

```bash
curl -sS https://api.sms4sats.com/v2/emails/ORDER_ID \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

The snapshot includes `site`, `domain`, `email`, `priceSats`, `status`, `orderStatus`, timestamps, and eventually `code` and/or `message`.

```json
{
  "id": "<payment-hash>",
  "type": "email",
  "site": "telegram.com",
  "domain": "example.com",
  "fulfillmentType": "new",
  "reorderOfOrderId": null,
  "status": "waiting_for_email",
  "orderStatus": "waiting_for_email",
  "email": "assigned@example.com",
  "code": null,
  "message": null,
  "priceSats": 1000,
  "createdAt": "2026-09-30T19:00:00.000Z",
  "updatedAt": "2026-09-30T19:01:10.000Z",
  "paidAt": "2026-09-30T19:01:00.000Z",
  "expiresAt": "2026-09-30T19:21:00.000Z",
  "completedAt": null,
  "cancelledAt": null,
  "failedAt": null
}
```

Poll every 5–10 seconds and stop on `completed`, `cancelled`, `failed`, or `expired`.

## Reorder the same email

<mark style="color:green;">`POST`</mark> `/v2/emails/{orderId}/reorder`

Reorder is available only after the original assigned email has received a code or message. Authenticate with the **original order's** bearer token. The response creates a new order with its own `orderId`, `accessToken`, invoice, and price.

```bash
curl -sS -X POST https://api.sms4sats.com/v2/emails/ORIGINAL_ORDER_ID/reorder \
  -H 'Authorization: Bearer ORIGINAL_ACCESS_TOKEN'
```

## Cancel

<mark style="color:green;">`POST`</mark> `/v2/emails/{orderId}/cancel`

`DELETE /v2/emails/{orderId}` is a server-side alias. Browser clients must use `POST` because the API's CORS policy does not allow `DELETE`. Authenticate with the order's bearer token.

A paid email order becomes cancellable two minutes after payment while no code or message has arrived. Successful manual cancellation confirms the payment release. A completed order cannot be cancelled.

```bash
curl -sS -X POST https://api.sms4sats.com/v2/emails/ORDER_ID/cancel \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

## Email states

```
pending_payment → paid → waiting_for_email → code_received → completed
                                        ↘ cancelled / failed / expired
```

`code_received` is transitional; content fields may not be available yet. Continue polling until `completed`.


# Order States

Interpret sms4sats order lifecycle states and know when to stop polling.

Always use server state as the source of truth. Do not infer order status from elapsed time, payment-wallet UI, or the presence of a phone number alone.

## Bearer-token SMS and rentals

| State                | Meaning                                                      | Client action                                 |
| -------------------- | ------------------------------------------------------------ | --------------------------------------------- |
| `pending_payment`    | Invoice created; payment not accepted                        | Present invoice; allow immediate cancellation |
| `paid`               | Hold accepted                                                | Poll                                          |
| `allocating`         | Provider allocation in progress                              | Poll; do not cancel unless API marks eligible |
| `waiting_for_sms`    | Number assigned, waiting for message                         | Display number; poll                          |
| `code_received`      | Message received; payment confirmation pending               | Preserve message; poll                        |
| `rent_active`        | Rental allocated and active                                  | Display number/messages; poll until end       |
| `settlement_pending` | Fulfillment complete; payment confirmation pending           | Poll; do not create replacement               |
| `release_pending`    | Hold release retrying                                        | Poll; do not create replacement               |
| `expiring`           | Expiry cleanup in progress                                   | Poll                                          |
| `cancelling`         | Cancellation cleanup in progress                             | Poll                                          |
| `completed`          | Fulfilled and finalized                                      | Stop                                          |
| `cancelled`          | User cancellation finalized                                  | Stop                                          |
| `expired`            | Timed out and finalized                                      | Stop                                          |
| `failed`             | Fulfillment failed and payment cleanup completed or recorded | Stop; inspect response/error                  |

## L402 SMS and rentals

The implemented L402 states are `pending_payment`, `paid`, `allocating_number`, `waiting_for_sms`, `rent_active`, `cancel_pending`, `refund_pending`, `refunded`, `refund_failed`, `completed`, and `failed`.

Terminal L402 states are `completed`, `refunded`, `refund_failed`, and `failed`.

## Email

| State               | Meaning                                                |
| ------------------- | ------------------------------------------------------ |
| `pending_payment`   | Hold invoice awaits payment                            |
| `paid`              | Payment accepted; allocation starting                  |
| `waiting_for_email` | Address assigned; waiting for code/message             |
| `code_received`     | Code or message received; payment confirmation pending |
| `completed`         | Delivery and settlement finalized                      |
| `cancelled`         | User cancellation and hold release finalized           |
| `failed`            | Allocation/provider flow failed                        |
| `expired`           | Timed out without delivery                             |

## Robust polling

1. Poll every 5–10 seconds with the same order credential.
2. Use `expiresAt` for display, not as permission to create a duplicate.
3. Continue through transitional payment and cleanup states.
4. Stop only on a documented terminal state.
5. If a request fails transiently, retry polling with exponential backoff and jitter.


# Errors, Limits & Retries

Handle sms4sats API v2 errors, rate limits, authentication failures, and safe retries.

## Error shape

```json
{
  "error": "UNAVAILABLE",
  "message": "No numbers available",
  "requestId": "<request-id>"
}
```

Application errors normally use this shape. Rate-limit middleware may return a plain `429` body instead, so clients must branch on HTTP status before parsing an application error. Include `requestId` when present and contacting support. Messages for server-side `5xx` errors are intentionally generic.

## Common HTTP responses

| HTTP  | Code examples                                                                                                                                                                                                                                                                  | Meaning / action                                                                            |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
| `400` | `INVALID_REQUEST`, `VALIDATION_ERROR`, `INVALID_INPUT`, `INVALID_COUNTRY`, `INVALID_DURATION`, `IDEMPOTENCY_KEY_REQUIRED`, `INVALID_IDEMPOTENCY_KEY`, `MISSING_SITE`, `INVALID_SITE`, `INVALID_REFUND_INVOICE`, `REFUND_INVOICE_EXPIRES_TOO_SOON`, `PROVIDER_REJECTED`         | Correct the request; do not retry unchanged                                                 |
| `401` | `ORDER_TOKEN_REQUIRED`, `EMAIL_ORDER_TOKEN_REQUIRED`, `MISSING_L402_AUTH`, `INVALID_L402_AUTH`, `INVALID_PREIMAGE`, `INVALID_MACAROON`, `EXPIRED_MACAROON`                                                                                                                     | Supply a valid credential/payment proof                                                     |
| `403` | `INVALID_ORDER_TOKEN`, `EMAIL_ORDER_TOKEN_INVALID`, `CORS_NOT_ALLOWED`                                                                                                                                                                                                         | Bearer order capability is invalid, or the browser origin is not allowed                    |
| `404` | `ORDER_NOT_FOUND`, `EMAIL_ORDER_NOT_FOUND`, `NOT_FOUND`                                                                                                                                                                                                                        | Verify API family and order ID                                                              |
| `409` | `UNAVAILABLE`, `IDEMPOTENCY_CONFLICT`, `IDEMPOTENCY_IN_PROGRESS`, `ORDER_NOT_PAID`, `CANCEL_NOT_AVAILABLE_YET`, `CANCEL_NOT_SUPPORTED`, `ORDER_NOT_CANCELLABLE`, `RENTAL_NOT_CANCELLABLE`, `EMAIL_DOMAIN_UNAVAILABLE`, `EMAIL_ALREADY_RECEIVED`, `EMAIL_REORDER_NOT_AVAILABLE` | Read the code; refresh state or choose new inventory as appropriate                         |
| `429` | rate limit                                                                                                                                                                                                                                                                     | Honor rate-limit headers; retry with backoff and jitter                                     |
| `500` | `INTERNAL_ERROR`                                                                                                                                                                                                                                                               | Unexpected server failure; preserve `requestId`, avoid duplicate creation, and retry safely |
| `503` | `PROVIDER_UNAVAILABLE`, `PROVIDER_CANCEL_FAILED`, `PAYMENT_RELEASE_FAILED`, `LNBITS_CANCEL_FAILED`, `REFUND_FAILED`, `INVOICE_RECONCILIATION_REQUIRED`, `INVOICE_HASH_MISMATCH`                                                                                                | Temporary dependency/reconciliation condition; do not assume the order failed               |

## Retry policy

### Safe to retry

* Catalog and quote requests.
* Poll requests using the same credential.
* A bearer-token SMS/rental creation request using the **same body and same idempotency key**.
* A `429` or transient `5xx` after waiting with exponential backoff and jitter, only when the operation is read-only or idempotent.

### Never retry blindly

* Creation with a new idempotency key after a timeout.
* Email or L402 creation after an ambiguous response; those endpoints do not support idempotency keys.
* Payment of a second invoice before resolving the first order.
* Cancellation after a conflict without fetching current state.
* A request rejected for validation or authentication without correcting it.

## Rate limits

* Global: 300 requests per minute per client.
* Bearer-token creation: 60 requests per minute per client.
* Poll no faster than every 5–10 seconds per active order.

## Credential handling

* Redact bearer tokens, order references, macaroons, preimages, refund invoices, and BOLT11 invoices from logs.
* Send credentials in `Authorization` headers, never query parameters.
* Do not persist secrets in browser analytics, crash reports, or support screenshots.
* Use TLS and the exact `https://api.sms4sats.com` origin.


# Send SMS Overview

Send SMS using the original SMS4Sats API contract, with Lightning invoices or a prepaid satoshi balance.

This section is only for **sending SMS**, not receiving verification codes, renting numbers, or email activations.

The send API preserves the legacy endpoint names, `X-API-Key` authentication, satoshi balances, and JSON responses on the canonical API origin:

```
https://api.sms4sats.com
```

## Choose a payment mode

| Mode            | How it works                                                                     | API key                                      |
| --------------- | -------------------------------------------------------------------------------- | -------------------------------------------- |
| Pay per message | Create a send order, pay its Lightning invoice, then poll its status             | Not required unless `immediate` is requested |
| Prepaid         | Top up a balance once, then request `immediate: true` sends against that balance | Required                                     |

Send is a separate legacy-compatible contract. It does **not** use receive-SMS bearer tokens or L402 macaroons. Do not prepend `/v2/receive-sms` to these paths.

## Endpoint overview

| Method | Path                       | Purpose                                                  |
| ------ | -------------------------- | -------------------------------------------------------- |
| `POST` | `/fund`                    | Create a Lightning invoice to top up an API-key balance  |
| `GET`  | `/balance`                 | Read the balance in satoshis                             |
| `GET`  | `/history`                 | Read paid funding history                                |
| `POST` | `/createsendorder`         | Create a send order, paid by invoice or existing balance |
| `GET`  | `/orderstatus?orderId=...` | Read payment and SMS-send status                         |

Start with [Top up & balances](https://docs.sms4sats.com/send-sms/top-up), then [Send a message & track delivery](https://docs.sms4sats.com/send-sms/send).

## API-key handling

For existing integrations, reuse your original `X-API-Key`: the send account remains associated with that key and its original balance records. There is no conversion to a new receive-SMS account.

For a new integration, choose a cryptographically random secret identifier, such as a UUID. Keep it private: possession of the key authorizes spending its prepaid balance. Send it only as the `X-API-Key` header, never in a public URL.

Keys must be nonempty, have no surrounding whitespace, be at most 256 UTF-8 bytes, and exclude these characters (`.`, `#`, `$`, `[`, `]`, `/`, `\`) and control characters.

{% hint style="warning" %}
Send only to recipients who consented to receive your messages. Existing anti-spam checks remain in place. An accepted API request is not proof of handset delivery; poll the order status.
{% endhint %}


# Top Up & Balances

Fund an SMS4Sats send-SMS account with Lightning and check its prepaid satoshi balance.

All amounts are **satoshis**, not millisatoshis, dollars, or BTC decimals. Use the same secret `X-API-Key` for funding, balance checks, history, and prepaid sending.

## 1. Create a top-up invoice

```bash
curl -sS -X POST 'https://api.sms4sats.com/fund' \
  -H 'Content-Type: application/json' \
  -H 'X-API-Key: YOUR_SECRET_API_KEY' \
  --data '{"amount":3000}'
```

`amount` must be a positive safe integer. A digits-only string is also accepted for compatibility. A successful response has the original shape:

```json
{
  "status": "OK",
  "orderId": "<order-id>",
  "payreq": "<bolt11-invoice>"
}
```

This creates an invoice; it does **not** credit your balance yet.

## 2. Pay the invoice

Pay the returned `payreq` using a Lightning wallet that supports hold invoices. Your prepaid balance becomes available after the payment is confirmed. Check `/balance` before sending.

Keep the returned `orderId`. You can poll:

```bash
curl -sS 'https://api.sms4sats.com/orderstatus?orderId=ORDER_ID'
```

The returned `paid` flag describes the order's recorded payment state. **Confirm the balance increase before sending against it.** Invoice creation, or payment being held, is not by itself proof of available credit.

## 3. Check your balance

```bash
curl -sS 'https://api.sms4sats.com/balance' \
  -H 'X-API-Key: YOUR_SECRET_API_KEY'
```

```json
{"status":"OK","balance":3000}
```

The numeric value above is an example. An account without an existing balance returns zero. Existing legacy keys continue reading their existing balances; no re-registration is required.

## Funding history

```bash
curl -sS 'https://api.sms4sats.com/history' \
  -H 'X-API-Key: YOUR_SECRET_API_KEY'
```

The legacy response is:

```json
{
  "status": "OK",
  "orders": [],
  "totalAmount": 0
}
```

`orders` contains paid funding/account history for your API key. For compatibility, `totalAmount` may be a number or string and is **not** your current spendable balance. Use `/balance` for available credit.

## Common errors

| HTTP status | `reason`                       | Meaning                                           |
| ----------- | ------------------------------ | ------------------------------------------------- |
| `400`       | `X-API-Key header is missing.` | Supply the header                                 |
| `400`       | `X-API-Key header is invalid.` | The key does not meet the legacy key rules        |
| `400`       | `amount is required.`          | Missing or invalid top-up amount                  |
| `500`       | `backend error`                | Invoice backend returned an unsuccessful response |
| `500`       | `backend invoice error`        | Invoice initialization failed                     |
| `500`       | `unable to save data`          | Order persistence failed                          |
| `500`       | `unable to create invoice`     | No usable invoice was returned                    |
| `500`       | `server error`                 | Balance lookup failed (`/balance`)                |
| `500`       | Exception message              | Funding history lookup failed (`/history`)        |

A network timeout is ambiguous: do not assume the original request was never processed. Preserve any returned order ID and reconcile its payment/balance before creating another top-up.


# Send a Message & Track Delivery

Send an SMS with the legacy-compatible API and poll its delivery status.

## Request fields

`POST https://api.sms4sats.com/createsendorder`

| Field        | Type    | Required | Meaning                                                                                                         |
| ------------ | ------- | -------- | --------------------------------------------------------------------------------------------------------------- |
| `phone`      | string  | Yes      | Recipient number in international format, including country code; E.164 with `+` is recommended                 |
| `message`    | string  | Yes      | Nonempty SMS text, at most **140 UTF-16 code units** (some characters, including many emoji, consume two)       |
| `immediate`  | boolean | No       | Set to `true` to spend the balance belonging to `X-API-Key`; omit or use `false` to receive a Lightning invoice |
| `webhookUrl` | string  | No       | Publicly reachable HTTPS URL for SMS-status updates                                                             |

The limit applies to UTF-16 code units, not SMS segments. Invalid numbers and messages rejected by anti-spam checks cannot be sent. The API determines the price; caller-supplied price fields do not override it.

## Option A: pay per message

```bash
curl -sS -X POST 'https://api.sms4sats.com/createsendorder' \
  -H 'Content-Type: application/json' \
  --data '{"phone":"+12025550123","message":"Your requested notification."}'
```

The number is an example; replace it with your own consenting recipient.

```json
{
  "status": "OK",
  "orderId": "<order-id>",
  "payreq": "<bolt11-invoice>"
}
```

Pay the amount specified in `payreq`, then poll `/orderstatus`. The returned invoice is authoritative.

## Option B: prepaid immediate sending

First [top up and confirm your balance](https://docs.sms4sats.com/send-sms/top-up).

```bash
curl -sS -X POST 'https://api.sms4sats.com/createsendorder' \
  -H 'Content-Type: application/json' \
  -H 'X-API-Key: YOUR_SECRET_API_KEY' \
  --data '{"phone":"+12025550123","message":"Your requested notification.","immediate":true}'
```

```json
{
  "status": "OK",
  "orderId": "<order-id>",
  "payreq": "paid"
}
```

`payreq: "paid"` means this order uses the prepaid flow; there is no second invoice to pay. Recheck `/balance` for the resulting debit.

Do not blindly retry a timed-out send: it may already have reached the provider. The legacy send contract has no caller-provided idempotency key. Preserve order IDs and reconcile status before retrying.

## Poll send status

Polling requires **no API key**: possession of the order ID permits lookup. Treat order IDs as private. Use the exact order ID returned by the API; do not construct one yourself.

Invalid input, a missing order, or a lookup exception returns HTTP **400** with `{ "status": "error", "reason": "..." }`:

| `reason`                    | Meaning                  |
| --------------------------- | ------------------------ |
| `valid orderId is required` | Missing or invalid ID    |
| `order does not exist`      | No matching stored order |
| `server error`              | Status lookup failed     |

```bash
curl -sS 'https://api.sms4sats.com/orderstatus?orderId=ORDER_ID'
```

Example after the provider has created the SMS:

```json
{
  "status": "OK",
  "paid": true,
  "smsStatus": "created",
  "timestamp": 1700000000000
}
```

Fields vary with the order's state. Delivery updates can change `smsStatus` to values such as `sent`, `delivered`, or `undelivered`. A send failure can expose an `error` field.

**Important:** `status: "OK"`, `paid: true`, or `payreq: "paid"` alone does not prove delivery. Read `smsStatus` and `error`. The inherited send flow can record a provider error even when the create response is `OK`; do not treat that as a new retry authorization.

If you supplied `webhookUrl`, delivery-status updates use the same public status shape. Your handler should return promptly and tolerate repeated updates. Use `/orderstatus` to confirm payment and delivery state; receiving a notification alone is not payment confirmation.

## Common errors

| HTTP status | `reason`                                                                 |
| ----------- | ------------------------------------------------------------------------ |
| `400`       | `missing x-api-key header` when requesting prepaid sending without a key |
| `400`       | `invalid x-api-key header`                                               |
| `500`       | `missing required parameters`                                            |
| `500`       | `message can not be longer than 140 characters`                          |
| `500`       | `phone number validation failed`                                         |
| `500`       | `message rejected as spam`                                               |
| `500`       | `spam detection failed, please try again later.`                         |
| `500`       | `Not enough balance.`                                                    |
| `500`       | `Failed to create order. Try again later.`                               |
| `500`       | `backend error` (invoice mode)                                           |
| `500`       | `backend invoice error` (invoice mode)                                   |
| `500`       | `unable to save data` (invoice mode)                                     |
| `500`       | `unable to create invoice` (invoice mode)                                |

The status codes and wording above intentionally retain the legacy contract, including its `500` validation responses.


