# ABM SMS Gateway — API Reference

English reference for `/api/v1`. See [SPEC.md](SPEC.md) for the full internal design spec this is derived from; this document is the external-facing subset a client integration actually needs. Bangla quick-start: [api.bn.md](api.bn.md). PHP SDK: [../sdk/README.md](../sdk/README.md). Postman collection: [postman/abmsms.postman_collection.json](postman/abmsms.postman_collection.json).

**DoD this document exists to satisfy:** a CI3 app integrates in under 15 minutes using only these docs (SPEC §13 Phase 10).

## 1. Base URL

```
https://sms.nextmotogear.com/api/v1
```

(Local development: `http://localhost:8095/api/v1`.)

## 2. Authentication

Every endpoint below accepts either mode, on the same URL. Pick Bearer unless you have a specific reason for HMAC (a higher-value integration, or a security policy that requires request signing).

### Mode A — Bearer (default, simplest)

```
Authorization: Bearer abmsms_live_xxxxxxxx.YOUR_SECRET
Content-Type: application/json
```

Combine with HTTPS in production, and an IP whitelist if your credential supports one (set in the tenant portal's API Credentials screen).

### Mode B — HMAC-SHA256 signed (higher-value tenants)

```
X-Api-Key:    abmsms_live_xxxxxxxx
X-Timestamp:  1755400000                                (unix seconds)
X-Nonce:      32-char random hex
X-Signature:  hex hmac_sha256(api_secret, "{METHOD}\n{path}\n{timestamp}\n{nonce}\n{sha256(raw_body)}")
```

- `{METHOD}` is upper-case (`GET`, `POST`).
- `{path}` is the request path only, no query string, no host (e.g. `/api/v1/sms/send`, not `sms/send` or the full URL).
- `{sha256(raw_body)}` is the hex SHA-256 of the exact raw request body bytes - `""` (empty string) for a GET with no body, hashed the same way.
- Timestamp must be within ±300s of server time; nonce must not have been seen in the last 600s (replay protection); signature is compared with a constant-time comparison.
- Distinct error codes for each failure reason (`SIG_INVALID`, `TIMESTAMP_SKEW`, `NONCE_REPLAY`) so you're never left guessing which part is wrong.

The [Postman collection](postman/abmsms.postman_collection.json)'s "HMAC Auth" folder computes all four headers for you via a pre-request script - copy that JavaScript if you're implementing your own signing.

### Rate limits

Per credential, sliding window: 60 requests/min and 10,000 recipients/min by default (your credential may have a custom limit). A breach returns `429` with a `Retry-After` header and `RATE_LIMITED`.

## 3. Response envelope

Every response is JSON with the same shape:

```json
{
  "success": true,
  "request_id": "0f3c1a2b-...",
  "client_id": 25,
  "data": { }
}
```

```json
{
  "success": false,
  "request_id": "0f3c1a2b-...",
  "client_id": 25,
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Balance 12.50 BDT is below required 45.00 BDT",
    "details": { "required": 45.0, "available": 12.5 }
  }
}
```

`request_id` is logged server-side against every request - include it in any support ticket, it makes tracing the exact request trivial.

`client_id` is your own tenant account number (stable for the lifetime of your account) - it's on every response so your own systems can match a response back to a client without parsing anything else out of the payload. It's `null` only on the handful of pre-auth errors (`AUTH_REQUIRED`, `INVALID_CREDENTIALS`, etc.) where the request never got far enough to identify who's calling. Don't confuse it with `client_reference` (§4) - that's a free-text tag *you* choose per message, this is a fixed number *we* assign per account.

### Error codes

| HTTP | Code | Meaning |
|---|---|---|
| 400 | `VALIDATION_ERROR` | Request body failed validation - see `error.details` for the field(s). |
| 400 | `INVALID_NUMBER` | A phone number didn't normalize (SPEC §2.1 - Bangladeshi mobile formats only). |
| 401 | `AUTH_REQUIRED` | No credentials supplied at all. |
| 401 | `INVALID_CREDENTIALS` | Unknown API key, or a Bearer secret that doesn't match. |
| 401 | `CREDENTIAL_REVOKED` | The credential exists but has been revoked. |
| 401 | `SIG_INVALID` | HMAC signature didn't verify. |
| 401 | `TIMESTAMP_SKEW` | HMAC `X-Timestamp` is more than 300s from server time. |
| 401 | `NONCE_REPLAY` | HMAC `X-Nonce` was already used in the last 600s. |
| 402 | `INSUFFICIENT_BALANCE` | Balance + credit limit can't cover the request. `details.required`/`details.available` tell you by how much. |
| 403 | `IP_NOT_WHITELISTED` | Caller's IP isn't in this credential's whitelist. |
| 403 | `SCOPE_FORBIDDEN` | Credential doesn't have the scope this endpoint needs (`send`/`report`/`balance`). |
| 403 | `TENANT_SUSPENDED` | Your account has been suspended - contact ABM Soft. |
| 403 | `SENDER_ID_NOT_AUTHORIZED` | The `sender_id` you asked for isn't approved for your account yet. |
| 404 | `NOT_FOUND` | The resource doesn't exist, or belongs to another tenant (SPEC §12: cross-tenant access is always a 404, never a leak - if you're sure something should exist and get this, double-check you're using the right credential). |
| 409 | `IDEMPOTENCY_CONFLICT` | You reused an `Idempotency-Key` with a *different* request body than the first time. |
| 422 | `NO_RATE_CONFIGURED` | No price is configured for this route/encoding combination - contact ABM Soft. |
| 422 | `BUSINESS_RULE_VIOLATION` | A business rule blocked the request (see `error.message`). |
| 429 | `RATE_LIMITED` | Slow down - see the `Retry-After` header. |
| 502 | `PROVIDER_FAILURE` | Every candidate upstream provider is currently down. Retry later; nothing was charged. |
| 503 | `NO_ROUTE_AVAILABLE` | No provider route is configured/healthy for this recipient right now. |
| 500 | `INTERNAL_ERROR` | Something broke on our end - include the `request_id` when you report it. |

## 4. Sending SMS

### `POST /sms/send` — up to 100 recipients, one shared message

```json
{
  "to": ["01712345678", "01812345678"],
  "message": "আপনার বাইকের সার্ভিস ডিউ ২০ আগস্ট।",
  "sender_id": "ABM-BIKE",
  "client_reference": "SVC-4471",
  "schedule_at": null
}
```

- `to`: a single number or an array of up to 100. Any Bangladeshi mobile format normalizes automatically (SPEC §2.1) - `01712345678`, `+8801712345678`, `8801712345678` are all accepted.
- `sender_id`: omit for the platform default (non-masking, always available). A masking (branded) sender ID needs prior approval - request one from the tenant portal.
- `schedule_at`: ISO 8601 datetime, or `null` to send immediately.
- `client_reference`: your own ID for this message (e.g. an invoice/service ticket number) - comes back on every status lookup, so you can look up "the SMS for invoice 4471" without storing our `message_uuid` yourself if you don't want to.
- Header `Idempotency-Key` (any string) is honoured: replay the same key within 24h and you get back the *original* response, no second send, no second charge. Use a UUID generated per logical send, not per HTTP attempt - that's exactly what makes a retried request safe after a timeout where you don't know if the first attempt actually landed.

Response (`202`):

```json
{
  "success": true,
  "data": {
    "batch_uuid": "34df4236-...",
    "encoding": "gsm7",
    "part_count": 1,
    "total_cost": 0.40,
    "balance_after": 1204.10,
    "messages": [
      { "message_uuid": "ae8f6251-...", "to": "8801712345678", "status": "queued", "cost": 0.20 },
      { "message_uuid": "1e0230e5-...", "to": "8801812345678", "status": "queued", "cost": 0.20 }
    ]
  }
}
```

`status` here is the state right after accepting the request (usually `queued`, or `blacklisted`/`rejected` for a recipient that couldn't be included) - actual delivery happens asynchronously; poll `status()`/`bulk_status()` or set up a webhook to find out what happened next.

### `POST /sms/bulk` — up to 50,000 recipients, personalized

```json
{
  "name": "Eid Offer Aug 2026",
  "sender_id": "ABM-BIKE",
  "messages": [
    { "to": "01712345678", "message": "প্রিয় করিম সাহেব, ...", "client_reference": "C-101" },
    { "to": "01812345678", "message": "প্রিয় রহিম সাহেব, ...", "client_reference": "C-102" }
  ],
  "schedule_at": null,
  "allow_partial": false
}
```

If the balance can't cover the *whole* batch, the whole batch is rejected (`402 INSUFFICIENT_BALANCE`) and nothing is charged - unless `"allow_partial": true`, in which case as many recipients as fit the balance are sent (in submission order) and the rest come back with `"status": "rejected"` in the response, no partial charge for the ones that didn't fit.

Response shape matches `/sms/send`'s, plus `"status"` at the top level (`pending`/`partial`/etc. - the batch's own overall state).

### `POST /sms/estimate` — dry run, no charge

Identical payload to `/sms/send` (or `/sms/bulk`'s `messages` shape). Returns exactly what sending would cost without sending or charging anything:

```json
{
  "success": true,
  "data": {
    "encoding": "gsm7",
    "route_type": "non_masking",
    "char_count": 22,
    "part_count": 1,
    "recipients": 1,
    "rate_per_part": 0.20,
    "cost_per_recipient": 0.20,
    "total_cost": 0.20,
    "balance": 1249.40,
    "credit_limit": 0,
    "sufficient_balance": true
  }
}
```

Call this from your own UI before the user hits send - it's what eliminates most "why didn't my message go through" support tickets. A single non-GSM-7 character (most Bangla text, emoji, etc.) forces the whole message to UCS-2 encoding, which fits fewer characters per part (67 vs 153) - `estimate()` is the only reliable way to know the real part count/cost before sending.

## 5. Status & history

### `GET /sms/{message_uuid}` — one message, full detail

```json
{
  "success": true,
  "data": {
    "message_uuid": "ae8f6251-...",
    "client_reference": "SVC-4471",
    "to": "8801712345678",
    "operator": "grameenphone",
    "sender_id": "ABM-BIKE",
    "route_type": "non_masking",
    "message": "...",
    "encoding": "gsm7",
    "char_count": 19,
    "part_count": 1,
    "cost": 0.20,
    "status": "delivered",
    "provider_message_id": "...",
    "error_code": null,
    "error_message": null,
    "created_at": "2026-08-18T04:53:12+00:00",
    "submitted_at": "2026-08-18T04:53:13+00:00",
    "delivered_at": "2026-08-18T04:53:20+00:00"
  }
}
```

`status` is one of `queued`, `submitted`, `sent`, `delivered`, `failed`, `rejected`, `expired`, `blacklisted`.

### `POST /sms/status` — bulk status lookup, max 500

This is what a cron job should poll if you can't receive [outbound webhooks](#6-outbound-webhooks-we-call-you) at all - never poll `GET /sms/{uuid}` in a loop for a batch, use this instead.

```json
{ "message_uuids": ["ae8f6251-...", "1e0230e5-..."] }
```

or

```json
{ "client_references": ["SVC-4471", "SVC-4472"] }
```

Response: `{"data": {"messages": [ /* same shape as GET /sms/{uuid}, one per match */ ]}}`. An identifier that doesn't match anything is simply omitted from the response, not an error.

## 6. Outbound webhooks (we call you)

Set up an endpoint in the tenant portal's Webhooks screen (URL + which events you want: `message.delivered`, `message.failed`), and ABM SMS Gateway calls it as each of your messages resolves:

```
POST <your url>
Content-Type: application/json
X-Abm-Signature:   hex hmac_sha256(endpoint_secret, raw_body)
X-Abm-Event:       message.delivered
X-Abm-Delivery-Id: <uuid, stable across retries of this same event>

{
  "event": "message.delivered",
  "delivery_id": "...",
  "created_at": "2026-08-18T04:53:20+00:00",
  "data": {
    "message_uuid": "ae8f6251-...",
    "client_reference": "SVC-4471",
    "to": "8801712345678",
    "sender_id": "ABM-BIKE",
    "status": "delivered",
    "cost": 0.20,
    "delivered_at": "2026-08-18T04:53:20+00:00"
  }
}
```

**Verify the signature before trusting anything in the body** - `endpoint_secret` is shown once when you create the endpoint. The PHP SDK does this in one call:

```php
if (! AbmSms::verifyWebhook($rawBody, $signatureHeader, $endpointSecret)) {
    http_response_code(401);
    exit;
}
```

Return any `2xx` within 10 seconds or the delivery counts as failed. Failed deliveries retry with backoff (1m, 5m, 15m, 1h, 6h - 6 attempts total), after which the endpoint is marked degraded in the portal (it recovers automatically the next time a delivery to it succeeds - nothing you need to do). `X-Abm-Delivery-Id` is stable across every retry of one event, so dedupe on it if your handler isn't naturally idempotent.

## 7. Account & reporting

### `GET /account/balance`

```json
{ "data": { "balance": 1249.40, "credit_limit": 0, "available": 1249.40, "currency": "BDT", "plan_name": "Standard", "rates": [ /* per route_type/encoding */ ] } }
```

### `GET /account/ledger?from=&to=`

Paginated ledger entries (`topup`/`reserve`/`charge`/`refund`/`adjustment`/`reversal`) - every balance movement, in order, with a running balance. `from`/`to` are `YYYY-MM-DD`, both optional.

### `GET /sender-ids`

Your sender IDs and their approval status (`pending`/`approved`/`rejected`).

### `GET /reports/messages?from=&to=&status=&sender_id=&search=&page=&per_page=`

Paginated message list with the same filters as the tenant portal's Message History screen. `per_page` max 500. Response includes a `pagination` object (`page`, `per_page`, `total`, `total_pages`).

### `GET /reports/summary?from=&to=&group_by=day|sender_id|status`

Aggregated counts and cost, grouped however you ask. Backed by a pre-aggregated rollup table, not a live scan - stays fast (well under 300ms) regardless of how much history you have.

### `GET /reports/export?from=&to=&format=csv`

Queues an export job and returns a `download_token` immediately - **never streams rows synchronously**, so don't expect a CSV body back from this call itself.

```json
{ "data": { "download_token": "b7e1...", "status": "pending" } }
```

Poll `GET /reports/export/{download_token}` until `"status": "completed"` (typically a few seconds), which includes a `download_url`; `GET /reports/export/{download_token}/download` streams the actual file. The download link expires after 48 hours.

## 8. PHP SDK

For any PHP integration (CI3 or otherwise), use [`sdk/AbmSms.php`](../sdk/AbmSms.php) instead of hand-rolling HTTP calls - it's a single dependency-free file (PHP 7.2+, cURL only) that already handles signing, retries, and error parsing for every endpoint above. See [`sdk/README.md`](../sdk/README.md) and the CI3 integration example under [`sdk/examples/ci3/`](../sdk/examples/ci3/).

## 9. Bangladesh-specific notes

- **Phone numbers**: any of `01XXXXXXXXX`, `1XXXXXXXXX`, `8801XXXXXXXXX`, `+8801XXXXXXXXX` are accepted and normalize to `8801XXXXXXXXX`. The operator (Grameenphone/Banglalink/Teletalk/Airtel/Robi) is derived from the prefix automatically - you never need to specify it.
- **Encoding**: plain ASCII/GSM-7 text fits 160 characters in one part (153 if it needs more than one part); Bangla text (or any non-GSM-7 character - emoji included) forces UCS-2 encoding, which fits only 70 characters per part (67 if more than one part). `estimate()` always tells you the real `part_count` for your actual message text - never assume based on character count alone.
- **Masking vs non-masking**: non-masking (numeric/shortcode sender) is always available with no setup. Masking (a branded sender ID like `ABM-BIKE`) needs a one-time approval - request it from the tenant portal's Sender IDs screen; ABM Soft reviews and approves/rejects it.
