# 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&apos;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<T> {
  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.