# Polish, optimize to 160 characters & localize SMS copy
URL: /docs/api-reference/ai-copy-assistant/polishSmsCopy
## POST `/api/v1/public/ai-copy/polish`
**Summary:** Polish, optimize to 160 characters & localize SMS copy
**Operation ID:** `polishSmsCopy`
Uses AI to trim marketing or transactional copy down to fit within a single 160-character GSM-7 segment, optimize tone, or localize into African languages.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"prompt"
],
"properties": {
"prompt": {
"type": "string",
"example": "Hello our esteemed customer, we are pleased to inform you that our annual clearance mega sale has begun today with up to 50% discount on all items."
},
"mode": {
"type": "string",
"enum": [
"FIT_TO_160",
"URGENT_MARKETING",
"PROFESSIONAL_FORMAL",
"WARM_CELEBRATORY",
"LOCALIZE_PIDGIN",
"LOCALIZE_FRENCH",
"LOCALIZE_TWI",
"LOCALIZE_YORUBA",
"GSM7_CLEANSE"
],
"default": "FIT_TO_160"
}
}
}
```
### Responses
- **`200`**: Polished text with character count and savings
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"polishedText": {
"type": "string",
"example": "Mega Sale is live! Enjoy up to 50% off all items today only. Shop now: bit.ly/sale26"
},
"originalLength": {
"type": "integer",
"example": 164
},
"polishedLength": {
"type": "integer",
"example": 83
},
"segments": {
"type": "integer",
"example": 1
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Check balance (POST alias)
URL: /docs/api-reference/authentication-balance/checkBalancePost
## POST `/api/v1/public/sms/balance`
**Summary:** Check balance (POST alias)
**Operation ID:** `checkBalancePost`
Alternative POST endpoint for querying wallet and credit balances in restricted enterprise network environments.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: Current account balance details
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"balance": {
"type": "number",
"example": 250,
"description": "Monetary PAYG wallet cash balance"
},
"smsUnits": {
"type": "integer",
"example": 1000,
"description": "Prepaid SMS unit credits remaining"
},
"currency": {
"type": "string",
"example": "GHS",
"description": "Account settlement currency"
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`403`**: API key lacks required scope (e.g. sms:send, mfa:write, balance:read)
---
# Check SMS unit and wallet balance
URL: /docs/api-reference/authentication-balance/getBalance
## GET `/api/v1/public/sms/balance`
**Summary:** Check SMS unit and wallet balance
**Operation ID:** `getBalance`
Retrieves the authenticated user's current SMS credit balance, pay-as-you-go (PAYG) monetary cash balance, and active account currency.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: Current account balance details
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"balance": {
"type": "number",
"example": 250,
"description": "Monetary PAYG wallet cash balance"
},
"smsUnits": {
"type": "integer",
"example": 1000,
"description": "Prepaid SMS unit credits remaining"
},
"currency": {
"type": "string",
"example": "GHS",
"description": "Account settlement currency"
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`403`**: API key lacks required scope (e.g. sms:send, mfa:write, balance:read)
---
# Get aggregate birthday statistics
URL: /docs/api-reference/birthdays-milestones/getBirthdayStats
## GET `/api/v1/public/birthdays/stats`
**Summary:** Get aggregate birthday statistics
**Operation ID:** `getBirthdayStats`
Returns upcoming birthday counts for the current week and month, and active celebration template status.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: Birthday counts and active automation status
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"thisWeek": {
"type": "integer",
"example": 8
},
"thisMonth": {
"type": "integer",
"example": 34
},
"automationActive": {
"type": "boolean",
"example": true
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Sync contact birthday & optionally greet immediately
URL: /docs/api-reference/birthdays-milestones/syncContactBirthday
## POST `/api/v1/public/birthdays/sync`
**Summary:** Sync contact birthday & optionally greet immediately
**Operation ID:** `syncContactBirthday`
Saves contact date of birth for automated celebration alerts and optionally dispatches an immediate greeting SMS.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"name": {
"type": "string",
"example": "Kwame Mensah"
},
"birthDate": {
"type": "string",
"format": "date",
"example": "1994-06-15"
},
"sendGreetImmediately": {
"type": "boolean",
"default": false
}
}
}
```
### Responses
- **`200`**: Contact birthday synced or greeting dispatched
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Contact birthday synced"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Cancel pending bulk SMS job
URL: /docs/api-reference/bulk-campaign-messaging/cancelBulkJob
## PATCH `/api/v1/public/sms/bulk/jobs/{jobId}`
**Summary:** Cancel pending bulk SMS job
**Operation ID:** `cancelBulkJob`
Aborts a bulk job if it is currently in QUEUED or SCHEDULED status. Unconsumed units are refunded to the customer wallet.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `jobId` | `path` | Yes | Job ID to cancel |
### Responses
- **`200`**: Bulk job successfully cancelled and credits refunded
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Bulk job cancelled successfully"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`422`**: Validation error or invalid input parameters
---
# Cancel scheduled message
URL: /docs/api-reference/bulk-campaign-messaging/cancelScheduledMessage
## PATCH `/api/v1/public/sms/scheduled/{id}`
**Summary:** Cancel scheduled message
**Operation ID:** `cancelScheduledMessage`
Cancels a pending scheduled message before its dispatch time. Reserved credits are refunded immediately.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | Scheduled message ID |
### Responses
- **`200`**: Scheduled message cancelled successfully
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Scheduled message cancelled"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# Get bulk job progress & metrics
URL: /docs/api-reference/bulk-campaign-messaging/getBulkJobProgress
## GET `/api/v1/public/sms/bulk/jobs/{batchId}`
**Summary:** Get bulk job progress & metrics
**Operation ID:** `getBulkJobProgress`
Polls real-time progress for a bulk broadcast batch, including percentage completed, sent count, failed count, and execution timestamps.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `batchId` | `path` | Yes | Batch ID of the bulk broadcast |
### Responses
- **`200`**: Real-time bulk job progress and telemetry
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/BulkSmsProgressDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# List bulk SMS jobs
URL: /docs/api-reference/bulk-campaign-messaging/listBulkJobs
## GET `/api/v1/public/sms/bulk/jobs`
**Summary:** List bulk SMS jobs
**Operation ID:** `listBulkJobs`
Returns a paginated list of bulk broadcast campaigns created by the API key owner.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `page` | `query` | No | |
| `pageSize` | `query` | No | |
### Responses
- **`200`**: List of bulk jobs with execution metrics
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/BulkSmsProgressDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# List SMS campaigns
URL: /docs/api-reference/bulk-campaign-messaging/listCampaigns
## GET `/api/v1/public/sms/campaigns`
**Summary:** List SMS campaigns
**Operation ID:** `listCampaigns`
Retrieves high-level campaign summaries with recipient totals and completion percentages.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: List of active and historical campaigns
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/BulkCampaignDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# List upcoming scheduled messages
URL: /docs/api-reference/bulk-campaign-messaging/listScheduledMessages
## GET `/api/v1/public/sms/scheduled`
**Summary:** List upcoming scheduled messages
**Operation ID:** `listScheduledMessages`
Retrieves pending messages scheduled to be dispatched at a future timestamp.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: List of pending scheduled messages
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ScheduledSmsDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Search bulk SMS jobs
URL: /docs/api-reference/bulk-campaign-messaging/searchBulkJobs
## GET `/api/v1/public/sms/bulk/jobs/search`
**Summary:** Search bulk SMS jobs
**Operation ID:** `searchBulkJobs`
Filters bulk jobs by job name, status, or date range.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `q` | `query` | No | Search job title |
| `status` | `query` | No | |
| `page` | `query` | No | |
| `pageSize` | `query` | No | |
### Responses
- **`200`**: Filtered bulk jobs
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/BulkSmsProgressDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Submit asynchronous bulk SMS job
URL: /docs/api-reference/bulk-campaign-messaging/submitBulkJob
## POST `/api/v1/public/sms/bulk/jobs`
**Summary:** Submit asynchronous bulk SMS job
**Operation ID:** `submitBulkJob`
Submits a bulk campaign for asynchronous processing. Recipients can be supplied as an inline array of phone numbers or pre-uploaded via file. Unit credits are reserved upfront and unconsumed units are refunded if cancelled prior to dispatch.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"message"
],
"properties": {
"jobName": {
"type": "string",
"example": "November Promo Campaign"
},
"message": {
"type": "string",
"example": "Special offer! Use code PROMO50 today."
},
"senderId": {
"type": "string",
"maxLength": 11,
"example": "SMSPRO"
},
"recipients": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"+233241234567",
"+233501234567"
]
},
"fileId": {
"type": "string",
"format": "uuid",
"description": "Pre-uploaded CSV or Excel file ID"
},
"scheduledAt": {
"type": "string",
"format": "date-time"
},
"deliveryCallbackUrl": {
"type": "string",
"format": "uri"
}
}
}
```
### Responses
- **`202`**: Bulk job queued for asynchronous dispatch
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Bulk job queued"
},
"data": {
"type": "object",
"properties": {
"batchId": {
"type": "string",
"example": "batch-7f9a2e41-0023"
},
"jobName": {
"type": "string",
"example": "November Promo Campaign"
},
"recipientCount": {
"type": "integer",
"example": 2500
},
"status": {
"type": "string",
"example": "QUEUED"
},
"totalUnits": {
"type": "integer",
"example": 2500
}
}
}
}
}
```
- **`400`**: Invalid or malformed request syntax
- **`401`**: Authentication failed or API key missing
- **`422`**: Validation error or invalid input parameters
---
# Validate message compliance & character segments
URL: /docs/api-reference/compliance-validation/validateCompliance
## GET `/api/v1/public/sms/validate`
**Summary:** Validate message compliance & character segments
**Operation ID:** `validateCompliance`
Evaluates recipient format, detects GSM-7 vs. UCS-2 Unicode characters, computes billable segment counts, and verifies anti-spam opt-out compliance.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `to` | `query` | Yes | Recipient MSISDN |
| `message` | `query` | Yes | SMS text body |
### Responses
- **`200`**: Compliance validation outcome
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ValidateComplianceDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Validate message compliance (POST alias)
URL: /docs/api-reference/compliance-validation/validateCompliancePost
## POST `/api/v1/public/sms/validate`
**Summary:** Validate message compliance (POST alias)
**Operation ID:** `validateCompliancePost`
Validates message encoding and segments using a POST body.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"to",
"message"
],
"properties": {
"to": {
"type": "string",
"example": "+233241234567"
},
"message": {
"type": "string",
"example": "Special Promo: 50% off today!"
}
}
}
```
### Responses
- **`200`**: Compliance validation outcome
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ValidateComplianceDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Batch validate & normalize phone numbers
URL: /docs/api-reference/compliance-validation/validateRecipients
## POST `/api/v1/public/sms/validate-recipients`
**Summary:** Batch validate & normalize phone numbers
**Operation ID:** `validateRecipients`
Normalizes local and international numbers to standard E.164 format, filters out invalid formats, detects country and carrier prefixes, and deduplicates inputs.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"recipients"
],
"properties": {
"recipients": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"0241234567",
"+233501234567",
"invalid-phone",
"0241234567"
]
}
}
}
```
### Responses
- **`200`**: Validation and normalization summary
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"validCount": {
"type": "integer",
"example": 2
},
"invalidCount": {
"type": "integer",
"example": 1
},
"duplicateCount": {
"type": "integer",
"example": 1
},
"validRecipients": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"+233241234567",
"+233501234567"
]
},
"invalidRecipients": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"invalid-phone"
]
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Download OpenAPI 3.1 Specification
URL: /docs/api-reference/developer-tools-spec/getOpenApiSpec
## GET `/api/v1/public/sms/openapi.json`
**Summary:** Download OpenAPI 3.1 Specification
**Operation ID:** `getOpenApiSpec`
Returns this full OpenAPI 3.1 JSON definition for client SDK generators, Postman, and automated API contract testing.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: Complete OpenAPI 3.1 JSON specification
---
# Get event ticket pass details by token
URL: /docs/api-reference/event-passes-tickets/getEventTicketByToken
## GET `/api/v1/public/events/tickets/{token}`
**Summary:** Get event ticket pass details by token
**Operation ID:** `getEventTicketByToken`
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `token` | `path` | Yes | |
### Responses
- **`200`**: Ticket details and pass status
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"token": {
"type": "string"
},
"eventName": {
"type": "string",
"example": "Annual Tech Summit"
},
"status": {
"type": "string",
"example": "VALID"
},
"holder": {
"type": "string"
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# Verify and check in door entry ticket QR token
URL: /docs/api-reference/event-passes-tickets/verifyEventTicket
## POST `/api/v1/public/events/tickets/verify`
**Summary:** Verify and check in door entry ticket QR token
**Operation ID:** `verifyEventTicket`
Validates ticket token validity and marks attendee as checked in.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"token"
],
"properties": {
"token": {
"type": "string",
"example": "TK-AB74X9"
},
"eventId": {
"type": "string",
"format": "uuid"
}
}
}
```
### Responses
- **`200`**: Verification outcome with attendee details
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"verified": {
"type": "boolean",
"example": true
},
"attendeeName": {
"type": "string",
"example": "Kwame Mensah"
},
"ticketTier": {
"type": "string",
"example": "VIP"
},
"checkedInAt": {
"type": "string",
"format": "date-time"
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Create reusable survey template with custom questions
URL: /docs/api-reference/micro-surveys-nps/createSurvey
## POST `/api/v1/public/surveys`
**Summary:** Create reusable survey template with custom questions
**Operation ID:** `createSurvey`
Configures a responsive web survey template supporting NPS (0-10), CSAT (1-5), star ratings, multiple choice, and open-ended feedback.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"title",
"questions"
],
"properties": {
"title": {
"type": "string",
"example": "Customer Satisfaction Survey"
},
"description": {
"type": "string",
"example": "How was your experience today?"
},
"surveyType": {
"type": "string",
"enum": [
"NPS_1_TO_10",
"CSAT_1_TO_5",
"CUSTOM"
],
"default": "NPS_1_TO_10"
},
"questions": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"type",
"label"
],
"properties": {
"id": {
"type": "string",
"example": "nps_q1"
},
"type": {
"type": "string",
"enum": [
"NPS_1_TO_10",
"RATING_STARS",
"SINGLE_CHOICE",
"MULTIPLE_CHOICE",
"TEXT",
"YES_NO"
]
},
"label": {
"type": "string",
"example": "How likely are you to recommend us to a friend?"
},
"required": {
"type": "boolean",
"default": true
}
}
}
}
}
}
```
### Responses
- **`201`**: Survey template created
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"title": {
"type": "string"
},
"surveyType": {
"type": "string"
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Get aggregate survey metrics and NPS score
URL: /docs/api-reference/micro-surveys-nps/getSurveyMetrics
## GET `/api/v1/public/surveys/{id}/metrics`
**Summary:** Get aggregate survey metrics and NPS score
**Operation ID:** `getSurveyMetrics`
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Response rate %, NPS score (-100 to +100), and breakdown
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"npsScore": {
"type": "integer",
"example": 68
},
"totalResponses": {
"type": "integer",
"example": 254
},
"promoters": {
"type": "integer",
"example": 190
},
"passives": {
"type": "integer",
"example": 45
},
"detractors": {
"type": "integer",
"example": 19
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Dispatch survey invitation SMS
URL: /docs/api-reference/micro-surveys-nps/sendSurveyInvitation
## POST `/api/v1/public/surveys/send`
**Summary:** Dispatch survey invitation SMS
**Operation ID:** `sendSurveyInvitation`
Generates a unique short token, deducts SMS segments + service surcharge, and sends SMS invitation with responsive web link.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"recipient"
],
"properties": {
"surveyId": {
"type": "string",
"format": "uuid"
},
"title": {
"type": "string",
"example": "Feedback Request"
},
"recipient": {
"type": "string",
"example": "+233241234567"
},
"senderId": {
"type": "string",
"example": "FEEDBACK"
},
"customMessage": {
"type": "string",
"example": "Hi! Please take 30 seconds to rate us: {link}"
}
}
}
```
### Responses
- **`200`**: Survey invitation dispatched
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Survey invitation dispatched"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Create MFA Workflow
URL: /docs/api-reference/multi-factor-authentication-mfa/createMfaWorkflow
## POST `/api/v1/public/mfa/workflows`
**Summary:** Create MFA Workflow
**Operation ID:** `createMfaWorkflow`
Creates a new multi-factor authentication workflow policy configuring code length, expiration TTL, resend cooldown, channels, and optional signed webhooks.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string",
"example": "High Value Transactions"
},
"senderId": {
"type": "string",
"example": "AUTH"
},
"codeLength": {
"type": "integer",
"minimum": 4,
"maximum": 8,
"default": 6,
"example": 6
},
"expiryMinutes": {
"type": "integer",
"minimum": 1,
"maximum": 60,
"default": 5,
"example": 5
},
"maxAttempts": {
"type": "integer",
"minimum": 1,
"maximum": 10,
"default": 3,
"example": 3
},
"resendCooldownSeconds": {
"type": "integer",
"minimum": 10,
"maximum": 300,
"default": 30,
"example": 30
},
"channel": {
"type": "string",
"enum": [
"SMS",
"WHATSAPP",
"AUTO_FAILOVER"
],
"default": "AUTO_FAILOVER"
},
"messageTemplate": {
"type": "string",
"example": "Your security code is {code}."
},
"webhookUrl": {
"type": "string",
"format": "uri",
"example": "https://myapp.com/webhooks/mfa"
},
"webhookSecret": {
"type": "string",
"example": "whsec_secret94812"
},
"isDefault": {
"type": "boolean",
"default": false
},
"isActive": {
"type": "boolean",
"default": true
},
"defaultProofMode": {
"type": "string",
"enum": [
"CHALLENGE_RESPONSE",
"PLAIN"
],
"default": "CHALLENGE_RESPONSE",
"example": "CHALLENGE_RESPONSE"
}
}
}
```
### Responses
- **`201`**: MFA workflow successfully created
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "MFA workflow created successfully"
},
"data": {
"$ref": "#/components/schemas/MfaWorkflowDto"
}
}
}
```
- **`400`**: Invalid or malformed request syntax
- **`401`**: Authentication failed or API key missing
---
# Delete MFA Workflow by ID
URL: /docs/api-reference/multi-factor-authentication-mfa/deleteMfaWorkflow
## DELETE `/api/v1/public/mfa/workflows/{id}`
**Summary:** Delete MFA Workflow by ID
**Operation ID:** `deleteMfaWorkflow`
Deletes an MFA workflow configuration.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Workflow deleted successfully
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "MFA workflow deleted successfully"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Get MFA Workflow by ID
URL: /docs/api-reference/multi-factor-authentication-mfa/getMfaWorkflowById
## GET `/api/v1/public/mfa/workflows/{id}`
**Summary:** Get MFA Workflow by ID
**Operation ID:** `getMfaWorkflowById`
Retrieves configuration settings for a specific MFA workflow.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | Workflow identifier |
### Responses
- **`200`**: Workflow configuration details
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaWorkflowDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# Initiate MFA Challenge
URL: /docs/api-reference/multi-factor-authentication-mfa/initiateMfaChallenge
## POST `/api/v1/public/mfa/challenge`
**Summary:** Initiate MFA Challenge
**Operation ID:** `initiateMfaChallenge`
Generates a security challenge and dispatches verification challenge code over the configured channel (SMS, WhatsApp, or auto-failover).
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"workflowId": {
"type": "string",
"example": "wf-84910-b2c3"
},
"action": {
"type": "string",
"example": "PAYMENT_CONFIRMATION"
},
"senderId": {
"type": "string",
"example": "AUTH"
}
}
}
```
### Responses
- **`200`**: MFA challenge initiated
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaChallengeResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# List MFA Workflows
URL: /docs/api-reference/multi-factor-authentication-mfa/listMfaWorkflows
## GET `/api/v1/public/mfa/workflows`
**Summary:** List MFA Workflows
**Operation ID:** `listMfaWorkflows`
Retrieves all configured multi-factor authentication workflows for the API key owner.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Responses
- **`200`**: List of configured MFA workflows
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "MFA workflows retrieved"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MfaWorkflowDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Resend MFA Challenge Code
URL: /docs/api-reference/multi-factor-authentication-mfa/resendMfaChallenge
## POST `/api/v1/public/mfa/resend`
**Summary:** Resend MFA Challenge Code
**Operation ID:** `resendMfaChallenge`
Resends the verification challenge code subject to workflow cooldown rules.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"challengeId"
],
"properties": {
"challengeId": {
"type": "string",
"example": "ch_7f9a2e41"
}
}
}
```
### Responses
- **`200`**: Challenge code resent
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaChallengeResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Set Default MFA Workflow
URL: /docs/api-reference/multi-factor-authentication-mfa/setDefaultMfaWorkflow
## POST `/api/v1/public/mfa/workflows/{id}/set-default`
**Summary:** Set Default MFA Workflow
**Operation ID:** `setDefaultMfaWorkflow`
Designates the specified workflow as the default policy for challenge requests.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Default workflow updated
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaWorkflowDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Test MFA Webhook Endpoint
URL: /docs/api-reference/multi-factor-authentication-mfa/testMfaWebhook
## POST `/api/v1/public/mfa/workflows/test-webhook`
**Summary:** Test MFA Webhook Endpoint
**Operation ID:** `testMfaWebhook`
Dispatches a simulated ping event with a computed `X-SmsPro-Signature` HMAC to test customer webhook server integration.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"webhookUrl"
],
"properties": {
"webhookUrl": {
"type": "string",
"format": "uri",
"example": "https://myapp.com/api/webhooks/mfa"
},
"webhookSecret": {
"type": "string",
"example": "whsec_948f293048a1b2c3d4e5f60718"
}
}
}
```
### Responses
- **`200`**: Webhook test dispatch result with status code and latency
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "MFA webhook test dispatched"
},
"data": {
"type": "object",
"properties": {
"delivered": {
"type": "boolean",
"example": true
},
"statusCode": {
"type": "integer",
"example": 200
},
"latencyMs": {
"type": "integer",
"example": 142
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Update MFA Workflow by ID
URL: /docs/api-reference/multi-factor-authentication-mfa/updateMfaWorkflow
## PUT `/api/v1/public/mfa/workflows/{id}`
**Summary:** Update MFA Workflow by ID
**Operation ID:** `updateMfaWorkflow`
Updates settings, expiry timers, or webhooks on an existing MFA workflow.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string",
"example": "High Value Transactions"
},
"senderId": {
"type": "string",
"example": "AUTH"
},
"codeLength": {
"type": "integer",
"minimum": 4,
"maximum": 8,
"default": 6,
"example": 6
},
"expiryMinutes": {
"type": "integer",
"minimum": 1,
"maximum": 60,
"default": 5,
"example": 5
},
"maxAttempts": {
"type": "integer",
"minimum": 1,
"maximum": 10,
"default": 3,
"example": 3
},
"resendCooldownSeconds": {
"type": "integer",
"minimum": 10,
"maximum": 300,
"default": 30,
"example": 30
},
"channel": {
"type": "string",
"enum": [
"SMS",
"WHATSAPP",
"AUTO_FAILOVER"
],
"default": "AUTO_FAILOVER"
},
"messageTemplate": {
"type": "string",
"example": "Your security code is {code}."
},
"webhookUrl": {
"type": "string",
"format": "uri",
"example": "https://myapp.com/webhooks/mfa"
},
"webhookSecret": {
"type": "string",
"example": "whsec_secret94812"
},
"isDefault": {
"type": "boolean",
"default": false
},
"isActive": {
"type": "boolean",
"default": true
},
"defaultProofMode": {
"type": "string",
"enum": [
"CHALLENGE_RESPONSE",
"PLAIN"
],
"default": "CHALLENGE_RESPONSE",
"example": "CHALLENGE_RESPONSE"
}
}
}
```
### Responses
- **`200`**: Workflow updated successfully
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "MFA workflow updated successfully"
},
"data": {
"$ref": "#/components/schemas/MfaWorkflowDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Verify MFA Challenge Code
URL: /docs/api-reference/multi-factor-authentication-mfa/verifyMfaChallenge
## POST `/api/v1/public/mfa/verify`
**Summary:** Verify MFA Challenge Code
**Operation ID:** `verifyMfaChallenge`
Performs constant-time validation of submitted MFA challenge code. On successful verification, returns `verified: true` and a cryptographically signed `verificationToken` proof token for subsequent authenticated actions.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"challengeId",
"code"
],
"properties": {
"challengeId": {
"type": "string",
"example": "ch_7f9a2e41"
},
"code": {
"type": "string",
"example": "849201"
}
}
}
```
### Responses
- **`200`**: Challenge verification outcome
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaVerifyResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Create tracked vanity short link
URL: /docs/api-reference/short-links-analytics/createShortLink
## POST `/api/v1/public/shortlinks`
**Summary:** Create tracked vanity short link
**Operation ID:** `createShortLink`
Generates a compressed vanity URL with optional custom slug and expiration. Automatically enables dynamic click-through rate (CTR) tracking.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"originalUrl"
],
"properties": {
"originalUrl": {
"type": "string",
"format": "uri",
"example": "https://example.com/promo/summer-sale?utm_source=sms"
},
"customCode": {
"type": "string",
"example": "summer26"
},
"title": {
"type": "string",
"example": "Summer 2026 Promo"
},
"expiresAt": {
"type": "string",
"format": "date-time"
}
}
}
```
### Responses
- **`201`**: Short link created
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"shortUrl": {
"type": "string",
"example": "https://smspro.link/s/summer26"
},
"shortCode": {
"type": "string",
"example": "summer26"
},
"originalUrl": {
"type": "string"
},
"active": {
"boolean": true,
"example": true
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Deactivate short link
URL: /docs/api-reference/short-links-analytics/deleteShortLink
## DELETE `/api/v1/public/shortlinks/{id}`
**Summary:** Deactivate short link
**Operation ID:** `deleteShortLink`
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Short link deactivated and slug removed from cache
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Short link deactivated"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Get real-time CTR and click analytics
URL: /docs/api-reference/short-links-analytics/getShortLinkAnalytics
## GET `/api/v1/public/shortlinks/{id}/analytics`
**Summary:** Get real-time CTR and click analytics
**Operation ID:** `getShortLinkAnalytics`
Returns total clicks, unique visitors, click-through rate percentage, and breakdowns by device type, operating system, and browser.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Real-time analytics and device telemetry
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ShortLinkAnalyticsDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Get short link metadata
URL: /docs/api-reference/short-links-analytics/getShortLinkById
## GET `/api/v1/public/shortlinks/{id}`
**Summary:** Get short link metadata
**Operation ID:** `getShortLinkById`
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Short link metadata and target URL
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ShortLinkDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# List short links
URL: /docs/api-reference/short-links-analytics/listShortLinks
## GET `/api/v1/public/shortlinks`
**Summary:** List short links
**Operation ID:** `listShortLinks`
Retrieves short links owned by the caller with pagination.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `page` | `query` | No | |
| `pageSize` | `query` | No | |
### Responses
- **`200`**: List of short links with total count
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ShortLinkDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Toggle short link active status
URL: /docs/api-reference/short-links-analytics/toggleShortLinkStatus
## PATCH `/api/v1/public/shortlinks/{id}/status`
**Summary:** Toggle short link active status
**Operation ID:** `toggleShortLinkStatus`
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"active"
],
"properties": {
"active": {
"type": "boolean"
}
}
}
```
### Responses
- **`200`**: Short link active state updated
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ShortLinkDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Cancel upcoming reminder stages
URL: /docs/api-reference/smart-reminders/cancelReminder
## DELETE `/api/v1/public/reminders/{id}`
**Summary:** Cancel upcoming reminder stages
**Operation ID:** `cancelReminder`
Aborts all remaining pending stages. No future SMS credits will be deducted.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Reminder stages cancelled
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Reminder cancelled successfully"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Get reminder details and stage delivery statuses
URL: /docs/api-reference/smart-reminders/getReminderById
## GET `/api/v1/public/reminders/{id}`
**Summary:** Get reminder details and stage delivery statuses
**Operation ID:** `getReminderById`
Retrieves the status of all scheduled alert stages and execution logs for a reminder.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `id` | `path` | Yes | |
### Responses
- **`200`**: Reminder details with individual stage statuses
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/ReminderResponseDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# Schedule multi-stage appointment reminder
URL: /docs/api-reference/smart-reminders/scheduleReminder
## POST `/api/v1/public/reminders/schedule`
**Summary:** Schedule multi-stage appointment reminder
**Operation ID:** `scheduleReminder`
Queues automated timed reminders before an event (e.g. 24h, 2h before). Charges SMS segment cost plus configured service surcharge per sent stage.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"recipient",
"eventTitle",
"eventTime",
"schedule",
"messageTemplate"
],
"properties": {
"recipient": {
"type": "string",
"example": "+233241234567"
},
"eventTitle": {
"type": "string",
"example": "Dental Checkup"
},
"eventTime": {
"type": "string",
"format": "date-time",
"example": "2026-11-15T14:30:00Z"
},
"schedule": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"24h",
"2h"
]
},
"messageTemplate": {
"type": "string",
"example": "Reminder: {eventTitle} scheduled for {eventTime}."
},
"senderId": {
"type": "string",
"example": "CLINIC"
}
}
}
```
### Responses
- **`201`**: Reminder successfully scheduled
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Reminder scheduled successfully"
},
"data": {
"$ref": "#/components/schemas/ReminderResponseDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`422`**: Validation error or invalid input parameters
---
# Query message dispatch history
URL: /docs/api-reference/transactional-sms/getHistory
## GET `/api/v1/public/sms/history`
**Summary:** Query message dispatch history
**Operation ID:** `getHistory`
Returns recent dispatched messages within an optional date-time range (up to 100 entries).
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `from` | `query` | No | Filter messages dispatched on or after this timestamp |
| `to` | `query` | No | Filter messages dispatched on or before this timestamp |
| `limit` | `query` | No | Maximum number of records to return |
### Responses
- **`200`**: List of recent dispatched SMS records
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/SmsHistoryItemDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Query dispatch history (POST alias)
URL: /docs/api-reference/transactional-sms/getHistoryPost
## POST `/api/v1/public/sms/history`
**Summary:** Query dispatch history (POST alias)
**Operation ID:** `getHistoryPost`
Query dispatch history using a JSON body filter in environments where query string parameters are restricted.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"properties": {
"from": {
"type": "string",
"format": "date-time"
},
"to": {
"type": "string",
"format": "date-time"
},
"limit": {
"type": "integer",
"default": 50
}
}
}
```
### Responses
- **`200`**: List of recent dispatched SMS records
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/SmsHistoryItemDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Retrieve SMS status and delivery details
URL: /docs/api-reference/transactional-sms/getMessageById
## GET `/api/v1/public/sms/messages/{messageId}`
**Summary:** Retrieve SMS status and delivery details
**Operation ID:** `getMessageById`
Returns current delivery status, carrier report, submission and delivery timestamps, sender ID, and segment metrics for a dispatched message.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `messageId` | `path` | Yes | Unique identifier of the SMS message |
### Responses
- **`200`**: Message status and carrier receipt details
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/SmsMessageDetailDto"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`404`**: Requested resource was not found
---
# Batch query multiple message statuses
URL: /docs/api-reference/transactional-sms/queryMessageStatuses
## POST `/api/v1/public/sms/messages`
**Summary:** Batch query multiple message statuses
**Operation ID:** `queryMessageStatuses`
Retrieves current delivery states and carrier timestamps for an array of up to 50 message IDs in a single call.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"messageIds"
],
"properties": {
"messageIds": {
"type": "array",
"items": {
"type": "string"
},
"maxItems": 50,
"example": [
"c7a8b9e0-1234-5678-9abc-def012345678",
"e8f9a0b1-2345-6789-0bcd-ef0123456789"
]
}
}
}
```
### Responses
- **`200`**: Array of message details matching the requested IDs
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/SmsMessageDetailDto"
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Search message dispatch history with filters
URL: /docs/api-reference/transactional-sms/searchHistory
## GET `/api/v1/public/sms/history/search`
**Summary:** Search message dispatch history with filters
**Operation ID:** `searchHistory`
Search and paginate through dispatch logs by phone number, message text keyword, delivery status, or date range.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `q` | `query` | No | Search query matching recipient or text |
| `status` | `query` | No | Filter by message delivery status |
| `page` | `query` | No | Page index (0-based) |
| `pageSize` | `query` | No | Number of records per page |
### Responses
- **`200`**: Paginated history search results
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"$ref": "#/components/schemas/SmsHistoryItemDto"
}
},
"totalElements": {
"type": "integer",
"example": 142
},
"page": {
"type": "integer",
"example": 0
},
"pageSize": {
"type": "integer",
"example": 20
}
}
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Send single or multi-recipient SMS
URL: /docs/api-reference/transactional-sms/sendSms
## POST `/api/v1/public/sms/send`
**Summary:** Send single or multi-recipient SMS
**Operation ID:** `sendSms`
Dispatches high-priority transactional SMS to 1-10 recipients. Supports test keys (`sk_test_...`) and magic numbers (`+233200000001` through `+233200000004`) for deterministic sandbox simulation without deducting wallet credits.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Parameters
| Name | In | Required | Description |
| :--- | :--- | :--- | :--- |
| `Idempotency-Key` | `header` | No | Unique UUID or string for idempotent dispatch protection. Guarantees that a message is only sent once within a 24-hour window. |
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"message"
],
"properties": {
"to": {
"type": "string",
"description": "Single recipient phone number in E.164 format",
"example": "+233241234567"
},
"recipients": {
"type": "array",
"items": {
"type": "string"
},
"maxItems": 10,
"description": "Multi-recipient list (1-10 phone numbers in E.164 format)",
"example": [
"+233241234567",
"+233200000001"
]
},
"message": {
"type": "string",
"description": "Text content of the message",
"example": "Your OTP verification code is 849201."
},
"senderId": {
"type": "string",
"maxLength": 11,
"description": "Registered alphanumeric Sender ID (max 11 chars)",
"example": "SMSPRO"
},
"scheduleAt": {
"type": "string",
"format": "date-time",
"description": "Optional future timestamp to schedule delivery",
"example": "2026-11-01T12:00:00Z"
},
"deliveryCallbackUrl": {
"type": "string",
"format": "uri",
"description": "Webhook URL to receive signed delivery receipts",
"example": "https://myapp.com/webhooks/dlr"
}
}
}
```
### Responses
- **`202`**: Message accepted and queued for carrier delivery or simulated in sandbox
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Queued"
},
"data": {
"type": "object",
"properties": {
"jobId": {
"type": "string",
"example": "job-d41d8cd9-8f00"
},
"messageIds": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"c7a8b9e0-1234-5678-9abc-def012345678"
]
},
"messageId": {
"type": "string",
"example": "c7a8b9e0-1234-5678-9abc-def012345678"
},
"status": {
"type": "string",
"example": "ACCEPTED"
},
"segmentCount": {
"type": "integer",
"example": 1
},
"totalUnits": {
"type": "integer",
"example": 1
}
}
}
}
}
```
- **`400`**: Invalid or malformed request syntax
- **`401`**: Authentication failed or API key missing
- **`403`**: API key lacks required scope (e.g. sms:send, mfa:write, balance:read)
- **`422`**: Validation error or invalid input parameters
- **`429`**: Rate limit exceeded for the API key
---
# Trigger immediate SMS failover
URL: /docs/api-reference/two-factor-verification-otp/failoverOtp
## POST `/api/v1/public/otp/failover`
**Summary:** Trigger immediate SMS failover
**Operation ID:** `failoverOtp`
Explicitly triggers immediate resend of the active verification code via high-priority SMS route if WhatsApp delivery was delayed.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
}
}
}
```
### Responses
- **`200`**: Verification code dispatched via SMS fallback route
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Verification code resent via SMS fallback"
},
"data": {
"$ref": "#/components/schemas/OtpSendResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Generate and dispatch OTP verification code
URL: /docs/api-reference/two-factor-verification-otp/sendOtp
## POST `/api/v1/public/otp/send`
**Summary:** Generate and dispatch OTP verification code
**Operation ID:** `sendOtp`
Generates a cryptographically secure random verification code (4, 6, or 8 digits), reserves credits, and dispatches via priority OTP queue with automatic 30-second cooldown protection. Supports WhatsApp-first delivery with SMS fallback.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"senderId": {
"type": "string",
"maxLength": 11,
"example": "VERIFY"
},
"digits": {
"type": "integer",
"enum": [
4,
6,
8
],
"default": 6,
"example": 6
},
"expirySeconds": {
"type": "integer",
"default": 300,
"example": 300
},
"template": {
"type": "string",
"example": "Your verification code is {code}. Valid for {expiryMinutes} minutes."
},
"strategy": {
"type": "string",
"enum": [
"AUTO",
"SMS_ONLY",
"WHATSAPP_FIRST"
],
"default": "AUTO",
"description": "Delivery channel strategy. AUTO delivers via WhatsApp first if available, falling back to SMS."
}
}
}
```
### Responses
- **`200`**: OTP verification dispatched successfully
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Verification code dispatched successfully"
},
"data": {
"$ref": "#/components/schemas/OtpSendResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`429`**: Rate limit exceeded for the API key
---
# Verify submitted OTP code
URL: /docs/api-reference/two-factor-verification-otp/verifyOtp
## POST `/api/v1/public/otp/verify`
**Summary:** Verify submitted OTP code
**Operation ID:** `verifyOtp`
Validates the submitted verification code in constant time against active verification session. Enforces maximum attempt limits and prevents replay attacks. Returns the delivery channel used.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber",
"code"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"code": {
"type": "string",
"example": "849201"
},
"otpId": {
"type": "string",
"example": "otp-c7a8b9e0-1234"
}
}
}
```
### Responses
- **`200`**: Verification outcome with session resolution
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/OtpVerifyResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Trigger OTP Failover to SMS with Fresh Nonce (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/failoverOtpV2
## POST `/api/v2/public/otp/failover`
**Summary:** Trigger OTP Failover to SMS with Fresh Nonce (v2)
**Operation ID:** `failoverOtpV2`
Immediately resends OTP via priority SMS channel and rotates the challenge nonce for subsequent zero-knowledge proof generation.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
}
}
}
```
### Responses
- **`200`**: OTP failover resent via SMS
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Verification code resent via SMS"
},
"data": {
"$ref": "#/components/schemas/OtpSendResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Initiate MFA Challenge with Nonce (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/initiateMfaChallengeV2
## POST `/api/v2/public/mfa/challenge`
**Summary:** Initiate MFA Challenge with Nonce (v2)
**Operation ID:** `initiateMfaChallengeV2`
Generates a security challenge and dispatches verification challenge code over configured channels (SMS, WhatsApp, or auto-failover). Returns a 128-bit cryptographic challenge nonce for client-side zero-knowledge proof calculation.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"workflowId": {
"type": "string",
"example": "wf-84910-b2c3"
},
"action": {
"type": "string",
"example": "PAYMENT_CONFIRMATION"
},
"senderId": {
"type": "string",
"example": "AUTH"
}
}
}
```
### Responses
- **`200`**: MFA challenge initiated with challenge nonce
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaChallengeResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Resend MFA Challenge with Rotated Nonce (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/resendMfaChallengeV2
## POST `/api/v2/public/mfa/resend`
**Summary:** Resend MFA Challenge with Rotated Nonce (v2)
**Operation ID:** `resendMfaChallengeV2`
Resends the verification challenge code subject to workflow cooldown rules and issues a fresh challenge nonce.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"challengeId"
],
"properties": {
"challengeId": {
"type": "string",
"example": "ch_7f9a2e41"
},
"channel": {
"type": "string",
"example": "SMS"
}
}
}
```
### Responses
- **`200`**: Challenge code resent with fresh challenge nonce
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaChallengeResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Generate & Send OTP with Challenge Nonce (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/sendOtpV2
## POST `/api/v2/public/otp/send`
**Summary:** Generate & Send OTP with Challenge Nonce (v2)
**Operation ID:** `sendOtpV2`
Generates a cryptographically random verification code, reserves credits, and issues a 128-bit cryptographic challenge nonce alongside the dispatched SMS or WhatsApp. The nonce is used by client applications to compute a zero-knowledge challenge-response proof, ensuring cleartext codes are never transmitted over HTTP.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"senderId": {
"type": "string",
"maxLength": 11,
"example": "VERIFY"
},
"digits": {
"type": "integer",
"enum": [
4,
6,
8
],
"default": 6,
"example": 6
},
"expirySeconds": {
"type": "integer",
"default": 300,
"example": 300
},
"template": {
"type": "string",
"example": "Your verification code is {code}. Valid for {expiryMinutes} minutes."
},
"strategy": {
"type": "string",
"enum": [
"AUTO",
"SMS_ONLY",
"WHATSAPP_FIRST"
],
"default": "AUTO"
}
}
}
```
### Responses
- **`200`**: OTP verification dispatched with challenge nonce
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"message": {
"type": "string",
"example": "Verification code dispatched successfully"
},
"data": {
"$ref": "#/components/schemas/OtpSendResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`429`**: Rate limit exceeded for the API key
---
# Verify MFA Zero-Knowledge Proof (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/verifyMfaChallengeV2
## POST `/api/v2/public/mfa/verify`
**Summary:** Verify MFA Zero-Knowledge Proof (v2)
**Operation ID:** `verifyMfaChallengeV2`
Performs constant-time zero-knowledge proof verification (`codeProof`) against the issued challenge nonce. On successful verification, returns a cryptographically signed `verificationToken` proof token for subsequent authenticated actions and burns the challenge nonce.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"challengeId",
"codeProof"
],
"properties": {
"challengeId": {
"type": "string",
"example": "ch_7f9a2e41"
},
"codeProof": {
"type": "string",
"description": "Zero-Knowledge challenge proof: hex(sha256(challengeNonce.trim().toLowerCase() + ':' + code.trim().toLowerCase()))",
"example": "7c8e91f0c2b3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9"
}
}
}
```
### Responses
- **`200`**: Challenge verification outcome with proof token
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/MfaVerifyResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
---
# Verify Submitted OTP Zero-Knowledge Proof (v2)
URL: /docs/api-reference/zero-knowledge-verification-v2/verifyOtpV2
## POST `/api/v2/public/otp/verify`
**Summary:** Verify Submitted OTP Zero-Knowledge Proof (v2)
**Operation ID:** `verifyOtpV2`
Verifies the submitted zero-knowledge `codeProof` in constant time against the issued challenge nonce and active session. Enforces attempt limits and immediately burns the single-use token on success to prevent replay.
**Authentication:** `X-Api-Key: sk_live_...` or `Authorization: Bearer sk_live_...`
### Request Body (`application/json`)
```json
{
"type": "object",
"required": [
"phoneNumber",
"codeProof"
],
"properties": {
"phoneNumber": {
"type": "string",
"example": "+233241234567"
},
"codeProof": {
"type": "string",
"description": "Zero-Knowledge challenge proof: hex(sha256(challengeNonce.trim().toLowerCase() + ':' + code.trim().toLowerCase()))",
"example": "4a8e91f0c2b3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9"
},
"otpId": {
"type": "string",
"example": "otp-c7a8b9e0-1234"
}
}
}
```
### Responses
- **`200`**: Verification outcome
```json
{
"type": "object",
"properties": {
"status": {
"type": "string",
"example": "success"
},
"data": {
"$ref": "#/components/schemas/OtpVerifyResponse"
}
}
}
```
- **`401`**: Authentication failed or API key missing
- **`429`**: Rate limit exceeded for the API key
---
# API Reference Overview
URL: /docs/api-reference
> Base URLs, ResourceResponse envelopes, rate limit headers, and RFC 7807 Problem Details for the SMS Pro v1/v2 API.
The SMS Pro Developer API follows RESTful JSON conventions over HTTPS with an interactive OpenAPI 3.1 playground on every operation page.
## API and keys [#api-and-keys]
Every call uses `https://api.smspro.com`.
| Key prefix | Behavior |
| :--- | :--- |
| `sk_test_` | Simulated delivery. No wallet charge. Magic numbers select a specific outcome. |
| `sk_live_` | Carrier delivery. Uses wallet credit. |
Pass the key with `X-Api-Key` or `Authorization: Bearer`.
## Standard Success Envelope [#standard-success-envelope]
All JSON endpoints wrap response payloads inside a uniform `ResourceResponse` envelope:
```json
{
"status": "success",
"message": "Operation completed successfully",
"data": {
"balance": 250.0,
"smsUnits": 1000,
"currency": "GHS"
}
}
```
## Rate Limit & Tracing Headers [#rate-limit--tracing-headers]
Responses include diagnostic and rate-limiting metadata headers:
## RFC 7807 Problem Details Errors [#rfc-7807-problem-details-errors]
Non-2xx responses return `Content-Type: application/problem+json` following RFC 7807:
```json
{
"type": "https://docs.smspro.com/errors/insufficient-credits",
"title": "Insufficient Unit Credits",
"status": 422,
"detail": "Wallet PAYG balance or SMS credit units insufficient for carrier dispatch.",
"instance": "/api/v1/public/sms/send",
"code": "INSUFFICIENT_CREDITS",
"requestId": "d50c1f10-982f-4889-8d76-d392ef401032"
}
```
| HTTP Status | Typical Causes |
| :--- | :--- |
| `400 Bad Request` | Malformed JSON body or missing required field |
| `401 Unauthorized` | Missing, revoked, or malformed `X-Api-Key` / `Bearer` token |
| `403 Forbidden` | Key lacks required permission scope (for example `sms:send` or `mfa:write`) |
| `404 Not Found` | Resource ID (`messageId`, `batchId`, `otpId`, or `challengeId`) does not exist |
| `422 Unprocessable Entity` | Invalid E.164 recipient, >10 transactional recipients, or `INSUFFICIENT_CREDITS` |
| `429 Too Many Requests` | Rate limit exceeded; inspect `X-RateLimit-Reset` before retrying |
---
# Authentication
URL: /docs/getting-started/authentication
> Secure your API requests with X-Api-Key or Bearer tokens, enforce granular scopes, and protect operations with idempotency.
All requests to the SMS Pro Developer Platform must be authenticated over HTTPS. Unauthenticated calls or requests with invalid keys will be rejected with an HTTP `401 Unauthorized` or `403 Forbidden` response.
---
## Authentication Schemes [#authentication-schemes]
SMS Pro supports two standard methods for supplying your API credentials:
### 1. `X-Api-Key` Header (Recommended) [#1-x-api-key-header-recommended]
Pass your secret key in the custom `X-Api-Key` header:
```http
POST /api/v1/public/sms/send HTTP/1.1
Host: api.smspro.com
X-Api-Key: sk_live_948f293048a1b2c3d4e5f60718a2b3c4
Content-Type: application/json
```
### 2. `Authorization: Bearer` Header [#2-authorization-bearer-header]
Alternatively, use the RFC 6750 standard `Bearer` authorization scheme:
```http
POST /api/v1/public/sms/send HTTP/1.1
Host: api.smspro.com
Authorization: Bearer sk_live_948f293048a1b2c3d4e5f60718a2b3c4
Content-Type: application/json
```
---
## Anatomy of an API Key [#anatomy-of-an-api-key]
SMS Pro uses distinct, human-readable key prefixes to prevent accidental environment mismatches:
| Prefix | Behavior |
| :--- | :--- |
| `sk_test_` | Simulated delivery on `https://api.smspro.com`. No wallet charge. |
| `sk_live_` | Carrier delivery on the same API. Uses wallet credit. |
Test keys and live keys are both sent to `https://api.smspro.com`. The key prefix selects simulated delivery or carrier delivery.
---
## Essential Request Headers [#essential-request-headers]
When constructing API calls, include the following headers:
| Header | Required? | Format / Value | Description |
| :--- | :--- | :--- | :--- |
| `X-Api-Key` | Required* | `sk_live_...` or `sk_test_...` | Secret API key (*or use `Authorization: Bearer`). |
| `Content-Type` | Required for `POST`/`PUT` | `application/json` | All request bodies must be JSON encoded. |
| `Idempotency-Key` | Recommended for `POST` | UUID v4 (e.g. `9b1deb4d-...`) | Unique request ID with a 24-hour cache TTL preventing duplicate dispatches on network retries. |
---
## Understanding Idempotency Keys [#understanding-idempotency-keys]
Network blips and client timeouts can occur during mobile or server-to-server operations. If your application sends a payment receipt SMS and times out after 5 seconds, retrying the call blindly could result in the customer receiving duplicate text messages and your balance being deducted twice.
To prevent this, supply a unique `Idempotency-Key` on every mutating request:
```ts
const idempotencyKey = crypto.randomUUID();
const res = await fetch('https://api.smspro.com/api/v1/public/sms/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.SMSPRO_API_KEY!,
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify({
to: '+233241234567',
senderId: 'SMSPRO',
message: 'Your order #89201 has been dispatched.',
}),
});
```
- If SMS Pro receives a request with an `Idempotency-Key` that was already processed within the past 24 hours, it **immediately returns the cached initial response** without re-queueing the SMS or billing your wallet again.
- Idempotency keys are cached per-organization, so keys from different accounts will never collide.
---
## Scope Verification & Principle of Least Privilege [#scope-verification--principle-of-least-privilege]
Every API key has a specific set of granted permissions. If your key attempts to access an endpoint outside its configured scopes, the gateway returns HTTP `403 Forbidden`:
```json
{
"type": "https://docs.smspro.com/errors/forbidden-scope",
"title": "Forbidden Scope",
"status": 403,
"detail": "API key lacks the required 'mfa:write' scope to access this resource.",
"code": "AUTH_FORBIDDEN_SCOPE",
"requestId": "req-9b1deb4d",
"timestamp": "2026-11-18T08:45:00Z"
}
```
To resolve this error, visit **Developer > API Keys** in the console and either edit the key's assigned scopes or generate a dedicated key with the required permissions.
---
## Zero-Downtime Key Rotation [#zero-downtime-key-rotation]
When cycling secrets or replacing a potentially compromised key, execute a zero-downtime rotation:
**Generate a New Key**
In the SMS Pro Console, generate a new scoped key with identical permissions and environments.
**Update Application Secrets**
Deploy the new key (`SMSPRO_API_KEY`) to your production staging and worker fleets.
**Verify Traffic in API Logs**
Navigate to **Developer > API Logs** and verify that requests are arriving successfully with the new key prefix.
**Revoke the Old Key**
Click **Revoke** on the legacy key in the console to permanently disable it.
---
## Common Authentication Errors [#common-authentication-errors]
| Status | Error Code | Root Cause & Resolution |
| :--- | :--- | :--- |
| `401` | `UNAUTHORIZED` | The key is missing, unknown, or the caller address is not on the IP whitelist. |
| `403` | `FORBIDDEN_SCOPE` | The key does not include the scope for this endpoint. |
| `422` | `API_KEY_ALLOCATION_EXCEEDED` | The key has used its SMS allocation. |
---
## Next Step [#next-step]
Learn how test keys and live keys share one API in [Environments](/docs/getting-started/environments).
---
# Create an Account
URL: /docs/getting-started/create-account
> Step-by-step walkthrough for registering on the SMS Pro platform and accessing the developer portal.
To begin integrating with SMS Pro, you must create a developer account on the official SMS Pro web platform. Registration is free and provides immediate access to the full sandbox simulation environment.
---
## Registration Steps [#registration-steps]
Follow these steps to set up your account:
### Navigate to the SMS Pro Platform [#navigate-to-the-sms-pro-platform]
Open the [SMS Pro console](https://smspro.com) and choose **Sign Up**. Account creation and sign-in are handled by the Authorisation Server.
### Enter Your Account Credentials [#enter-your-account-credentials]
Complete the prompts on the Authorisation Server. Use a work email address. The server may also offer a social sign-in.
### Confirm the account [#confirm-the-account]
Finish whatever confirmation the Authorisation Server asks for, such as an email code, before returning to the console.
### Set your profile [#set-your-profile]
After the first sign-in, open **Account settings**. You can set a display name and a phone number. The email address stays with the Authorisation Server.
### Access the Customer Dashboard [#access-the-customer-dashboard]
Once onboarded, you are automatically directed to your main **Customer Dashboard** (`/customer/dashboard`).
---
## Exploring the Customer Console [#exploring-the-customer-console]
The SMS Pro Console provides a unified interface for managing both manual campaign operations and automated developer integrations:

| Console section | Purpose |
| :--- | :--- |
| **Dashboard** | Credits, wallet cash, messages sent, and delivery rate for the selected period. |
| **Send SMS** | Compose a message or pick one from Message Bank. |
| **Campaign Manager** | Bulk and scheduled sends. |
| **Contacts** | All contacts, groups, and imports. |
| **Sender ID** | Request a sender name and track approval. |
| **Automations** | Reminders, birthdays, surveys, events, and short links. |
| **OTP and MFA** | Quick OTP and MFA workflows. |
| **Wallet and Billing** | Balance, top-up, bundles, subscriptions, and history. |
| **Reports** | Summary, detailed reports, and exports. |
| **Developer** | Shown after Developer Mode is on: API Documentation, API Keys, Webhooks, API Logs, Sandbox, and Usage Metrics. |
---
## After sign-in [#after-sign-in]
If the account has SMS credit, has not sent a message, and has not topped up, the dashboard shows **Complimentary Test SMS Credits Active**. You can dismiss that banner. Send from **Send SMS**, or turn on Developer Mode and call the API with an `sk_test_` key.
Live sends need an approved Sender ID and wallet credit. Request the sender name from **Sender ID**. There is no separate business-profile page. See [Going Live](/docs/getting-started/going-live).
Marketing messages are held during the platform quiet hours, 21:00–07:00 local time. Transactional messages and OTP are not held. Account settings shows this policy. It is not a switch on your account.
---
## Next Step [#next-step]
With your account established, the next step is to toggle the developer environment and generate your first API keys in [Developer Environment & API Keys](/docs/getting-started/create-application).
---
# Developer Environment & API Keys
URL: /docs/getting-started/create-application
> How to enable Developer Mode on SMS Pro, provision scoped API keys, assign granular permissions, and safeguard credentials.
To begin making programmatic API requests, you must enable the **Developer Environment** in your SMS Pro account and generate an API key with the appropriate security scopes.
---
## 1. Enabling Developer Mode [#1-enabling-developer-mode]
By default, the SMS Pro Console displays a simplified interface tailored for marketing and manual messaging. Enabling Developer Mode reveals advanced programmatic tools, API logs, and webhook management.
### Open Settings or Developer Preferences [#open-settings-or-developer-preferences]
Log in to the [SMS Pro console](https://smspro.com) and open **Account settings**.
### Toggle Developer Mode On [#toggle-developer-mode-on]
Locate the **Developer Mode** toggle switch and toggle it **On**.
This activates the `DEVELOPER_ENABLED` feature for your organization profile.
### Access the Developer Section [#access-the-developer-section]
Once enabled, a **Developer** group appears in the sidebar:
- **API Documentation**
- **API Keys**
- **Webhooks**
- **API Logs**
- **Sandbox**
- **Usage Metrics**
---
## 2. Choosing Your Key Type [#2-choosing-your-key-type]
In **Developer > API Keys**, SMS Pro offers two types of keys:
| Key Type | Scope & Authority | Recommended Use Case |
| :--- | :--- | :--- |
| **Master API Key** | Has full, unconstrained access across every endpoint, campaign, and wallet function in your organization. | Initial sandbox experimentation or administrative orchestration tools. Only one Master Key exists per account. |
| **Scoped API Keys** *(Recommended)* | Bound to specific permissions, environments (`live` vs `test`), dedicated traffic queues, rate limits, and optional IP allowlists. | Production microservices, third-party backend integrations, and serverless functions adhering to the **Principle of Least Privilege**. |
---
## 3. Generating a Scoped API Key [#3-generating-a-scoped-api-key]
The form is already on the page. Fill it in and click **Add API Key**. It does not open a separate dialog.

### Configuration fields [#configuration-fields]
#### 1. Key name [#1-key-name]
A label for the service using this key, such as `Billing worker`.
#### 2. Environment [#2-environment]
The default is **Live (`sk_live_`)**. Choose **Test / Sandbox (`sk_test_`)** while you are integrating. Both keys call `https://api.smspro.com`. A test key simulates delivery and does not charge the wallet.
#### 3. Traffic class [#3-traffic-class]
- **OTP and 2FA**: Verification messages.
- **Transactional notifications**: Receipts, alerts, and other operational messages.
- **Marketing campaigns**: Broadcast traffic.
#### 4. SMS allocation [#4-sms-allocation]
Required. Once the key has used this many units, further sends with that key are rejected with `422 API_KEY_ALLOCATION_EXCEEDED`.
#### 5. Rate limit [#5-rate-limit]
Optional requests-per-minute cap. Above the cap the API returns `429`.
#### 6. IP whitelist [#6-ip-whitelist]
Optional comma-separated addresses. A request from any other address is rejected as an invalid key.
---
## 4. Selecting Granular Scopes [#4-selecting-granular-scopes]
Scopes define the exact permissions granted to the API key. Follow the principle of least privilege—only check the permissions your integration strictly needs:
| Domain | Scope Identifier | Description |
| :--- | :--- | :--- |
| **SMS Messaging** | `sms:send` | Authorizes single and bulk SMS dispatch via `/api/v1/public/sms/*`. |
| | `sms:read` | Read delivery statuses, message history, and job metrics. |
| | `balance:read` | Check account wallet balances and unit rates via `/api/v1/public/account/balance`. |
| **OTP & 2FA** | `otp:send` | Dispatch automated numeric one-time verification passcodes. |
| | `otp:verify` | Validate user-submitted OTP codes against active challenges. |
| **Zero-Knowledge MFA** | `mfa:challenge` | Create cryptographically blind MFA challenges. |
| | `mfa:verify` | Verify client-side zero-knowledge MFA proofs. |
| | `mfa:read` | Query MFA configuration workflows and active sessions. |
| | `mfa:write` | Configure and update organizational MFA security workflows. |
| **Branded Shortlinks** | `shortlinks:write` | Create and shorten trackable branded short URLs. |
| | `shortlinks:read` | Retrieve real-time click telemetry, referrers, and device analytics. |
| **Contacts & Lists** | `contacts:write` | Create, update, or delete subscriber phone books and custom tags. |
| | `contacts:read` | Read subscriber profiles, birthday reminders, and list metadata. |
| **Automations** | `reminders:write` | Schedule and cancel automated calendar reminders. |
| | `reminders:read` | Query active and pending scheduled reminders. |
| | `surveys:write` | Launch interactive two-way SMS micro-surveys. |
| | `surveys:read` | Inspect customer responses and satisfaction survey results. |
| **Ops** | `webhooks:write` | Register and update webhook URLs. |
| | `reports:read` | Read delivery reports. |
| **AI and events** | `ai:copy` | Use the copy assistant. |
| | `events:verify` | Verify event ticket codes. |
---
## 5. Storing Your Secret Key Securely [#5-storing-your-secret-key-securely]
When you click **Add API Key**, the secret is shown once in a banner on the page:

```
sk_test_example
```
Once you leave this page, the full key cannot be viewed again. If you lose it, revoke it and create another.
The only dialog on this page is **Edit API Key**. It changes the name, traffic class, allocation, rate limit, IP whitelist, and scopes. It does not show the secret again.

### Recommended Storage Practices [#recommended-storage-practices]
1. **Environment Variables**: Store your key in `.env.local` or `.env` and add the file to your `.gitignore`:
```bash title=".env.local"
SMSPRO_API_KEY=sk_test_example
SMSPRO_BASE_URL=https://api.smspro.com
```
2. **Never Commit to Source Control**: Do not hardcode API keys directly in client-side mobile applications, frontend React/Vue code, or public GitHub repositories.
3. **Key Rotation**: When rotating credentials, generate a new scoped key first, update your production environment variables, verify successful traffic, and then revoke the old key.
---
## Next Step [#next-step]
Learn how to attach your credentials and construct valid HTTP request headers in [Authentication](/docs/getting-started/authentication).
---
# Environments
URL: /docs/getting-started/environments
> Compare test keys and live keys on the SMS Pro API.
SMS Pro has one API, `https://api.smspro.com`. The key you send chooses simulated delivery or carrier delivery.
---
## Key comparison [#key-comparison]

| | `sk_test_` | `sk_live_` |
| :--- | :--- | :--- |
| **Base URL** | `https://api.smspro.com` | `https://api.smspro.com` |
| **Delivery** | Simulated. No handset is contacted. | Sent to the carrier. |
| **Wallet** | Not charged. | Charged per segment. |
| **Result** | `202` with status `ACCEPTED_SANDBOX` and a `sim_` message id. | `202` and a later delivery status. |
| **Magic numbers** | Select a specific simulated outcome. | The same four numbers are still simulated, even on a live key. |
| **Sender ID** | A test name is accepted. | A custom name must be approved. |
---
## Test keys [#test-keys]
A test key checks authentication, scopes, and the request body, then returns a simulated acceptance. It also posts a simulated delivery webhook when you have a webhook URL.
```bash
curl -X POST "https://api.smspro.com/api/v1/public/sms/send" \
-H "X-Api-Key: sk_test_example" \
-H "Content-Type: application/json" \
-d '{
"to": "+233200000001",
"senderId": "SMSPRO",
"message": "Testing from local environment."
}'
```
Read the magic-number outcomes in [Testing in Sandbox](/docs/getting-started/testing-in-sandbox).
---
## Live keys [#live-keys]
A live key sends to the carrier and uses wallet credit.
```bash
curl -X POST "https://api.smspro.com/api/v1/public/sms/send" \
-H "X-Api-Key: sk_live_example" \
-H "Content-Type: application/json" \
-d '{
"to": "+233241234567",
"senderId": "MYAPP",
"message": "Your verification code is 491029."
}'
```
Before live traffic:
1. Keep a prepaid balance.
2. Use an approved `senderId`, or the platform default.
3. Send only to people who have opted in.
---
## Configuring Your Environment [#configuring-your-environment]
We recommend decoupling the gateway URL and API key from your application logic using environment variables.
### Local Development (`.env.local`) [#local-development-envlocal]
```bash title=".env.local"
SMSPRO_BASE_URL=https://api.smspro.com
SMSPRO_API_KEY=sk_test_948f293048a1b2c3d4e5f60718a2b3c4
```
### Production Deployment (`.env.production`) [#production-deployment-envproduction]
```bash title=".env.production"
SMSPRO_BASE_URL=https://api.smspro.com
SMSPRO_API_KEY=sk_live_891024ab9012cd34ef560718a2b3c4d5
```
### Dynamic Client Initialization Example [#dynamic-client-initialization-example]
```ts title="sms-client.ts"
const baseUrl = process.env.SMSPRO_BASE_URL || 'https://api.smspro.com';
const apiKey = process.env.SMSPRO_API_KEY;
if (!apiKey) {
throw new Error('Missing SMSPRO_API_KEY configuration.');
}
export async function sendSms(to: string, senderId: string, message: string) {
const response = await fetch(`${baseUrl}/api/v1/public/sms/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey,
'Idempotency-Key': crypto.randomUUID(),
},
body: JSON.stringify({ to, senderId, message }),
});
return response.json();
}
```
---
## Next Step [#next-step]
Make your very first live API call in [Your First API Request](/docs/getting-started/first-request).
---
# Your First API Request
URL: /docs/getting-started/first-request
> Send your very first transactional SMS message in under five minutes with copy-pasteable examples in cURL, TypeScript, Python, PHP, and Java.
This guide sends the first SMS with an `sk_test_` key on `https://api.smspro.com`. Magic numbers keep the send simulated and free of wallet charges.
---
## 1. The API Request [#1-the-api-request]
To send a message, submit an HTTP `POST` request to the `/api/v1/public/sms/send` endpoint.
Select your language of choice below to copy a complete, functional code sample:
```bash
curl -X POST "https://api.smspro.com/api/v1/public/sms/send" \
-H "X-Api-Key: sk_test_948f293048a1b2c3d4e5f60718" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
-d '{
"to": "+233200000001",
"senderId": "SMSPRO",
"message": "Welcome to SMS Pro! Your first API test is successful."
}'
```
```ts title="send-sms.ts"
import crypto from 'node:crypto';
interface SendSmsResponse {
status: string;
message: string;
data: {
jobId: string;
messageId: string;
status: string;
segmentCount: number;
totalUnits: number;
};
}
async function sendFirstSms() {
const apiKey = process.env.SMSPRO_API_KEY || 'sk_test_948f293048a1b2c3d4e5f60718';
const baseUrl = 'https://api.smspro.com';
const response = await fetch(`${baseUrl}/api/v1/public/sms/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey,
'Idempotency-Key': crypto.randomUUID(),
},
body: JSON.stringify({
to: '+233200000001',
senderId: 'SMSPRO',
message: 'Welcome to SMS Pro! Your first API test is successful.',
}),
});
const payload: SendSmsResponse = await response.json();
if (!response.ok) {
console.error(`Dispatch failed [${response.status}]:`, payload);
return;
}
console.log('✅ SMS Queued Successfully:');
console.log(`Job ID: ${payload.data.jobId}`);
console.log(`Message ID: ${payload.data.messageId}`);
console.log(`Segments: ${payload.data.segmentCount}`);
}
sendFirstSms();
```
```python title="send_sms.py"
import os
import uuid
import requests
API_KEY = os.getenv("SMSPRO_API_KEY", "sk_test_948f293048a1b2c3d4e5f60718")
BASE_URL = "https://api.smspro.com"
headers = {
"Content-Type": "application/json",
"X-Api-Key": API_KEY,
"Idempotency-Key": str(uuid.uuid4())
}
payload = {
"to": "+233200000001",
"senderId": "SMSPRO",
"message": "Welcome to SMS Pro! Your first API test is successful."
}
response = requests.post(f"{BASE_URL}/api/v1/public/sms/send", json=payload, headers=headers)
data = response.json()
if response.status_code == 202:
print("✅ SMS Queued Successfully:")
print(f"Job ID: {data['data']['jobId']}")
print(f"Message ID: {data['data']['messageId']}")
print(f"Segments: {data['data']['segmentCount']}")
else:
print(f"❌ Error [{response.status_code}]: {data}")
```
```php title="send_sms.php"
'+233200000001',
'senderId' => 'SMSPRO',
'message' => 'Welcome to SMS Pro! Your first API test is successful.'
];
$ch = curl_init("{$baseUrl}/api/v1/public/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Api-Key: ' . $apiKey,
'Idempotency-Key: ' . bin2hex(random_bytes(16))
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($statusCode === 202) {
echo "✅ SMS Queued Successfully:\n";
echo "Job ID: " . $data['data']['jobId'] . "\n";
echo "Message ID: " . $data['data']['messageId'] . "\n";
} else {
echo "❌ Error [{$statusCode}]: " . $response . "\n";
}
```
```java title="SendSms.java"
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;
public class SendSms {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv().getOrDefault("SMSPRO_API_KEY", "sk_test_948f293048a1b2c3d4e5f60718");
String endpoint = "https://api.smspro.com/api/v1/public/sms/send";
String jsonPayload = """
{
"to": "+233200000001",
"senderId": "SMSPRO",
"message": "Welcome to SMS Pro! Your first API test is successful."
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.header("Content-Type", "application/json")
.header("X-Api-Key", apiKey)
.header("Idempotency-Key", UUID.randomUUID().toString())
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("HTTP Status: " + response.statusCode());
System.out.println("Response: " + response.body());
}
}
```
---
## 2. Request Component Breakdown [#2-request-component-breakdown]
Let's dissect each component of the request:
### HTTP Headers [#http-headers]
- **`X-Api-Key`**: Authenticates the call. `sk_test_` simulates delivery on this same API.
- **`Content-Type: application/json`**: Signals to the gateway that the request body is a JSON-encoded string.
- **`Idempotency-Key`**: A random UUID identifying this specific transmission attempt. If network connectivity drops and your client retries the exact same call, the gateway guarantees the message will not be queued a second time.
### JSON Request Body [#json-request-body]
- **`to`**: Destination phone number. In this example, `+233200000001` is a reserved **Sandbox Magic Number** that causes the mock gateway to simulate an immediate successful delivery (`DELIVERED`). In production, SMS Pro accepts local format (`0241234567`), international without plus (`233241234567`), and standard E.164 (`+233241234567`), normalizing them automatically.
- **`senderId`**: Up to 11 alphanumeric characters (e.g. `SMSPRO`).
- **`message`**: The text string to deliver to the recipient.
---
## 3. Dissecting the Response [#3-dissecting-the-response]
A successful dispatch returns **HTTP `202 Accepted`**. The `202` status code indicates that the message has been validated, accepted by the ingestion pipeline, and queued for telco transmission:
```json
{
"status": "success",
"message": "Queued",
"data": {
"jobId": "job-d41d8cd9-8f00-4b11-b841-892104ab0123",
"messageIds": ["c7a8b9e0-1234-5678-9abc-def012345678"],
"messageId": "c7a8b9e0-1234-5678-9abc-def012345678",
"status": "ACCEPTED",
"segmentCount": 1,
"totalUnits": 1
}
}
```
### Response Fields Explained [#response-fields-explained]
- **`jobId`**: Identifier for the background dispatch job. For bulk sends, one job encompasses many messages.
- **`messageId`**: Unique identifier for this specific recipient delivery. Store this key in your database to correlate future delivery receipts (`DLR`).
- **`status`**: Current pipeline state. Begins at `ACCEPTED` or `QUEUED`, and later transitions to `SENT`, `DELIVERED`, or `FAILED`.
- **`segmentCount`**: The number of 160-character (GSM-7) or 70-character (UCS-2) SMS segments computed for your message text.
- **`totalUnits`**: Billing unit cost calculated for this dispatch (in sandbox, 0 balance is deducted).
---
## 4. Polling Delivery Status [#4-polling-delivery-status]
To query the current state of your message, send a `GET` request to `/api/v1/public/sms/messages/{messageId}`:
```bash
curl -X GET "https://api.smspro.com/api/v1/public/sms/messages/c7a8b9e0-1234-5678-9abc-def012345678" \
-H "X-Api-Key: sk_test_948f293048a1b2c3d4e5f60718"
```
Because `+233200000001` is a success magic number, the status will immediately report `DELIVERED`:
```json
{
"status": "success",
"message": "Message details retrieved",
"data": {
"id": "c7a8b9e0-1234-5678-9abc-def012345678",
"to": "+233200000001",
"senderId": "SMSPRO",
"status": "DELIVERED",
"deliveredAt": "2026-11-18T08:45:10Z"
}
}
```
---
## Next Step [#next-step]
Learn how to parse standard response envelopes, handle HTTP status codes, and manage errors in [Understanding Responses](/docs/getting-started/understanding-responses).
---
# Going Live
URL: /docs/getting-started/going-live
> The complete production readiness checklist for launching your SMS Pro integration onto live telecommunication carrier routes.
Transition from an `sk_test_` key to an `sk_live_` key on `https://api.smspro.com` after the account can pay for messages and the sender name is approved.
---
## Checklist [#checklist]
| Step | What to do |
| :--- | :--- |
| **1** | Confirm the display name and phone on Account settings. |
| **2** | Request a Sender ID and wait until it is approved. |
| **3** | Add credit from Wallet. |
| **4** | Create an `sk_live_` key with only the scopes you need. |
| **5** | Verify `X-SmsPro-Signature` on delivery webhooks. |
| **6** | Send an `Idempotency-Key` on every mutating `POST`. |
| **7** | Retry `429` and `503` with backoff, using the same idempotency key. |
---
## 1. Account profile [#1-account-profile]
Open [Account settings](https://smspro.com) after sign-in and save the display name and phone number. Email changes are done on the Authorisation Server.
The same page lists email, SMS, and marketing notification toggles. Marketing messages are held from 21:00 to 07:00 local time. Transactional messages and OTP are sent during those hours. That quiet-hours window applies to every account.
---
## 2. Request a Sender ID [#2-request-a-sender-id]
A custom alphanumeric sender name has to be approved before live traffic can use it.

1. Open **Sender ID** and choose **Request new sender ID** (`/customer/sender-id/request`).
2. Enter a name of up to 11 characters, the message types, and the purpose.
3. Attach supporting documents if you have them. They are optional.
4. Accept the Sender ID terms and submit.
5. The request stays **Pending** until it is **Approved**. A rejected request can be corrected and sent again. An approved name can later be revoked.
Send with a sender name that is already approved on the account.
---
## 3. Add credit [#3-add-credit]
Live segments draw on the wallet.
1. Open **Wallet** (`/customer/wallet`).
2. Use **Top Up Wallet** (`/customer/wallet/top-up`) or **Buy SMS Bundle** (`/customer/wallet/buy-bundle`).
3. Enter the amount and complete checkout.
---
## 4. Create a live key [#4-create-a-live-key]
1. Open **Developer > API Keys**.
2. Set **Environment** to **Live (`sk_live_`)**.
3. Choose the traffic class and enter an SMS allocation.
4. Select only the scopes the integration needs.
5. Optionally fill **IP whitelist**.
6. Click **Add API Key**, copy the secret from the banner, and store it outside the repository.
---
## 5. Secure Your Webhook Receiver [#5-secure-your-webhook-receiver]
When receiving asynchronous Delivery Receipts (`DLR`) in production, always verify the cryptographic signature in the `X-SmsPro-Signature` header to ensure payloads originate exclusively from SMS Pro:

```ts title="webhook-handler.ts"
import crypto from 'node:crypto';
export function verifyWebhookSignature(
rawPayload: string,
signatureHeader: string,
signingSecret: string,
): boolean {
const parts = Object.fromEntries(
signatureHeader.split(',').map((part) => {
const index = part.indexOf('=');
return [part.slice(0, index), part.slice(index + 1)];
}),
);
const timestamp = parts.t;
const expected = parts.v1;
if (!timestamp || !expected) return false;
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > 300) return false;
const computed = crypto
.createHmac('sha256', signingSecret)
.update(`${timestamp}.${rawPayload}`)
.digest('hex');
const left = Buffer.from(computed, 'utf8');
const right = Buffer.from(expected, 'utf8');
if (left.length !== right.length) return false;
return crypto.timingSafeEqual(left, right);
}
```
- Return HTTP `200` promptly.
- Do later work on your own job queue after you have verified the signature.
---
## 6. Switch the key [#6-switch-the-key]
```bash title=".env.production"
SMSPRO_BASE_URL=https://api.smspro.com
SMSPRO_API_KEY=sk_live_example
SMSPRO_WEBHOOK_SECRET=whsec_example
```
---
## 7. Check the first live message [#7-check-the-first-live-message]
1. Send one message to a phone you control.
2. Confirm the sender name and the text.
3. Open **Developer > API Logs** (`/customer/developer/api-logs`) and confirm `202`.
4. Watch the wallet on the dashboard. Account settings can send email and SMS alerts. There is no separate wallet-threshold page.
---
## Next [#next]
Continue with the [transactional SMS guide](/docs/guides/transactional-sms) and the [recipes](/docs/recipes).
---
# Introduction
URL: /docs/getting-started/introduction
> Overview of the SMS Pro Developer Platform, core messaging capabilities, integration protocols, and data formats.
Welcome to the **SMS Pro Developer Platform**. SMS Pro delivers carrier-grade direct telecommunications routing across Ghana and West Africa (supporting MTN, Telecel, and AT networks) with sub-second delivery latencies, zero-knowledge verification primitives, and enterprise reliability.
Whether you are dispatching mission-critical one-time passwords (OTPs), sending real-time transactional payment receipts, launching high-volume localized marketing campaigns, or automating customer surveys, our developer APIs provide a robust, modern foundation for your communication stack.
---
## Core Capabilities [#core-capabilities]
The SMS Pro platform exposes an extensive suite of public REST endpoints designed for speed, resilience, and developer ergonomics:
Single and batch messaging over dedicated high-priority carrier routes with sub-second delivery and automatic retry failovers.
Issue cryptographically hashed authentication challenges where the SMS Pro gateway never sees plaintext secrets.
Asynchronously fan out millions of messages with automated deduplication, opt-out filtering, and scheduled dispatch windows.
Receive real-time, HMAC-SHA256 signed delivery receipts directly into your application as carriers confirm handset delivery.
Generate trackable, branded micro-URLs that capture per-click analytics and user agent metadata while saving precious SMS character counts.
Schedule calendar-aware customer follow-ups and run interactive two-way SMS feedback loops with automated keyword parsing.
---
## Integration Architecture [#integration-architecture]
SMS Pro is built upon standard web protocols to integrate cleanly into any language, framework, or cloud environment:
| Protocol & Convention | Specification & Usage |
| :--- | :--- |
| **Transport** | Secure HTTPS (TLS 1.2 or 1.3 required on all inbound and outbound requests). |
| **API Architecture** | Standard RESTful design with predictable resource URLs and HTTP verbs (`GET`, `POST`, `PUT`, `DELETE`). |
| **Data Format** | Request and response payloads are formatted strictly as `application/json` with UTF-8 encoding. |
| **Error Handling** | RFC 7807 Problem Details (`application/problem+json`) with structured error codes and trace IDs. |
| **Idempotency** | Supported on all mutating `POST` endpoints via the `Idempotency-Key` header to safely retry requests without duplicates. |
| **Webhooks** | Outbound HTTP `POST` notifications signed with a SHA-256 HMAC digest in the `X-SmsPro-Signature` header. |
---
## API Versioning [#api-versioning]
All SMS Pro developer endpoints follow structured URI versioning:
```http
https://api.smspro.com/api/v1/public/...
```
- **Path prefix**: `/api/v1/public/` guarantees backward compatibility.
- **Breaking changes**: Breaking modifications (such as removing fields or altering required parameters) are never applied without a new major version prefix (e.g. `/api/v2/`).
- **Additive enhancements**: New optional request parameters, additional webhook events, or extra fields in response objects are introduced non-destructively within the existing version.
---
## What Developers Can Build [#what-developers-can-build]
With the SMS Pro platform, engineering teams frequently build:
1. **Authentication Workflows**: Secure two-factor authentication (2FA), passwordless magic logins, and password reset flows over prioritized telco channels.
2. **Fintech & Banking Notifications**: Real-time transaction alerts, instant debit/credit receipts, and compliance audit notifications.
3. **Logistics & Delivery Updates**: Automated dispatch milestones, courier arrival notifications, and live tracking short links.
4. **Healthcare & Appointment Reminders**: Scheduled reminders that reduce missed appointments and support interactive SMS confirmation replies.
5. **Customer Engagement Campaigns**: Personalized, segmented bulk messaging with custom sender IDs for promotions, announcements, and emergency notices.
---
## Next Steps [#next-steps]
To begin building on SMS Pro:
**Review the Prerequisites**
Check environment requirements, telecom standards, and supported tooling in [Prerequisites](/docs/getting-started/prerequisites).
**Register on the SMS Pro Platform**
Set up your account on the SMS Pro console as outlined in [Create an Account](/docs/getting-started/create-account).
**Enable the Developer Environment**
Unlock developer features and generate scoped API keys in [Developer Environment & API Keys](/docs/getting-started/create-application).
---
# Prerequisites
URL: /docs/getting-started/prerequisites
> Everything you need before making your first API request to the SMS Pro Gateway.
Before integrating with the SMS Pro platform, ensure you have gathered the required credentials, understand telecommunication formatting rules, and have a testing environment configured.
---
## 1. Account & Credential Requirements [#1-account--credential-requirements]
To call any SMS Pro endpoint, you will need:
- **An Active SMS Pro Account**: Registered on the [SMS Pro Platform](https://smspro.com) (see [Create an Account](/docs/getting-started/create-account)).
- **Developer Mode Enabled**: Your organization must toggle Developer Mode in account settings to reveal the developer tools and API management interfaces.
- **An API Key**: Either a Sandbox test key (`sk_test_...`) for zero-cost simulated testing, or a Live production key (`sk_live_...`) with required scopes such as `sms:send`.
Start with an `sk_test_` key. Those requests use the same API, do not charge the wallet, and do not send to a handset.
---
## 2. Telecommunication Formatting Standards [#2-telecommunication-formatting-standards]
SMS messaging over telco networks relies on specific international formatting, automatic number normalization, and character encoding rules:
### Flexible Phone Number Formats & Automatic Normalization [#flexible-phone-number-formats--automatic-normalization]
SMS Pro accepts local and international forms and cleans them on ingest. You do not need a separate normalizer in your application.
The platform natively accepts all of the following formats:
| Format Type | Input Example | Gateway Normalization | Status | Notes |
| :--- | :--- | :--- | :--- | :--- |
| **Local Format (with leading 0)** | `0241234567` | `233241234567` | **Supported** | Standard 10-digit Ghana local mobile number. The leading `0` is replaced with `233`. |
| **International (without `+`)** | `233241234567` | `233241234567` | **Supported** | 12-digit international format without leading plus. |
| **Standard E.164 (with `+`)** | `+233241234567` | `233241234567` | **Supported** | Standard E.164 with country dial code. |
| **National (9-digit)** | `241234567` | `233241234567` | **Supported** | 9-digit format omitting leading zero. The gateway prepends `233`. |
| **Formatted / Punctuation** | `+233 (24) 123-4567` or `024-123-4567` | `233241234567` | **Supported** | Spaces, dashes, and parentheses are automatically stripped before processing. |
Whether you pass `0241234567`, `233241234567`, or `+233241234567`, SMS Pro normalizes all inputs to the carrier-standard routing MSISDN (`233241234567`). In batch and campaign dispatches, duplicate representations of the same phone number in a single request are automatically consolidated.
### Invalid Number Rejections [#invalid-number-rejections]
A recipient number is rejected with HTTP `422` and `INVALID_PHONE_NUMBER` or `DESTINATION_COUNTRY_NOT_SUPPORTED` in these cases:
- **Incorrect Digit Count**: Local Ghana numbers starting with `0` that do not contain exactly 10 digits (e.g. `024123` or `024123456789`).
- **Unsupported Destination**: Submitting phone numbers for countries not currently activated in your organization's routing profile (e.g. attempting to send to a UK `+44` number when your account is configured for Ghana-only routing).
- **Empty / Non-numeric Inputs**: Strings containing no numeric digits.
### GSM-7 vs. UCS-2 Encoding & Segment Limits [#gsm-7-vs-ucs-2-encoding--segment-limits]
Carrier billing and SMS delivery rely on message segmentation:
- **Standard GSM-7 Encoding**: Plain alphanumeric characters, punctuation, and standard symbols support up to **160 characters** in a single SMS segment. Messages longer than 160 characters are automatically split into concatenated multi-part segments of **153 characters** each (due to concatenation headers).
- **UCS-2 (Unicode) Encoding**: If your message contains emojis, accents, or non-Latin scripts (Arabic, Chinese, Cyrillic), the carrier forces UCS-2 encoding. This restricts a single segment to **70 characters** (or **67 characters** per concatenated segment).
Adding a single emoji (such as 👋 or 🚀) converts the entire message payload from GSM-7 to UCS-2, reducing the segment threshold from 160 to 70 characters and increasing your billing unit consumption.
### Sender ID Guidelines [#sender-id-guidelines]
The `senderId` parameter designates the alphanumeric brand name displayed in the recipient's SMS inbox:
- Maximum length: **11 alphanumeric characters** (A-Z, a-z, 0-9).
- Special characters, spaces, and punctuation are restricted by telecom regulators.
- In production, telecom regulators (such as Ghana's NCA) mandate business registration and whitelisting before your custom Sender ID can route over live carrier channels.
- In the Sandbox environment, you can use any test Sender ID (e.g. `SMSPRO`, `MYAPP`).
---
## 3. Tooling & Development Environment [#3-tooling--development-environment]
SMS Pro communicates over standard HTTPS with JSON request bodies. The runtimes and utilities listed below are the ones used for the interactive code samples throughout this documentation:
### Documentation Sample Runtimes [#documentation-sample-runtimes]
- **cURL**: Command-line HTTP requests (native on macOS, Linux, and Windows PowerShell).
- **TypeScript / Node.js**: v18.0+ (supports native global `fetch` and `crypto.randomUUID()`).
- **Python**: v3.9+ with `requests` or `httpx`.
- **PHP**: v8.0+ with native `cURL` or `GuzzleHttp`.
- **Java**: v17+ with native `java.net.http.HttpClient` or `OkHttp`.
### Interactive API Testing Utilities [#interactive-api-testing-utilities]
- **Postman / Insomnia / Bruno**: For visual exploration, saving request collections, and inspecting response headers.
- **HTTPie**: Fast, human-friendly CLI HTTP client.
Because SMS Pro is a standard RESTful API over HTTPS, you can connect from **any** programming language or environment supporting TLS 1.2+ (including C# / .NET, Go, Ruby, Rust, Flutter, Dart, Swift, or Kotlin).
If your team requires code walkthroughs, sample boilerplates, or integration assistance in an environment not covered in these guides, please reach out to our [Developer Support Team](https://smspro.com) or open a ticket in your Customer Console.
---
## Next Step [#next-step]
Now that you understand the platform requirements and telecom conventions, follow the registration walkthrough in [Create an Account](/docs/getting-started/create-account).
---
# Testing in Sandbox
URL: /docs/getting-started/testing-in-sandbox
> Test with an sk_test_ key and magic phone numbers on the SMS Pro API.
Use an `sk_test_` key on `https://api.smspro.com` to exercise authentication, validation, and webhooks without contacting a handset or charging the wallet. The same numbers are on **Developer > Sandbox** (`/customer/developer/sandbox`).

---
## Test-key rules [#test-key-rules]
- The request is validated the same way as a live send.
- The response is `202` with status `ACCEPTED_SANDBOX` and a message id that starts with `sim_`.
- The wallet is not charged.
- A simulated delivery is posted to your webhook URL.
---
## Magic test numbers [#magic-test-numbers]
These numbers select the simulated outcome. They take the simulated path even when the key is `sk_live_`.

| Number | Simulated status |
| :--- | :--- |
| `+233200000001` | `DELIVERED` |
| `+233200000002` | `UNDELIVERABLE` |
| `+233200000003` | `EXPIRED` |
| `+233200000004` | `REJECTED_SPAM` |
`REJECTED_SPAM` is a sandbox result. Live traffic uses statuses such as `BLOCKED_SPAM`.
### Example [#example]
```bash
curl -X POST "https://api.smspro.com/api/v1/public/sms/send" \
-H "X-Api-Key: sk_test_example" \
-H "Content-Type: application/json" \
-d '{
"to": "+233200000004",
"senderId": "SMSPRO",
"message": "Testing spam rejection flow."
}'
```
The `202` body includes the simulated message id. The matching status is sent to your webhook. Do not expect a stored message lookup to return this simulation.
---
## Testing Webhooks & Delivery Receipts [#testing-webhooks--delivery-receipts]
In production, carrier networks send asynchronous Delivery Receipts (`DLR`) back to SMS Pro once a handset acknowledges receipt. SMS Pro forwards these events to your registered webhook URL.
### Testing Your Webhook Endpoint via CLI [#testing-your-webhook-endpoint-via-cli]
You can trigger a mock webhook ping to verify that your local webhook handler can receive, parse, and verify signatures without sending an actual message:
```bash
curl -X POST "https://api.smspro.com/api/v1/public/mfa/workflows/test-webhook" \
-H "X-Api-Key: sk_test_948f293048a1b2c3d4e5f60718" \
-H "Content-Type: application/json" \
-d '{
"webhookUrl": "https://api.yourdomain.com/webhooks/smspro",
"eventType": "SMS_DELIVERY_STATUS"
}'
```
The gateway immediately sends a simulated signed delivery receipt to your endpoint and returns the HTTP status code received from your server:
```json
{
"status": "success",
"data": {
"success": true,
"statusCode": 200,
"latencyMs": 48,
"webhookUrl": "https://api.yourdomain.com/webhooks/smspro"
}
}
```
---
## Balance [#balance]
`GET` the balance endpoint with your test key. It returns the account balance. Test sends do not reduce that balance.
---
## API logs [#api-logs]
Calls are listed in the [SMS Pro console](https://smspro.com) under **Developer > API Logs** (`/customer/developer/api-logs`). Open a row to see the request and response.
---
## Next Step [#next-step]
Once your integration handles sandbox requests and webhook events reliably, review the launch requirements in [Going Live](/docs/getting-started/going-live).
---
# Understanding Responses
URL: /docs/getting-started/understanding-responses
> Complete guide to SMS Pro API response envelopes, RFC 7807 error formats, HTTP status codes, rate limits, and retry strategies.
The SMS Pro API adheres to consistent, predictable JSON conventions across all endpoints. Every HTTP response is structured using standardized envelopes for both successful transactions and error conditions.
---
## 1. Successful Response Envelope [#1-successful-response-envelope]
All successful responses (`2xx` status codes) return the standard `ResourceResponse` envelope:
```json
{
"status": "success",
"message": "Human-readable summary of the operation",
"data": { ... }
}
```
### Key Envelope Fields [#key-envelope-fields]
- **`status`** *(string)*: Always `"success"`.
- **`message`** *(string)*: A concise summary of the outcome (e.g. `"Queued"`, `"Balance retrieved"`, `"Sender ID verified"`).
- **`data`** *(object | array)*: The requested resource object or array of items.
---
## 2. Error Response Envelope (RFC 7807) [#2-error-response-envelope-rfc-7807]
When an API call fails (`4xx` or `5xx` status codes), the gateway returns an **RFC 7807 Problem Details** document with `Content-Type: application/problem+json`:
```json
{
"type": "https://docs.smspro.com/errors/insufficient-credits",
"title": "INSUFFICIENT CREDITS",
"status": 402,
"detail": "Insufficient credits for this send.",
"instance": "/api/v1/public/sms/send",
"code": "INSUFFICIENT_CREDITS",
"message": "Insufficient credits for this send.",
"requestId": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
}
```
### Error Envelope Fields Explained [#error-envelope-fields-explained]
- **`type`** *(URI)*: A stable link referencing the error documentation.
- **`title`** *(string)*: A short, human-readable summary of the problem type.
- **`status`** *(number)*: The HTTP status code generated by the origin server.
- **`detail`** *(string)*: An explanation of the exact occurrence to assist in debugging.
- **`code`** *(string)*: A machine-readable application error code, such as `INSUFFICIENT_CREDITS`.
- **`requestId`** *(string)*: A unique correlation ID. Always supply this value when opening a support ticket with the SMS Pro engineering team.
- **`invalidParams`** *(array, optional)*: Present on `400 Bad Request` validation failures, detailing which fields failed schema checks:
```json
"invalidParams": [
{
"name": "to",
"reason": "For local Ghana numbers starting with 0, exactly 10 digits are required (e.g. 0241234567)."
}
]
```
---
## 3. HTTP Status Codes Reference [#3-http-status-codes-reference]
SMS Pro uses standard HTTP response codes to indicate the success or failure of an API request:
| Status Code | Meaning | Typical Scenario |
| :--- | :--- | :--- |
| **`200 OK`** | Success | `GET` requests (balance query, message status lookup) or synchronous `PUT`/`PATCH` updates. |
| **`201 Created`** | Created | Resource was created (e.g. creating a new shortlink or MFA policy). |
| **`202 Accepted`** | Queued | Asynchronous dispatch accepted. Message has entered the telco delivery pipeline. |
| **`400 Bad Request`** | Validation Error | Malformed JSON, missing required fields, or invalid E.164 phone numbers. |
| **`401 Unauthorized`** | Authentication Failure | Missing or invalid API key. An address outside an IP whitelist is also rejected as an invalid key. |
| **`402 Payment Required`** | Wallet Depleted | Insufficient prepaid SMS units or wallet balance to route the message. |
| **`403 Forbidden`** | Scope Failure | API key lacks the required scope (`FORBIDDEN_SCOPE`). |
| **`404 Not Found`** | Missing Resource | Requested message ID, job ID, or survey does not exist. |
| **`409 Conflict`** | Resource Conflict | Duplicate resource submission or concurrent modification lock. |
| **`422 Unprocessable`** | Semantic Error | Valid syntax, but a business rule failed. Key allocation uses `API_KEY_ALLOCATION_EXCEEDED`. |
| **`429 Too Many Requests`**| Rate Limited | Exceeded per-minute request threshold. Back off and retry. |
| **`500 Internal Error`** | Server Error | Unexpected failure. Retry the request with the same idempotency key. |
| **`503 Unavailable`** | Temporarily unavailable | Retry later. |
---
## 4. Application Error Codes [#4-application-error-codes]
When parsing errors programmatically, branch on the `code` property rather than parsing human-readable `detail` strings:
| Application Error Code | HTTP Status | Recommended Action |
| :--- | :--- | :--- |
| `UNAUTHORIZED` | 401 | The key is missing, unknown, or the caller is outside the IP whitelist. |
| `FORBIDDEN_SCOPE` | 403 | Add the missing scope, such as `sms:send`, on the key. |
| `API_KEY_ALLOCATION_EXCEEDED` | 422 | Raise the key's SMS allocation, or use another key. |
| `INVALID_PHONE_NUMBER` | 422 | The recipient is empty or not a usable number. |
| `INVALID_PHONE` | 422 | OTP and similar routes use this code for a missing or unusable number. |
| `DESTINATION_COUNTRY_NOT_SUPPORTED` | 422 | The destination country is not enabled for the account. |
| `INSUFFICIENT_CREDITS` | 402 | Add credit from Wallet, then retry with the same idempotency key. |
| `RATE_LIMIT_EXCEEDED` | 429 | Wait, then retry with the same idempotency key. |
| `TOO_MANY_REQUESTS` | 429 | Wait, then retry with the same idempotency key. |
---
## 5. Rate Limits & Headers [#5-rate-limits--headers]
Every API response from the public SMS routes includes these headers:
| Response Header | Description |
| :--- | :--- |
| `X-RateLimit-Limit` | Maximum number of requests allowed in the current 60-second window. |
| `X-RateLimit-Remaining` | Number of remaining calls available before hitting the rate limit. |
| `X-RateLimit-Reset` | Seconds left in the current one-minute window. |
| `Retry-After` | Present on `429` responses; number of seconds to wait before retrying. |
---
## 6. Recommended Retry Strategy [#6-recommended-retry-strategy]
When receiving transient errors (`429 Too Many Requests`, `500 Internal Server Error`, or `503 Service Unavailable`), follow an **exponential backoff with jitter** strategy:
1. **Check `Retry-After` Header**: If a `429` response provides a `Retry-After` header, wait for that duration before retrying.
2. **Preserve the `Idempotency-Key`**: Always send the exact same `Idempotency-Key` header on all retries. This ensures the SMS is never dispatched twice if the initial request succeeded behind a gateway timeout.
3. **Exponential Backoff Formula**: For network timeouts, compute sleep intervals using:
```text
wait_time = min(max_backoff, base_backoff * (2 ^ attempt)) ± jitter
```
4. **Never Retry 4xx Client Errors**: Never retry `400`, `401`, `402`, or `422` without altering the request payload or credentials, as these are permanent validation or authorization failures.
---
## Next Step [#next-step]
Explore mock telco testing, magic numbers, and delivery receipts in [Testing in Sandbox](/docs/getting-started/testing-in-sandbox).
---
# Architecture, Resiliency & Scale
URL: /docs/guides/architecture-and-resilience
> Production integration architecture covering queue-based decoupling, rate limiting, exponential backoff with jitter, and circuit breaker patterns.
Building a mission-critical SMS integration requires architecting for upstream network latency, rate limits, and carrier outages. Direct, blocking synchronous calls from your web request handlers to an external API introduce fragility and performance bottlenecks.
---
## 1. Recommended Production Architecture [#1-recommended-production-architecture]
Never call the SMS API from the user-facing request. Put the send on a queue in your application and let a worker call SMS Pro.

- The user request returns as soon as your queue accepts the job.
- If SMS Pro or the carrier is unavailable, the job stays in your queue.
- Pace the worker so it stays under the key's rate limit.
---
## 2. Rate Limits & Concurrency Management [#2-rate-limits--concurrency-management]
SMS Pro protects carrier signaling channels by enforcing rate limits per API key:
| Rate Limit Header | Description |
| :--- | :--- |
| `X-RateLimit-Limit` | Maximum number of requests permitted in the current 60-second window. |
| `X-RateLimit-Remaining` | Remaining request allowance in the current window. |
| `X-RateLimit-Reset` | Unix epoch timestamp (seconds) when the quota window resets. |
| `Retry-After` | Included on `429 Too Many Requests`; number of seconds to wait. |
### Client-Side Token Bucket Pacing [#client-side-token-bucket-pacing]
Configure your worker queues (e.g. BullMQ, Celery, or Sidekiq) to rate-limit outbound requests to stay comfortably beneath your tier threshold (e.g. `rate: { max: 100, duration: 1000 }` for 100 TPS).
---
## 3. Exponential Backoff with Full Jitter [#3-exponential-backoff-with-full-jitter]
When encountering transient network timeouts (`ETIMEDOUT`, `ECONNRESET`), HTTP `429 Too Many Requests`, or `503 Service Unavailable`, implement an **exponential backoff algorithm with full jitter**:
```text
wait_time = min(max_backoff, base_backoff * (2 ^ attempt)) ± jitter
```
### Why Jitter Is Essential [#why-jitter-is-essential]
Without jitter, hundreds of worker processes that encounter a transient rate limit at the exact same instant will back off for the exact same duration and retry simultaneously. This creates a **thundering herd** that repeatedly overwhelms the gateway. Adding random jitter desynchronizes the retries, allowing queues to drain smoothly.
---
## 4. Idempotency Key Preservation [#4-idempotency-key-preservation]
Whenever a worker retries an API request, it **must attach the identical `Idempotency-Key`**:
1. Worker picks up job `job_order_84920`.
2. Worker generates a stable UUID `c7a8b9e0-1234-5678-9abc-def012345678` tied to this job.
3. Worker sends request. Network drops before the HTTP response headers arrive.
4. Worker catches error and retries 2 seconds later using the **same** UUID.
5. The SMS Pro gateway recognizes the cached UUID and returns the original `202 Accepted` response without billing your wallet or sending a duplicate message.
---
## 5. Circuit Breaker Pattern [#5-circuit-breaker-pattern]
If downstream carrier networks experience a major disruption, repeatedly battering the endpoint will exhaust your worker connections. Implement a circuit breaker:
- **Closed (Normal)**: All traffic flows to SMS Pro normally.
- **Open (Failing)**: If the failure rate exceeds 25% over a 30-second window, the circuit trips **Open**. Outbound calls immediately fail fast or divert to local persistent storage without making network calls.
- **Half-Open (Testing)**: After a sleep window (e.g. 60 seconds), a single canary request is allowed through. If successful, the circuit closes; if it fails, the open state resets.
---
## Related Documentation [#related-documentation]
- 📖 [Message Lifecycle & Routing](/docs/guides/message-lifecycle-and-routing)
- 📖 [Error Handling & Diagnostics](/docs/guides/error-handling-and-troubleshooting)
- ⚡ [Recipe: Idempotent SMS Dispatch](/docs/recipes/idempotent-sms-dispatch)
---
# Automations
URL: /docs/guides/automations
> Reminders, birthdays, surveys, events, and short links in the console and on the public API.
These tools sit under **Automations** in the console. Each one also has a public API. Request bodies and response fields are in the [API Reference](/docs/api-reference).
---
## Console [#console]
| Tool | Route |
| :--- | :--- |
| Reminders | `/customer/reminders` |
| Birthdays | `/customer/birthdays` |
| Surveys | `/customer/surveys` |
| Events | `/customer/events` |
| Short links | `/customer/short-links` |
Event ticket scanning is at `/customer/events/:id/scanner`.
---
## Public API [#public-api]
Use `https://api.smspro.com` and an API key that includes the matching scope.
| Tool | Path | What it does |
| :--- | :--- | :--- |
| Reminders | `/api/v1/public/reminders` | Schedule a reminder, read it, or cancel the stages that have not run. |
| Birthdays | `/api/v1/public/birthdays` | Sync a contact birthday, or read birthday statistics. |
| Surveys | `/api/v1/public/surveys` | Create a survey, send the invitation, and read response metrics. |
| Events | `/api/v1/public/events` | Verify a ticket token, or look up a ticket. |
| Short links | `/api/v1/public/shortlinks` | Create a short link, list them, and read click analytics. |
Survey answers from a recipient use the public form and submit paths under `/api/v1/public/surveys`. Those calls do not use your API key.
---
## Quiet hours [#quiet-hours]
A reminder, birthday, or survey invitation that is marketing traffic is held from 21:00 to 07:00 local time. Transactional messages and OTP are not held.
---
# Bulk & Campaign Messaging
URL: /docs/guides/bulk-campaigns
> Submit asynchronous high-volume broadcast jobs, schedule future campaigns, and poll batch delivery progress.
For promotional broadcasts, billing reminders, or announcements exceeding 10 recipients, submit asynchronous batch jobs to `POST /api/v1/public/sms/bulk/jobs`.
## Submitting a Bulk Job [#submitting-a-bulk-job]
You can supply either an explicit `recipients` array, pre-saved contact `groupIds`, or a pre-uploaded CSV/Excel `fileId`:
```json title="POST /api/v1/public/sms/bulk/jobs"
{
"jobName": "November Promo Campaign",
"senderId": "SMSPRO",
"message": "Special offer! Use code PROMO50 today.",
"recipients": ["+233241234567", "+233501234567"],
"scheduledAt": "2026-11-20T09:00:00Z",
"deliveryCallbackUrl": "https://myapp.com/webhooks/dlr"
}
```
SMS Pro immediately validates the payload, reserves units, and returns HTTP `202 Accepted` with a `batchId` (`batch-7f9a2e41-0023`) and `status: "QUEUED"`.
## Tracking Batch Progress [#tracking-batch-progress]
Poll `GET /api/v1/public/sms/bulk/jobs/{batchId}` to monitor throughput and completion:
```json title="Batch progress response"
{
"batchId": "batch-7f9a2e41-0023",
"jobName": "November Promo Campaign",
"recipientCount": 2500,
"status": "PROCESSING",
"progressPercent": 78,
"sentCount": 1950,
"failedCount": 12,
"totalUnits": 2500
}
```
## Managing Scheduled & Running Jobs [#managing-scheduled--running-jobs]
- **List scheduled messages:** `GET /api/v1/public/sms/scheduled`
- **Cancel a scheduled broadcast:** `PATCH /api/v1/public/sms/scheduled/{id}`
- **Cancel an in-flight bulk job:** `PATCH /api/v1/public/sms/bulk/jobs/{jobId}`
- **Inspect campaign summaries:** `GET /api/v1/public/sms/campaigns`
---
# Delivery Reports (DLR) Deep Dive
URL: /docs/guides/delivery-reports-dlr
> Architectural mechanics of telecommunication delivery receipts, intermediate vs. terminal states, status mapping, and message correlation.
In telecommunications, a **Delivery Report (DLR)** is an out-of-band network packet generated by the recipient's mobile operator when a short message reaches a terminal state. For developers, DLRs provide the definitive audit trail proving whether an SMS physically reached a subscriber's device.
---
## 1. How Delivery Reporting Works [#1-how-delivery-reporting-works]
When your application calls the SMS Pro API, you receive an immediate acknowledgment (`202 Accepted`). However, confirmation of whether the message was actually displayed on the recipient's screen arrives later via the **DLR lifecycle**:

1. Your application receives `202 Accepted`.
2. The carrier later reports whether the handset received the message.
3. SMS Pro matches that report to `messageId`, signs the body, and posts it to your webhook.

---
## 2. DLR Status Mapping [#2-dlr-status-mapping]
Telecom carriers across West Africa (MTN, Telecel, AT) emit vendor-specific status codes (e.g. `DELIVRD`, `UNDELIV`, `EXPIRED`, `REJECTD`). SMS Pro normalizes these into consistent platform statuses:
| SMS Pro Status | Carrier Code | State Type | Technical Meaning |
| :--- | :--- | :--- | :--- |
| **`SENT`** | `ENROUTE` / `ACCEPTD` | Intermediate | Message is queued at the carrier SMSC awaiting air interface transmission. |
| **`DELIVERED`** | `DELIVRD` | **Terminal** | Handset confirmed physical receipt. Message successfully landed on device. |
| **`UNDELIVERED`** | `UNDELIV` | **Terminal** | The number could not be delivered. |
| **`EXPIRED`** | `EXPIRED` | **Terminal** | The handset stayed unreachable until the message expired. |
| **`BLOCKED_SPAM`** | content filter | **Terminal** | The message was blocked as spam. |
| **`FAILED`** | routing failure | **Terminal** | The message was not delivered. |
Telecommunication carriers can charge once a message is accepted for delivery. A later `UNDELIVERED` or `EXPIRED` status does not always return the unit.
---
## 3. Understanding Delivery Report Latency [#3-understanding-delivery-report-latency]
DLR delivery is not instantaneous. Typical latency distributions:
- **Immediate Delivery (70-85% of traffic)**: Reaches handset within **1 to 5 seconds**.
- **Transient Network Delays (10-15%)**: Reaches handset within **10 to 60 seconds** due to radio interference, tower handover, or localized network congestion.
- **Extended Delay (3-5%)**: Takes **minutes to hours** if the subscriber's phone is in airplane mode, driving through a coverage dead zone, or powered off.
### When Delivery Reports Are Missing [#when-delivery-reports-are-missing]
In rare scenarios, a message may be delivered to a handset, but the developer never receives a `DELIVERED` DLR:
1. **International Roaming**: When a subscriber roams onto a foreign network, the foreign carrier's visited SMSC may not support reciprocal DLR signaling back to the home network.
2. **Legacy Feature Phones**: Older 2G handsets occasionally fail to return radio-layer acknowledgments during low-battery states.
3. **SMSC Buffer Flush**: During rare carrier disaster recovery events, unacknowledged receipts in transit may be purged.
**Recommendation**: Do not hold critical user workflows in a blocking state waiting for terminal DLRs. Treat DLRs as asynchronous telemetry.
---
## 4. Message Correlation Architecture [#4-message-correlation-architecture]
To track messages across their lifecycle, your application must correlate three identifiers:
| Identifier | Source | Purpose |
| :--- | :--- | :--- |
| **`clientReference`** | Your Application | Your internal domain ID (e.g. `order_89201`, `auth_attempt_482`). |
| **`messageId`** | SMS Pro Gateway | UUID returned in the `202 Accepted` response. Identifies the specific recipient dispatch. |
| **`jobId`** | SMS Pro Gateway | Identifies the overall submission job (for bulk sends, one job encompasses many messages). |
### Recommended Database Schema [#recommended-database-schema]
When dispatching an SMS, store the `messageId` alongside your domain entity:
```sql
CREATE TABLE outgoing_sms (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
order_id UUID REFERENCES orders(id),
recipient_phone VARCHAR(20) NOT NULL,
message_id UUID UNIQUE, -- Returned by SMS Pro 202 response
status VARCHAR(32) DEFAULT 'QUEUED', -- ACCEPTED, SENT, DELIVERED, FAILED
delivered_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
```
When an inbound webhook arrives containing `messageId`, execute an idempotent update:
```sql
UPDATE outgoing_sms
SET status = 'DELIVERED', delivered_at = NOW()
WHERE message_id = 'c7a8b9e0-1234-5678-9abc-def012345678'
AND status != 'DELIVERED';
```
---
## Related Documentation [#related-documentation]
- 📖 [Webhooks & Event Notifications](/docs/guides/webhooks-and-dlr)
- ⚡ [Recipe: Verify Inbound Webhooks](/docs/recipes/verify-webhooks)
- 🔌 [API Reference: Query Message Statuses](/docs/api-reference/transactional-sms/queryMessageStatuses)
---
# Error Handling & Diagnostics
URL: /docs/guides/error-handling-and-troubleshooting
> Comprehensive technical troubleshooting guide covering RFC 7807 error taxonomy, carrier failure diagnostics, and request tracing.
When integrating telecommunication services, distinguishing between **API-layer failures** (e.g. invalid authentication or schema violations) and **telecom-layer failures** (e.g. handset out of coverage or spam filtering) is critical to diagnosing issues quickly.
---
## 1. Error Taxonomy & Layering [#1-error-taxonomy--layering]
Errors in SMS Pro originate at three distinct architectural tiers:

---
## 2. RFC 7807 Problem Details Format [#2-rfc-7807-problem-details-format]
All synchronous API errors return structured JSON using the RFC 7807 `application/problem+json` standard:
```json
{
"type": "https://docs.smspro.com/errors/invalid-phone",
"title": "Invalid Recipient Phone Number",
"status": 400,
"detail": "For local Ghana numbers starting with 0, exactly 10 digits are required (e.g. 0241234567). Given: 024123",
"code": "INVALID_PHONE_NUMBER",
"instance": "/api/v1/public/sms/send",
"requestId": "req-9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
"timestamp": "2026-11-18T09:15:00Z"
}
```
### Essential Diagnostic Fields [#essential-diagnostic-fields]
- **`code`**: A stable, machine-readable enum. Write application branching logic against `code`, never by parsing `detail` strings.
- **`requestId`**: The unique trace ID generated at the gateway edge. Quote this ID when submitting support tickets or searching console logs.
- **`invalidParams`**: A detailed array identifying specific field validation errors on `400` responses.
---
## 3. Comprehensive Application Error Codes [#3-comprehensive-application-error-codes]
| Application Code | HTTP Status | Root Cause | Resolution |
| :--- | :--- | :--- | :--- |
| **`UNAUTHORIZED`** | `401` | The key is missing, unknown, or the caller is outside the IP whitelist. | Check the key and the whitelist. |
| **`FORBIDDEN_SCOPE`** | `403` | The key lacks the required scope. | Edit scopes under **Developer > API Keys**. |
| **`API_KEY_ALLOCATION_EXCEEDED`** | `422` | The key has used its SMS allocation. | Raise the allocation or use another key. |
| **`INVALID_PHONE`** | `422` | The phone number is missing or not a usable number. | Send a local or international number SMS Pro can clean. |
| **`RATE_LIMIT_EXCEEDED`** | `429` | The key is over its per-minute limit. | Wait for `Retry-After`, then retry with the same idempotency key. |
---
## 4. Diagnosing Common Integration Anomalies [#4-diagnosing-common-integration-anomalies]
### Anomaly 1: "Subscribers are receiving duplicate text messages" [#anomaly-1-subscribers-are-receiving-duplicate-text-messages]
- **Cause**: Your application is timing out waiting for an HTTP response, catching an error, and retrying the request **without** an `Idempotency-Key`. The initial request succeeded on the gateway, and the retry sent a second message.
- **Fix**: Always generate a unique `Idempotency-Key` (UUID v4) for each logical message. When retrying network drops, send the **same** key. SMS Pro will return the cached response rather than queueing a second message.
### Anomaly 2: "Messages report `SENT`, but no Delivery Report arrives" [#anomaly-2-messages-report-sent-but-no-delivery-report-arrives]
- **Cause**: The subscriber's handset is powered off, out of signal range, or roaming on a network with delayed DLR forwarding.
- **Fix**: Check `GET /api/v1/public/sms/messages/{messageId}`. If the message remains in `SENT`, the carrier SMSC is still attempting delivery within its 24-hour validity window.
### Anomaly 3: "A 160-character message was billed as 3 units" [#anomaly-3-a-160-character-message-was-billed-as-3-units]
- **Cause**: An invisible Unicode character (such as an emoji, non-breaking space, or curly apostrophe `’`) forced the message into **UCS-2 encoding**, reducing the capacity to 70 characters per segment.
- **Fix**: Run dynamic text through a GSM-7 sanitizer or inspect the `segmentCount` in the `202 Accepted` response.
---
## Related Documentation [#related-documentation]
- 📖 [Delivery Reports (DLR) Deep Dive](/docs/guides/delivery-reports-dlr)
- 📖 [Architecture, Resiliency & Scale](/docs/guides/architecture-and-resilience)
- ⚡ [Recipe: Idempotent SMS Dispatch](/docs/recipes/idempotent-sms-dispatch)
---
# Developer Guides
URL: /docs/guides
> Comprehensive technical knowledge base for understanding, integrating, and operating the SMS Pro Messaging Platform.
Welcome to the **SMS Pro Developer Guides**. Unlike quickstarts or copy-paste recipes, this section provides the technical knowledge, telecommunication principles, architectural mental models, and production best practices required to build mission-critical, carrier-grade messaging integrations.
---
## Guide Categories [#guide-categories]
Explore our technical guides organized by engineering domain:
---
## How to Use These Guides [#how-to-use-these-guides]
- **Building a New Integration?** Start with [SMS Fundamentals](/docs/guides/sms-fundamentals) and [Message Lifecycle & Routing](/docs/guides/message-lifecycle-and-routing) to understand message segmentation and delivery guarantees.
- **Handling Inbound Callbacks?** Review [Delivery Reports (DLR)](/docs/guides/delivery-reports-dlr) and [Webhooks & Event Notifications](/docs/guides/webhooks-and-dlr).
- **Looking for Concrete Code Samples?** If you need ready-to-run, split-pane code in Node.js, Python, PHP, or Java, explore our [Interactive Recipes](/docs/recipes).
- **Need Endpoint Schemas?** Check the interactive OpenAPI playground in the [API Reference](/docs/api-reference).
---
# Message Lifecycle & Routing
URL: /docs/guides/message-lifecycle-and-routing
> Submission acceptance, later delivery, traffic classes, and message statuses.
A common misconception among developers new to telecommunications is assuming that receiving an HTTP `200` or `202` response means the recipient's mobile phone has buzzed. In reality, SMS operates as an asynchronous, distributed store-and-forward system.
---
## 1. Submission Acceptance vs. Handset Delivery [#1-submission-acceptance-vs-handset-delivery]
The transmission of an SMS is bifurcated into two distinct phases:

### Phase 1: Acceptance [#phase-1-acceptance]
- The API checks the key, the body, the numbers, and the idempotency key.
- It returns **HTTP `202 Accepted`** with a `messageId`. That means SMS Pro has accepted the message. It does not mean the handset has it yet.
### Phase 2: Delivery [#phase-2-delivery]
- The carrier delivers the message.
- SMS Pro later posts a signed webhook with the terminal status.
---
## 2. Ingestion Pipeline & Architecture [#2-ingestion-pipeline--architecture]
When you call `POST /api/v1/public/sms/send`, SMS Pro checks the key, validates the body, and returns `202 Accepted`. Delivery happens after that response.

---
## 3. Traffic Classes & Priority Queuing [#3-traffic-classes--priority-queuing]
Set the traffic class on the API key so verification messages are not held behind a large broadcast.
| Traffic class | Use it for |
| :--- | :--- |
| **OTP and 2FA** | One-time passwords and MFA. |
| **Transactional** | Receipts, booking updates, and account alerts. |
| **Marketing** | Promotions and announcements. |
A marketing broadcast does not have to delay OTP traffic. Put verification on an OTP key and broadcasts on a marketing key.
---
## 4. The Message State Machine [#4-the-message-state-machine]
Statuses you can see on a message:

### While it is moving [#while-it-is-moving]
`PENDING`, `QUEUED`, `IN_PROGRESS`, `SENT`, `ENROUTE`, and `ACCEPTED`.
### When it is finished [#when-it-is-finished]
`DELIVERED`, `UNDELIVERED`, `EXPIRED`, `FAILED`, `FAILED_DLQ`, `REJECTED`, `BLOCKED`, `BLOCKED_SPAM`, and `CANCELLED`.
`REJECTED_SPAM` and `UNDELIVERABLE` are results of the sandbox magic numbers. Live content filtering is reported as `BLOCKED_SPAM`.
---
## 5. Validity Periods & Message Expiry [#5-validity-periods--message-expiry]
When a recipient handset is out of coverage or turned off, the carrier SMSC stores the message and periodically retries delivery.
- **Default Validity Timer (TTL)**: **24 hours**.
- **Retry Schedule**: Carriers typically retry with an initial burst (after 1 minute, 5 minutes, 15 minutes), transitioning to hourly polling.
- **Expiry Transition**: If the subscriber does not reconnect within the validity window, the SMSC drops the message from its buffer and emits an `EXPIRED` status receipt.
---
## Related Documentation [#related-documentation]
- 📖 [Delivery Reports (DLR) Deep Dive](/docs/guides/delivery-reports-dlr)
- 📖 [Webhooks & Event Notifications](/docs/guides/webhooks-and-dlr)
- ⚡ [Recipe: Verify Inbound Webhooks](/docs/recipes/verify-webhooks)
---
# OTP & Zero-Knowledge MFA
URL: /docs/guides/otp-and-zero-knowledge-mfa
> Compare turnkey v1 OTP with v2 Zero-Knowledge SHA-256 Challenge-Response verification and automatic WhatsApp-to-SMS failover.
SMS Pro provides two verification tiers: **v1 Turnkey OTP/MFA** for rapid integration and **v2 Zero-Knowledge Challenge-Response** for security-sensitive fintech and enterprise applications.
## Zero-Knowledge Nonce Proof Protocol (v2) [#zero-knowledge-nonce-proof-protocol-v2]
On v2 endpoints (`POST /api/v2/public/otp/verify` and `POST /api/v2/public/mfa/verify`), raw user-entered PIN codes are **never transmitted over HTTP**:
1. **Challenge Issuance:** `POST /api/v2/public/otp/send` delivers the numeric PIN out-of-band to the user's phone and returns a 128-bit single-use `challengeNonce` (32 hex chars) to your backend/client.
2. **Canonical String Construction:** Concatenate normalized nonce and user PIN:
```text
canonical = challengeNonce.trim().toLowerCase() + ":" + userCode.trim().toLowerCase()
```
3. **Cryptographic Proof:** Compute lowercase hex SHA-256 over the canonical string:
```text
codeProof = hex(sha256(canonical))
```
4. **Verification:** Submit `challengeNonce` (or `otpId`) and `codeProof` to `/api/v2/public/otp/verify`. The proof is checked once and cannot be reused.
Follow the step-by-step code walkthrough in the [Zero-Knowledge OTP Verification Recipe](/docs/recipes/zero-knowledge-otp).
## Multi-Factor Authentication (MFA) Policies [#multi-factor-authentication-mfa-policies]
Create reusable verification policies via `POST /api/v1/public/mfa/workflows` to standardize:
- `codeLength`: `4` to `8` digits
- `expiryMinutes`: `1` to `60` minutes
- `maxAttempts`: `1` to `10` verification attempts
- `resendCooldownSeconds`: `10` to `300` seconds
- `channel`: `SMS`, `WHATSAPP`, or `AUTO_FAILOVER`
- `defaultProofMode`: `CHALLENGE_RESPONSE` or `PLAIN`
## Automatic WhatsApp-to-SMS Failover [#automatic-whatsapp-to-sms-failover]
When a workflow or OTP challenge starts over WhatsApp and the subscriber fails to receive or confirm within the delivery window, call `POST /api/v2/public/otp/failover` (or `POST /api/v1/public/otp/failover`) to immediately fall back to carrier SMS (`channelDelivered: "SMS_FAILOVER"`).
---
# Sender ID Management & Compliance
URL: /docs/guides/sender-id-and-compliance
> Request an alphanumeric sender name, the approval statuses, and what the request form collects.
A sender ID is the name shown on the handset. On SMS Pro it is an alphanumeric name of up to 11 characters, such as `MYBRAND`.
---
## 1. Request form [#1-request-form]
Open **Sender ID** and choose **Request new sender ID** (`/customer/sender-id/request`).

| Field | Required | What to enter |
| :--- | :--- | :--- |
| **Sender ID** | Yes | Up to 11 characters. The placeholder is `MYBRAND`. |
| **Type** | Yes | Transactional, Promotional, Marketing, OTP, or all of them. |
| **Purpose** | Yes | What the messages are for. |
| **Supporting documents** | No | PDF, JPG, PNG, DOC, or DOCX. |
| **Terms** | Yes | Accept the Sender ID terms before submit. |
The terms on the form say the name is used only for the stated purpose, that messages follow applicable SMS laws and NCA regulations, and that spam is prohibited. The name is not used for sending until the terms are accepted after approval.
---
## 2. Statuses [#2-statuses]

| Status | Meaning |
| :--- | :--- |
| **`PENDING`** | The request is waiting for review. |
| **`APPROVED`** | The name can be used on live sends. |
| **`REJECTED`** | The request was not approved. Correct it and submit again. |
| **`REVOKED`** | An approved name was withdrawn. |
---
## 3. Quiet hours [#3-quiet-hours]
Marketing messages are held from 21:00 to 07:00 local time. Transactional messages and OTP are not held. Account settings shows this window. It applies to every account.
---
## Related documentation [#related-documentation]
- [Going Live](/docs/getting-started/going-live)
- [API Reference: Validate Compliance](/docs/api-reference/compliance-validation/validateCompliance)
---
# SMS Fundamentals & Encoding
URL: /docs/guides/sms-fundamentals
> Telecommunication network architecture, GSM-7 vs. UCS-2 character sets, segmentation math, and automatic phone normalization.
Short Message Service (SMS) is a store-and-forward message. This page covers how a message moves from your app to a handset, how encoding changes the segment count, and how phone numbers are cleaned on the way in.
---
## 1. Path of a message [#1-path-of-a-message]

SMS Pro accepts the API call. The carrier delivers the SMS. The handset result comes back later as a delivery status.
---
## 2. Character Encodings: GSM-7 vs. UCS-2 [#2-character-encodings-gsm-7-vs-ucs-2]
Every character in an SMS payload is encoded as either **GSM 7-bit default alphabet** or **UCS-2 (16-bit Unicode)**. This distinction directly controls message segment capacity and billing units.
### GSM 7-bit Encoding (Standard) [#gsm-7-bit-encoding-standard]
The GSM 03.38 standard defines 128 basic characters (A-Z, a-z, 0-9, standard punctuation, and select Greek symbols). Because each character requires only 7 bits of data, a standard 140-byte telecommunication signaling packet holds up to **160 characters**.
- **Single Segment Maximum**: **160 characters**.
- **Concatenated Segment Maximum**: **153 characters** (7 bytes are consumed by the User Data Header for reassembly).
### UCS-2 Encoding (Unicode) [#ucs-2-encoding-unicode]
If an SMS payload contains even a single character outside the GSM-7 table (such as an emoji 👋, accented character, Arabic, Chinese, or specialized punctuation like curly quotes `“`), the entire message must be encoded using **UCS-2**.
Each character in UCS-2 requires 16 bits (2 bytes). This drastically reduces the capacity of a 140-byte signaling packet:
- **Single Segment Maximum**: **70 characters**.
- **Concatenated Segment Maximum**: **67 characters** (6 bytes are consumed by the User Data Header).
| Metric | GSM 7-bit Encoding | UCS-2 Unicode Encoding |
| :--- | :--- | :--- |
| **Bits Per Character** | 7 bits | 16 bits (2 bytes) |
| **Single Message Capacity** | **160 characters** | **70 characters** |
| **Multi-Part Segment Capacity**| **153 characters / segment** | **67 characters / segment** |
| **Trigger Characters** | Latin letters, numbers, standard symbols | Emojis (🚀), smart quotes (“”), non-Latin alphabets |
| **Billing Impact** | 1 unit per 160 chars | 1 unit per 70 chars (**~2.3x more units**) |
A 150-character plain text message is billed as **1 SMS unit**. Adding a single emoji converts the message to UCS-2, splitting the 151 characters into **3 concatenated segments** (67 + 67 + 17 characters), tripling your unit cost.
---
## 3. SMS Segmentation & Concatenation [#3-sms-segmentation--concatenation]
When a message exceeds the single-segment threshold, the SMS Pro gateway divides the text into concatenated segments. Each segment includes a 6-byte **User Data Header (UDH)**:
- **UDH Contents**: Information Element Identifier (IEI), CSMS reference number, total segment count (N), and current segment index (n).
- **Handset Reassembly**: The receiving mobile device buffers the incoming segments, orders them using the UDH sequence numbers, and displays them as a single seamless text to the user.
### Segmentation Calculation Example (GSM-7) [#segmentation-calculation-example-gsm-7]
```text
segments = length <= 160 ? 1 : Math.ceil(length / 153)
```
- Length = 160 characters $\to$ **1 segment** (160 used).
- Length = 161 characters $\to$ **2 segments** (153 + 8 used).
- Length = 306 characters $\to$ **2 segments** (153 + 153 used).
- Length = 307 characters $\to$ **3 segments** (153 + 153 + 1 used).
---
## 4. Phone Number Normalization & E.164 [#4-phone-number-normalization--e164]
SMS Pro cleans numbers on ingest:

### Supported Input Formats [#supported-input-formats]
- **Local with leading zero** (`0241234567`): 10 digits; leading `0` is replaced with national dial code `233`.
- **National without zero** (`241234567`): 9 digits; prepends national dial code `233`.
- **International without plus** (`233241234567`): 12 digits; validated and preserved.
- **E.164 with plus** (`+233241234567`): The leading `+` is removed.
- **Punctuation & Spaces** (`+233 (24) 123-4567`): All non-digit characters are automatically stripped.
### Automatic Deduplication [#automatic-deduplication]
If an API request or campaign file lists both `0241234567` and `+233241234567`, the engine detects identical normalized MSISDNs and deduplicates the recipient to prevent duplicate message delivery and billing.
---
## 5. Architectural Best Practices [#5-architectural-best-practices]
1. **Sanitize Dynamic Template Inputs**: If inserting user names or external database strings into SMS templates, strip invisible non-GSM characters (e.g. zero-width spaces or smart quotes) to prevent unintended UCS-2 conversion.
2. **Pre-Calculate Segment Counts**: Check the `segmentCount` in the `202 Accepted` response to monitor billing consumption in real time.
3. **Use Shortlinks for Long URLs**: URLs consume massive character counts. Use SMS Pro Branded Shortlinks to condense links to under 20 characters while gaining click analytics.
---
## Related Documentation [#related-documentation]
- 📖 [Message Lifecycle & Routing](/docs/guides/message-lifecycle-and-routing)
- ⚡ [Recipe: Idempotent SMS Dispatch](/docs/recipes/idempotent-sms-dispatch)
- 🔌 [API Reference: Send SMS](/docs/api-reference/transactional-sms/sendSms)
---
# Transactional SMS & Encoding
URL: /docs/guides/transactional-sms
> High-priority single and multi-recipient SMS dispatch, GSM-7 vs. UCS-2 segment billing, and Sender ID rules.
Use the transactional messaging endpoint (`POST /api/v1/public/sms/send`) for latency-sensitive notifications such as login alerts, payment confirmations, and order updates.
## Single vs. Multi-Recipient Dispatch [#single-vs-multi-recipient-dispatch]
The transactional endpoint supports **1 to 10 deduplicated recipients** per request via `to` (single MSISDN) or `recipients` (up to 10 numbers or comma-separated string).
```json title="Multi-recipient request body"
{
"recipients": "+233241234567,+233501234567",
"senderId": "SMSPRO",
"message": "Order #4821 has shipped and arrives tomorrow.",
"deliveryCallbackUrl": "https://myapp.com/webhooks/dlr"
}
```
If you need to target more than 10 recipients in a single API call, use the asynchronous [Bulk & Campaign Messaging](/docs/guides/bulk-campaigns) endpoint (`/api/v1/public/sms/bulk/jobs`).
## Character Encoding & Segment Math [#character-encoding--segment-math]
Telco carriers bill SMS by **segment**. SMS Pro inspects your payload automatically and selects either GSM-7 or UCS-2 (Unicode) encoding:
| Encoding | Single Segment Limit | Concatenated Segment Size | Triggered By |
| :--- | :--- | :--- | :--- |
| **GSM-7** | `160` characters | `153` characters / part | Standard Latin letters, numbers, basic symbols |
| **UCS-2 (Unicode)** | `70` characters | `67` characters / part | Emoji, accented non-GSM characters, curly quotes |
Pre-flight character count and compliance checks are available via `POST /api/v1/public/sms/validate` and `POST /api/v1/public/sms/validate-recipients` before dispatching live traffic.
## Alphanumeric Sender IDs [#alphanumeric-sender-ids]
- Alphanumeric Sender IDs (`senderId`) support up to **11 characters** (for example `SMSPRO` or `CLINIC`).
- Ensure your Sender ID is registered and approved in the SMS Pro Dashboard before sending to carrier networks that enforce strict sender whitelisting.
## Polling Message History & Status [#polling-message-history--status]
- Query a single message by ID: `GET /api/v1/public/sms/messages/{messageId}`
- Paginate dispatch history: `GET /api/v1/public/sms/history`
- Filter by date range or status: `GET /api/v1/public/sms/history/search`
---
# Wallet, Billing & Usage Accounting
URL: /docs/guides/wallet-and-billing
> Understand prepaid unit deduction mechanics, segment-based billing math, insufficient balance handling, and programmatic wallet queries.
SMS Pro operates on a transparent **Prepaid Wallet & Credit Allocation** model. Billing is strictly correlated to the telecommunication infrastructure resources consumed by your messages.
---
## 1. How SMS Billing Is Calculated [#1-how-sms-billing-is-calculated]
The cost of any outbound SMS transmission is determined by three variables:
1. **Number of Recipients**: Total count of distinct normalized phone numbers.
2. **Segment Count**: Determined by the character length and encoding scheme (GSM-7 vs. UCS-2).
3. **Destination Rate**: Country-specific unit pricing (Ghana domestic vs. international roaming destinations).
### Unit Billing Formula [#unit-billing-formula]
```text
total_billable_units = unique_recipients * calculated_segments * destination_rate
```
### Practical Billing Scenarios [#practical-billing-scenarios]
| Use Case | Recipient Count | Character Count | Encoding | Segment Count | Billable Units |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **Simple Auth OTP** | 1 recipient | 48 characters | GSM-7 | 1 segment | **1 unit** |
| **Order Receipt (Plain)** | 1 recipient | 155 characters | GSM-7 | 1 segment | **1 unit** |
| **Order Receipt (+ Emoji 📦)**| 1 recipient | 156 characters | **UCS-2** | **3 segments** | **3 units** |
| **Flash Sale Broadcast** | 5,000 recipients | 140 characters | GSM-7 | 1 segment | **5,000 units** |
| **Long Marketing Notice** | 10,000 recipients | 280 characters | GSM-7 | **2 segments** | **20,000 units** |
---
## 2. Programmatic Wallet Balance Queries [#2-programmatic-wallet-balance-queries]
Call `GET /api/v1/public/sms/balance`. The same payload is available from `POST /api/v1/public/sms/balance`. The response is the account balance. A test key does not return a separate sandbox balance.
```http
GET /api/v1/public/sms/balance HTTP/1.1
Host: api.smspro.com
X-Api-Key: sk_live_example
```
```json
{
"status": "success",
"message": null,
"data": {
"paygBalance": 0,
"bundleRemaining": 2400,
"unit": "SMS"
}
}
```
- **`paygBalance`**: Returned as `0` on this endpoint.
- **`bundleRemaining`**: The account SMS credit balance.
- **`unit`**: `SMS`.
---
## 3. Handling Insufficient Balance (`HTTP 402`) [#3-handling-insufficient-balance-http-402]
If your wallet lacks the credits required to service an API dispatch, the gateway **rejects the entire request atomically**:
```json
{
"type": "https://docs.smspro.com/errors/insufficient-credits",
"title": "INSUFFICIENT CREDITS",
"status": 402,
"detail": "Insufficient credits for this send.",
"instance": "/api/v1/public/sms/send",
"code": "INSUFFICIENT_CREDITS",
"message": "Insufficient credits for this send.",
"requestId": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
}
```
### Architectural Guarantees [#architectural-guarantees]
- **Atomic Rejection**: In batch requests, SMS Pro never performs partial sends if balance is insufficient. The entire request fails so your application does not end up in an inconsistent state.
- **Zero Debt**: Accounts cannot run into negative balances. Dispatches halt cleanly until a wallet top-up is processed.
---
## 4. Wallet Top-Up Methods [#4-wallet-top-up-methods]
Add credit from the [SMS Pro console](https://smspro.com):
- **Top up** at `/customer/wallet/top-up`.
- **Buy a bundle** at `/customer/wallet/buy-bundle`.
- History is at `/customer/wallet/history`.
Account settings can send email and SMS alerts. Watch the wallet balance on the dashboard as well.
---
## Related Documentation [#related-documentation]
- 📖 [SMS Fundamentals & Encoding](/docs/guides/sms-fundamentals)
- 📖 [Error Handling & Diagnostics](/docs/guides/error-handling-and-troubleshooting)
- 🔌 [API Reference: Get Account Balance](/docs/api-reference/authentication-balance/getBalance)
---
# Webhooks & Delivery Reports
URL: /docs/guides/webhooks-and-dlr
> Receive signed delivery receipts (DLR), opt-out events, and inbound MO messages with X-SmsPro-Signature verification.
SMS Pro posts a signed JSON body to your webhook when a delivery status is ready. Read `status` on that body.
```json title="Delivery status body"
{
"messageId": "c7a8b9e0-1234-5678-9abc-def012345678",
"providerMessageId": "provider-1001",
"to": "233241234567",
"status": "DELIVERED",
"deliveredAt": "2026-11-18T08:15:04Z",
"gateway": "carrier",
"raw": ""
}
```
## Verifying `X-SmsPro-Signature` [#verifying-x-smspro-signature]
Every outbound webhook includes an `X-SmsPro-Signature` header signed with your webhook secret (`whsec_...`):
```http
X-SmsPro-Signature: t=1730462400,v1=5d41402abc4b2a76b9719d911017c592a187383fe52e2e7b57b6f634571999a3
```
Verification requirements:
1. **Read raw bytes/string:** Never re-serialize parsed JSON (`JSON.stringify(req.body)`); whitespace or key-order changes break the HMAC digest.
2. **Construct signed string:** Concatenate `` `${timestamp}.${rawRequestBody}` ``.
3. **Compute HMAC-SHA256:** Hash with your `whsec_...` secret as lowercase hex.
4. **Enforce anti-replay window:** Reject payloads whose timestamp differs from current Unix time by more than `300` seconds (5 minutes).
5. **Constant-time comparison:** Compare the hex digests only when they are the same length. Use `crypto.timingSafeEqual` in Node.js. In Java, compare equal-length digests with `MessageDigest.isEqual`.
Walk through a production-ready Next.js Route Handler verifier in the [Verify Delivery Report Webhooks Recipe](/docs/recipes/verify-webhooks).
## MFA Callback Signatures (`X-MFA-Signature`) [#mfa-callback-signatures-x-mfa-signature]
MFA workflow webhooks (`mfa.challenge.created`, `mfa.challenge.verified`, `mfa.challenge.test`) transmit `X-MFA-Signature: sha256=`, computed directly over the raw JSON body with the workflow's `webhookSecret`.
## Endpoint Reliability & Retries [#endpoint-reliability--retries]
- Respond with any `2xx` status code within **5 seconds**.
- Enqueue heavy database or notification side effects asynchronously after signature verification.
- Non-2xx responses or timeouts are retried. Failed deliveries are listed under **Developer > Webhooks**.
---
# SMS Pro Developer Documentation
URL: /docs
> Carrier-grade transactional SMS, bulk campaigns, Zero-Knowledge OTP/MFA, and real-time webhook telemetry across African and global telco networks.
Welcome to the **SMS Pro Developer Portal**. Build reliable messaging workflows using the REST API, test with an `sk_test_` key, and verify delivery reports with HMAC-SHA256 webhooks.
Every request uses `https://api.smspro.com`. An `sk_test_` key simulates delivery and does not charge the wallet. An `sk_live_` key sends through the carrier and uses wallet credit.
## Start Building [#start-building]
## Platform Guides [#platform-guides]
## AI-Ready Documentation [#ai-ready-documentation]
Every page on this portal is directly consumable by AI coding assistants:
- Index directory: [`/llms.txt`](/llms.txt)
- Full Markdown corpus: [`/llms-full.txt`](/llms-full.txt)
- Append `.md` to any documentation URL (for example, [`/docs/getting-started/first-request.md`](/docs/getting-started/first-request.md)) to fetch raw Markdown.
---
# Idempotent Transactional SMS Dispatch
URL: /docs/recipes/idempotent-sms-dispatch
> Configure a typed SMS Pro client, attach UUID idempotency keys, test against deterministic sandbox numbers, and parse RFC 7807 errors.
Difficulty: Beginner | Duration: 5 min | Language: TypeScript
## Step 1: Configure Gateway & Auth Headers (`src/lib/smspro-client.ts`)
Initialize configuration from environment variables. Test keys and live keys both use `https://api.smspro.com`. The key prefix selects simulated delivery or carrier delivery.
```typescript
export interface SmsProConfig {
baseUrl: string;
apiKey: string;
}
export function getSmsProConfig(): SmsProConfig {
const apiKey = process.env.SMSPRO_API_KEY;
if (!apiKey) {
throw new Error('Missing SMSPRO_API_KEY environment variable');
}
const defaultBaseUrl = 'https://api.smspro.com';
return {
baseUrl: process.env.SMSPRO_BASE_URL ?? defaultBaseUrl,
apiKey,
};
}
```
## Step 2: Attach UUID Idempotency-Key (`src/lib/send-sms.ts`)
Generate a single UUID `Idempotency-Key` per logical notification **outside** your retry loop. SMS Pro caches the initial dispatch result for 24 hours so network retries remain side-effect free.
```typescript
import { randomUUID } from 'node:crypto';
import { getSmsProConfig } from './smspro-client';
export interface SendSmsInput {
to: string;
message: string;
senderId?: string;
deliveryCallbackUrl?: string;
idempotencyKey?: string;
}
export async function dispatchTransactionalSms(input: SendSmsInput) {
const { baseUrl, apiKey } = getSmsProConfig();
const idempotencyKey = input.idempotencyKey ?? randomUUID();
const response = await fetch(`${baseUrl}/api/v1/public/sms/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey,
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify({
to: input.to,
message: input.message,
senderId: input.senderId ?? 'SMSPRO',
deliveryCallbackUrl: input.deliveryCallbackUrl,
}),
});
return { response, idempotencyKey };
}
```
## Step 3: Test Deterministic Sandbox Outcomes (`scripts/test-sandbox.ts`)
With a `sk_test_...` key configured, send to SMS Pro's magic test numbers (`+233200000001` through `+233200000004`) to simulate `DELIVERED`, `UNDELIVERABLE`, `EXPIRED`, and `REJECTED_SPAM` receipts without incurring charges.
```typescript
import { dispatchTransactionalSms } from '../src/lib/send-sms';
const SANDBOX_NUMBERS = {
DELIVERED: '+233200000001',
UNDELIVERABLE: '+233200000002',
EXPIRED: '+233200000003',
REJECTED_SPAM: '+233200000004',
} as const;
async function verifySandboxMatrix() {
const { response, idempotencyKey } = await dispatchTransactionalSms({
to: SANDBOX_NUMBERS.DELIVERED,
message: 'Your order #4821 has been dispatched.',
senderId: 'SMSPRO',
});
const body = await response.json();
console.log('Status:', response.status, 'Idempotency-Key:', idempotencyKey);
console.log('Message ID:', body.data?.messageId);
}
verifySandboxMatrix();
```
## Step 4: Handle RFC 7807 Problem Details (`src/lib/errors.ts`)
(response: Response): Promise {
if (response.ok) {
const json = (await response.json()) as { data: T };
return json.data;
}
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/problem+json')) {
const problem = (await response.json()) as ProblemDetails;
throw new Error(
\`SMS Pro [\${problem.code}] (\${problem.status}): \${problem.detail} (requestId=\${problem.requestId})\`,
);
}
throw new Error(\`Unexpected SMS Pro HTTP \${response.status}\`);
}`}
>
All non-2xx responses return `application/problem+json` conforming to RFC 7807. Surface `problem.code` and `problem.requestId` in application logs for rapid support correlation, and only retry `429` / `5xx` errors.
---
# Interactive Recipes
URL: /docs/recipes
> Hands-on, split-pane code walkthroughs for common SMS Pro production integrations.
Browse step-by-step developer recipes modeled after production SMS Pro workflows. Click any recipe below to launch the split-pane interactive walkthrough.
---
# Send Bulk SMS with CSV Streaming & Batch Progress
URL: /docs/recipes/send-bulk-sms-campaign
> Ingest high-volume CSV contact lists without memory leaks, dispatch chunked batch jobs, and poll asynchronous campaign completion.
Difficulty: Intermediate | Duration: 9 min | Language: TypeScript
## Step 1: 1. Configure Dependencies & Environment (`Terminal`)
Install `csv-parser` to handle Node.js streaming ingestion with minimal memory overhead.
```bash
npm install csv-parser dotenv
```
## Step 2: 2. Build the Streaming CSV Recipient Parser (`src/stream-contacts.ts`)
Read the CSV file as an asynchronous stream. Clean and normalize each phone number to standard format, discarding duplicates and malformed records on the fly.
```ts
import fs from 'node:fs';
import csv from 'csv-parser';
export interface CsvContact {
phone: string;
name: string;
}
/**
* Streams contacts from CSV without loading the entire file into memory.
*/
export async function* streamContacts(filePath: string): AsyncGenerator {
const stream = fs.createReadStream(filePath).pipe(csv());
const seenPhones = new Set();
for await (const row of stream) {
const rawPhone = row.phone || row.mobile || row.phoneNumber;
if (!rawPhone) continue;
// Normalize: strip non-digits; if starting with 0, prepend 233
const digits = String(rawPhone).replace(/\D/g, '');
let normalized = digits;
if (digits.startsWith('0') && digits.length === 10) {
normalized = `233${digits.substring(1)}`;
}
if (normalized.length >= 9 && !seenPhones.has(normalized)) {
seenPhones.add(normalized);
yield {
phone: normalized,
name: row.name || 'Valued Customer',
};
}
}
}
```
## Step 3: 3. Dispatch Chunked Asynchronous Batch Jobs (`src/dispatch-campaign.ts`)
Accumulate recipients into chunks of 1,000 recipients and submit each chunk to `POST /api/v1/public/sms/batch`. Attach a unique `Idempotency-Key` to each batch chunk.
```ts
import crypto from 'node:crypto';
import { streamContacts, CsvContact } from './stream-contacts';
import { pollJobProgress } from './poll-progress';
const BASE_URL = process.env.SMSPRO_BASE_URL || 'https://api.smspro.com';
const API_KEY = process.env.SMSPRO_API_KEY!;
const BATCH_SIZE = 1000;
interface BatchSubmissionResponse {
status: string;
data: {
jobId: string;
totalRecipients: number;
status: string;
};
}
export async function runCampaign(csvPath: string, messageTemplate: string) {
let batchBuffer: CsvContact[] = [];
const submittedJobIds: string[] = [];
console.log(`🚀 Starting campaign ingestion from ${csvPath}...`);
for await (const contact of streamContacts(csvPath)) {
batchBuffer.push(contact);
if (batchBuffer.length >= BATCH_SIZE) {
const jobId = await submitBatchChunk(batchBuffer, messageTemplate);
submittedJobIds.push(jobId);
batchBuffer = [];
}
}
// Flush remaining contacts
if (batchBuffer.length > 0) {
const jobId = await submitBatchChunk(batchBuffer, messageTemplate);
submittedJobIds.push(jobId);
}
console.log(`✅ All batches submitted! Monitoring ${submittedJobIds.length} background jobs...`);
for (const jobId of submittedJobIds) {
await pollJobProgress(jobId);
}
console.log('🎉 Campaign processing completed successfully!');
}
async function submitBatchChunk(contacts: CsvContact[], template: string): Promise {
const idempotencyKey = crypto.randomUUID();
const payload = {
senderId: 'SMSPRO',
messages: contacts.map((c) => ({
to: c.phone,
message: template.replace('{{name}}', c.name),
})),
};
const res = await fetch(`${BASE_URL}/api/v1/public/sms/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': API_KEY,
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const errorBody = await res.text();
throw new Error(`Batch submission failed [${res.status}]: ${errorBody}`);
}
const json: BatchSubmissionResponse = await res.json();
console.log(`📦 Enqueued Batch [${json.data.jobId}] with ${contacts.length} recipients`);
return json.data.jobId;
}
```
## Step 4: 4. Poll Campaign Progress & Completion (`src/poll-progress.ts`)
Periodically query `GET /api/v1/public/sms/batch/{jobId}/progress` until the job reaches a terminal state (`COMPLETED` or `FAILED`).
```ts
const BASE_URL = process.env.SMSPRO_BASE_URL || 'https://api.smspro.com';
const API_KEY = process.env.SMSPRO_API_KEY!;
interface JobProgressResponse {
status: string;
data: {
jobId: string;
total: number;
processed: number;
successful: number;
failed: number;
status: 'QUEUED' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
};
}
export async function pollJobProgress(jobId: string, intervalMs = 2500): Promise {
while (true) {
const res = await fetch(`${BASE_URL}/api/v1/public/sms/batch/${jobId}/progress`, {
headers: { 'X-Api-Key': API_KEY },
});
if (!res.ok) {
console.warn(`Failed to poll progress for ${jobId} [${res.status}]`);
await sleep(intervalMs);
continue;
}
const { data }: JobProgressResponse = await res.json();
const percent = data.total > 0 ? Math.round((data.processed / data.total) * 100) : 0;
console.log(`📊 Job ${jobId}: ${percent}% (${data.processed}/${data.total}) | Success: ${data.successful} | Failed: ${data.failed}`);
if (data.status === 'COMPLETED' || data.status === 'FAILED') {
console.log(`🏁 Job ${jobId} finished with status: ${data.status}`);
break;
}
await sleep(intervalMs);
}
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
```
---
# Send SMS & Handle Webhooks Using Laravel
URL: /docs/recipes/send-sms-laravel
> Integrate SMS Pro into a Laravel 10/11 application with a custom Notification Channel, Http client wrapper, and signed webhook route.
Difficulty: Beginner | Duration: 6 min | Language: PHP
## Step 1: 1. Configure Environment & Services Config (`config/services.php`)
Add your API credentials to `.env` and register the `smspro` service entry in `config/services.php`.
```php
[
'base_url' => env('SMSPRO_BASE_URL', 'https://api.smspro.com'),
'api_key' => env('SMSPRO_API_KEY'),
'default_sender_id' => env('SMSPRO_DEFAULT_SENDER_ID', 'SMSPRO'),
'webhook_secret' => env('SMSPRO_WEBHOOK_SECRET'),
],
];
```
## Step 2: 2. Build the SmsProService Client (`app/Services/SmsProService.php`)
Create a reusable service class using Laravel's `Http` facade. Every mutating `POST` request attaches a unique `Str::uuid()` idempotency header and throws on HTTP `4xx/5xx` client or billing errors.
```php
baseUrl = config('services.smspro.base_url');
$this->apiKey = config('services.smspro.api_key');
$this->defaultSenderId = config('services.smspro.default_sender_id');
}
/**
* Send a single transactional SMS message with automatic idempotency.
*/
public function send(string $to, string $message, ?string $senderId = null): array
{
$response = Http::withHeaders([
'X-Api-Key' => $this->apiKey,
'Content-Type' => 'application/json',
'Idempotency-Key' => (string) Str::uuid(),
])->post("{$this->baseUrl}/api/v1/public/sms/send", [
'to' => $to,
'senderId' => $senderId ?: $this->defaultSenderId,
'message' => $message,
]);
if ($response->failed()) {
throw new RuntimeException("SMS Pro Dispatch Failed [{$response->status()}]: {$response->body()}");
}
return $response->json('data');
}
}
```
## Step 3: 3. Create a Custom Notification Channel (`app/Channels/SmsProChannel.php`)
Implement `SmsProChannel` so any standard Laravel Notification (`User::notify()`) can dispatch SMS seamlessly through SMS Pro.
```php
toSmsPro($notifiable);
$to = $notifiable->routeNotificationFor('sms', $notification)
?: $notifiable->phone_number;
if (!$to) {
return;
}
$this->smsPro->send($to, $message);
}
}
```
## Step 4: 4. Build the Signed Webhook Controller (`app/Http/Controllers/SmsProWebhookController.php`)
Create an invokable controller in `app/Http/Controllers/SmsProWebhookController.php` that verifies `X-SmsPro-Signature` using `hash_equals()` against the raw request content (`$request->getContent()`).
```php
header('X-SmsPro-Signature');
$secret = config('services.smspro.webhook_secret');
if (!$signature || !$secret) {
return response('Missing signature or secret', 401);
}
// Compute HMAC-SHA256 over raw payload
$computed = hash_hmac('sha256', $request->getContent(), $secret);
// Constant-time string comparison prevents timing attacks
if (!hash_equals($computed, $signature)) {
Log::warning('SMS Pro Webhook Signature Verification Failed');
return response('Invalid signature', 401);
}
$event = $request->json('event');
$data = $request->json('data');
Log::info("Verified SMS Pro Webhook [{$event}]:", $data);
// TODO: Update your internal database model status
return response('ACK', 200);
}
}
```
---
# Send SMS & Receive DLRs Using Spring Boot
URL: /docs/recipes/send-sms-spring-boot
> Build a production-ready Spring Boot 3 service to dispatch transactional SMS and an HMAC-verified controller to ingest delivery reports.
Difficulty: Intermediate | Duration: 7 min | Language: Java
## Step 1: 1. Configure Application Properties (`src/main/resources/application.properties`)
Store your gateway credentials in `application.properties` (or `application.yml`). Use your `sk_test_...` key for local development and inject `sk_live_...` secrets via environment variables in production.
```properties
# SMS Pro Gateway Configuration
smspro.base-url=https://api.smspro.com
smspro.api-key=${SMSPRO_API_KEY:sk_test_948f293048a1b2c3d4e5f60718}
smspro.webhook-secret=${SMSPRO_WEBHOOK_SECRET:whsec_38f9024a1b2c3d4e5f60718a}
```
## Step 2: 2. Define Immutable Java Records (DTOs) (`src/main/java/com/example/sms/dto/SmsDtos.java`)
Define clean, immutable Java records matching the SMS Pro REST request, response, and delivery report payload specifications.
```java
package com.example.sms.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
public class SmsDtos {
public record SendSmsRequest(
String to,
String senderId,
String message
) {}
@JsonIgnoreProperties(ignoreUnknown = true)
public record SendSmsResponse(
String status,
String message,
JobData data
) {
public record JobData(
String jobId,
String messageId,
String status,
int segmentCount,
int totalUnits
) {}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record DlrWebhookEvent(
String messageId,
String providerMessageId,
String to,
String status,
String deliveredAt,
String gateway,
String raw
) {}
}
```
## Step 3: 3. Build the SmsProClient Service (`src/main/java/com/example/sms/service/SmsProClient.java`)
Use Spring Boot 3's modern `RestClient` to dispatch SMS. Every mutating request automatically attaches a unique `Idempotency-Key` (UUID v4) to prevent duplicate charges or accidental re-sends.
```java
package com.example.sms.service;
import com.example.sms.dto.SmsDtos.SendSmsRequest;
import com.example.sms.dto.SmsDtos.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.util.UUID;
@Service
public class SmsProClient {
private static final Logger log = LoggerFactory.getLogger(SmsProClient.class);
private final RestClient restClient;
public SmsProClient(
@Value("${smspro.base-url}") String baseUrl,
@Value("${smspro.api-key}") String apiKey
) {
this.restClient = RestClient.builder()
.baseUrl(baseUrl)
.defaultHeader("X-Api-Key", apiKey)
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.build();
}
/**
* Dispatches a single transactional SMS with automatic idempotency protection.
*/
public SendSmsResponse.JobData sendTransactionalSms(String to, String senderId, String message) {
String idempotencyKey = UUID.randomUUID().toString();
log.info("Dispatching SMS to {} via senderId {} (IdempotencyKey: {})", to, senderId, idempotencyKey);
SendSmsResponse response = restClient.post()
.uri("/api/v1/public/sms/send")
.header("Idempotency-Key", idempotencyKey)
.body(new SendSmsRequest(to, senderId, message))
.retrieve()
.body(SendSmsResponse.class);
if (response != null && response.data() != null) {
log.info("SMS queued successfully: messageId={}, jobId={}",
response.data().messageId(), response.data().jobId());
return response.data();
}
throw new IllegalStateException("Failed to queue SMS: Empty response from SMS Pro gateway");
}
}
```
## Step 4: 4. Implement the Verified DLR Webhook Controller (`src/main/java/com/example/sms/controller/DlrWebhookController.java`)
Expose an HTTP `POST` endpoint at `/api/v1/webhooks/smspro`. Read `X-SmsPro-Signature` as `t=,v1=`, sign `timestamp.rawBody`, and compare equal-length digests.
```java
package com.example.sms.controller;
import com.example.sms.dto.SmsDtos.DlrWebhookEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
@RestController
@RequestMapping("/api/v1/webhooks")
public class DlrWebhookController {
private static final Logger log = LoggerFactory.getLogger(DlrWebhookController.class);
private final String webhookSecret;
private final ObjectMapper objectMapper;
public DlrWebhookController(
@Value("${smspro.webhook-secret}") String webhookSecret,
ObjectMapper objectMapper
) {
this.webhookSecret = webhookSecret;
this.objectMapper = objectMapper;
}
@PostMapping("/smspro")
public ResponseEntity handleDlrWebhook(
@RequestHeader(value = "X-SmsPro-Signature", required = false) String signatureHeader,
@RequestBody byte[] rawPayload
) {
if (signatureHeader == null || !isValidSignature(rawPayload, signatureHeader)) {
log.warn("Rejected webhook: Invalid or missing X-SmsPro-Signature");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid signature");
}
try {
DlrWebhookEvent event = objectMapper.readValue(rawPayload, DlrWebhookEvent.class);
log.info("Received verified DLR: messageId={}, status={}",
event.messageId(), event.status());
// TODO: Update your internal database status (e.g. orderRepository.markSmsDelivered())
return ResponseEntity.ok("ACK");
} catch (Exception e) {
log.error("Failed to parse verified webhook payload", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Malformed payload");
}
}
private boolean isValidSignature(byte[] payload, String signatureHeader) {
try {
int comma = signatureHeader.indexOf(',');
int tMark = signatureHeader.indexOf("t=");
int vMark = signatureHeader.indexOf("v1=");
if (tMark < 0 || vMark < 0 || comma < 0) return false;
String timestamp = signatureHeader.substring(tMark + 2, comma).trim();
String expected = signatureHeader.substring(vMark + 3).trim();
String signed = timestamp + "." + new String(payload, StandardCharsets.UTF_8);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(webhookSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String computedHex = HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)));
byte[] left = computedHex.getBytes(StandardCharsets.UTF_8);
byte[] right = expected.getBytes(StandardCharsets.UTF_8);
if (left.length != right.length) return false;
return MessageDigest.isEqual(left, right);
} catch (Exception ex) {
log.error("Error computing HMAC-SHA256 signature", ex);
return false;
}
}
}
```
---
# Verify Delivery Report Webhooks
URL: /docs/recipes/verify-webhooks
> Extract raw request bodies, parse X-SmsPro-Signature headers, enforce 300s replay protection, and validate HMAC-SHA256 in constant time.
Difficulty: Intermediate | Duration: 8 min | Language: TypeScript
## Step 1: Read the Raw Unparsed HTTP Body (`src/app/api/webhooks/smspro/route.ts`)
Always capture the raw HTTP payload string with `await request.text()` before parsing JSON. Any whitespace normalization or key re-ordering from `JSON.stringify(await request.json())` invalidates the cryptographic signature.
```typescript
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
// CRITICAL: Read raw text bytes before JSON.parse().
// Re-serializing parsed JSON changes whitespace/key ordering and breaks HMAC.
const rawBody = await request.text();
const signatureHeader = request.headers.get('x-smspro-signature');
if (!rawBody || !signatureHeader) {
return NextResponse.json(
{ error: 'Missing webhook payload or X-SmsPro-Signature header' },
{ status: 400 },
);
}
// Verification proceeds in Steps 2-4...
return NextResponse.json({ received: true });
}
```
## Step 2: Parse X-SmsPro-Signature & Replay Window (`src/lib/verify-smspro-webhook.ts`)
= {};
for (const segment of header.split(',')) {
const idx = segment.indexOf('=');
if (idx === -1) continue;
const key = segment.slice(0, idx).trim().toLowerCase();
const val = segment.slice(idx + 1).trim();
if (key && val) parts[key] = val;
}
if (!parts.t || !parts.v1) return null;
const rawTs = Number(parts.t);
if (!Number.isFinite(rawTs)) return null;
// Normalize milliseconds to seconds if necessary
const tsSeconds = rawTs > 1_000_000_000_000 ? Math.floor(rawTs / 1000) : rawTs;
const nowSeconds = Math.floor(Date.now() / 1000);
if (Math.abs(nowSeconds - tsSeconds) > REPLAY_TOLERANCE_SECONDS) {
return null;
}
return { timestamp: parts.t, v1: parts.v1.toLowerCase() };
}`}
>
Extract `t` (Unix timestamp) and `v1` (64-character lowercase hex digest) from `X-SmsPro-Signature: t=...,v1=...`. Reject payloads older or newer than `300` seconds to block replay attacks.
## Step 3: Compute HMAC-SHA256 & Constant-Time Check (`src/lib/verify-smspro-webhook.ts`)
."
const signedPayload = \`\${parsed.timestamp}.\${rawBody}\`;
const computedHex = createHmac('sha256', webhookSecret.trim())
.update(signedPayload, 'utf8')
.digest('hex');
const computedBuf = Buffer.from(computedHex, 'utf8');
const expectedBuf = Buffer.from(parsed.v1, 'utf8');
if (computedBuf.length !== expectedBuf.length) {
return false;
}
return timingSafeEqual(computedBuf, expectedBuf);
}`}
>
Compute `HMAC-SHA256` over `` `${timestamp}.${rawBody}` `` using your `whsec_...` signing secret, check equal buffer lengths, and compare with `crypto.timingSafeEqual()` to prevent timing side-channel leaks.
## Step 4: Process Event & Acknowledge 200 OK (`src/app/api/webhooks/smspro/route.ts`)
Return `401 Unauthorized` on invalid or expired signatures. Once verified, parse the JSON event, enqueue downstream database or alert updates, and respond immediately with `200 OK`.
```typescript
import { NextRequest, NextResponse } from 'next/server';
import { verifySmsProSignature } from '@/lib/verify-smspro-webhook';
interface DeliveryEvent {
messageId: string;
providerMessageId: string;
to: string;
status: string;
deliveredAt: string;
gateway: string;
raw: string;
}
export async function POST(request: NextRequest) {
const rawBody = await request.text();
const signature = request.headers.get('x-smspro-signature') ?? '';
const secret = process.env.SMSPRO_WEBHOOK_SECRET ?? '';
if (!verifySmsProSignature(rawBody, signature, secret)) {
return NextResponse.json(
{ error: 'Invalid or expired webhook signature' },
{ status: 401 },
);
}
const payload = JSON.parse(rawBody) as DeliveryEvent;
// Dispatch to background queue so HTTP 200 returns well under 5 seconds
console.info('Verified SMS Pro delivery:', payload.messageId, payload.status);
return NextResponse.json({ status: 'received' }, { status: 200 });
}
```
---
# Zero-Knowledge OTP Verification (v2)
URL: /docs/recipes/zero-knowledge-otp
> Issue 128-bit single-use challenge nonces, derive SHA-256 codeProof digests, verify OTPs without transmitting raw PINs, and handle failover.
Difficulty: Advanced | Duration: 10 min | Language: TypeScript
## Step 1: Issue Challenge & Capture challengeNonce (`src/services/otp-v2.ts`)
{
const res = await fetch(\`\${process.env.SMSPRO_BASE_URL}/api/v2/public/otp/send\`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.SMSPRO_API_KEY!,
},
body: JSON.stringify({
phoneNumber,
senderId: 'AUTH',
}),
});
if (!res.ok) throw new Error(\`OTP send failed: \${res.status}\`);
const json = (await res.json()) as { data: OtpSendV2Response };
return json.data;
}`}
>
Call `POST /api/v2/public/otp/send`. SMS Pro delivers the numeric PIN out-of-band to the subscriber's handset and returns a single-use 128-bit hex `challengeNonce` plus `otpId`.
## Step 2: Derive Canonical SHA-256 codeProof (`src/lib/zk-proof.ts`)
{
const canonical = \`\${challengeNonce.trim().toLowerCase()}:\${userCode.trim().toLowerCase()}\`;
const data = new TextEncoder().encode(canonical);
const digest = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
}`}
>
Normalize both `challengeNonce` and the user-entered PIN with `.trim().toLowerCase()`, join with `:`, and compute the 64-character lowercase hexadecimal SHA-256 digest.
## Step 3: Verify Proof Without Sending Plaintext PIN (`src/services/otp-v2.ts`)
{
const codeProof = computeCodeProof(params.challengeNonce, params.userEnteredCode);
const res = await fetch(\`\${process.env.SMSPRO_BASE_URL}/api/v2/public/otp/verify\`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.SMSPRO_API_KEY!,
},
body: JSON.stringify({
phoneNumber: params.phoneNumber,
otpId: params.otpId,
codeProof,
}),
});
const json = (await res.json()) as { data: OtpVerifyV2Response };
return json.data;
}`}
>
Submit `phoneNumber`, `otpId`, and `codeProof` to `POST /api/v2/public/otp/verify`. The proof is checked once and cannot be reused.
## Step 4: Trigger Automatic SMS Failover (`src/services/otp-v2.ts`)
If the initial WhatsApp challenge goes undelivered or the user requests an alternate channel, invoke `POST /api/v2/public/otp/failover` to fall back to carrier SMS (`SMS_FAILOVER`) while preserving the challenge flow.
```typescript
export async function triggerOtpSmsFailover(otpId: string, phoneNumber: string) {
const res = await fetch(`${process.env.SMSPRO_BASE_URL}/api/v2/public/otp/failover`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': process.env.SMSPRO_API_KEY!,
},
body: JSON.stringify({
otpId,
phoneNumber,
}),
});
if (!res.ok) {
throw new Error(`OTP failover failed with status ${res.status}`);
}
return res.json();
}
```