> ## Documentation Index
> Fetch the complete documentation index at: https://docs.open.cx/llms.txt
> Use this file to discover all available pages before exploring further.

# Voice SDK integration

> Add voice support to your web, iOS, or Android app. Authenticate customers, connect AI or human teams, and manage call controls and session status.

<Warning>
  The Voice SDK is an opt-in preview. Your organization needs access enabled and a compatible backend deployment. Obtain the preview packages from your OpenCX contact; public package registry availability is not implied by this guide.
</Warning>

Add a **Call support** button to your app. Customers can speak with an AI phone agent, wait for a human team, or remain on the same call while the AI hands off to a human. Your app controls the interface; the SDK handles audio and call controls.

The SDK supports customer-initiated calls while your support screen is active. Incoming-call push notifications, system call-screen integration, and automatic background-call support are not included. Configure and test any app background audio behavior separately.

## Authenticate on your server

Your server must authenticate the customer and resolve their OpenCX contact. It then chooses an authorized phone agent or support team and calls [Create an app voice call](/api-reference/phone/create_web_call) with an API key holding `phone:write`.

Never put a permanent API key in a website or mobile app. Do not accept an arbitrary contact ID or privileged routing destination from the client. Membership in your app must be checked before returning call credentials.

```typescript theme={"dark"}
// Inside your authenticated server route:
// contactId is resolved from the signed-in customer, not the request body.
const response = await fetch('https://api.open.cx/phone/web-calls', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.OPENCX_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    requestId, // UUID; keep the same value when retrying this request
    contactId,
    destination: { type: 'agent', id: phoneAgentId },
    maxDurationSeconds: 1800,
  }),
});
if (!response.ok) {
  // Return an appropriate error to your app; never log returned credentials.
  throw new Error(`Call creation failed (${response.status})`);
}
const credentials = await response.json();
// Respond only to the authenticated customer, with Cache-Control: no-store.
```

Use `{ type: 'team', id: teamId }` to start with a human team. The team must belong to your organization and have support enabled. App calls use that team's routing and queue settings. A direct team call does not spill into unrelated teams when nobody is available.

For AI calls, configure the agent's languages and permitted human-team transfer destinations in the dashboard. App-call agents support team and end-call destinations. Agents with telephone-number or external telephony transfer destinations are rejected; use a dedicated app-support agent if your phone agent needs those destinations. No dialed phone number is available to select a country flow: choose the appropriate destination on your server.

Call creation returns `callId`, `sessionId`, `serverUrl`, `participantToken`, `controlToken`, and `expiresAt`. Pass this object to the SDK unchanged. Treat both tokens as secrets; do not log them, place them in page URLs, or store them persistently. The SDK connects and activates the call. An abandoned connection attempt expires automatically, and active calls have a server-enforced duration limit.

Reuse `requestId` only for retries of the same creation attempt. Different settings with the same ID fail. After a call starts or ends, use a new request ID for another call. One customer can have one active app call at a time.

## Web

Install the preview package supplied by OpenCX:

```bash theme={"dark"}
npm install ./opencx-voice-0.1.0.tgz
```

```typescript theme={"dark"}
import { OpenCXVoice } from '@opencx/voice';

const voice = new OpenCXVoice({
  getToken: async ({ requestId, signal }) => {
    const response = await fetch('/api/support/voice-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ requestId }),
      signal,
    });
    if (!response.ok) throw new Error('Unable to start support call');
    return response.json();
  },
});

voice.on('stateChanged', state => updateCallStatus(state));
voice.on('error', error => showCallError(error.message));

// Run from the customer's button click.
await voice.start();
await voice.setMuted(true);
voice.setSpeakerEnabled(false);
await voice.end();
// On permanent component removal:
await voice.dispose();
```

`setMicrophone(deviceId)` and `setAudioOutput(deviceId)` select audio devices where the browser supports them. If audio playback is blocked, show a button that calls `resumeAudio()`. Microphone access requires HTTPS (localhost is allowed for development). Embedded frames require microphone permission from the host page. Customers can refuse or revoke microphone access; display the SDK error and offer another support channel.

Subscribe before calling `start()`. The states are `idle`, `connecting`, `waiting`, `queued`, `connected`, `reconnecting`, and `ended`. A queue notification or ringing agent is not proof a human answered. `connected` reflects an observed ready support participant. An `ended` state means the local microphone is stopped; if server hangup fails, an error is also emitted and server cleanup remains responsible for the room.

## iOS

Add the supplied `OpenCXVoice` Swift package to your app. Include `NSMicrophoneUsageDescription` in your app's privacy settings. The SDK requests audio permission before creating a call.

```swift theme={"dark"}
import OpenCXVoice

let voice = try OpenCXVoice { requestId in
    // Authenticate with your backend and decode its response:
    try await supportAPI.voiceCredentials(requestId: requestId.uuidString)
}
voice.onStateChanged = { state in updateCallStatus(state.rawValue) }
voice.onError = { error in showCallError(error.localizedDescription) }
try await voice.start()
try await voice.setMuted(true)
try await voice.setSpeakerEnabled(true)
try await voice.end()
```

Keep the instance alive until the call ends. UI callbacks run on the main actor. End the call before discarding its owner. The speaker setting selects speakerphone or the system audio route. Test interruptions, Bluetooth, route changes, and app backgrounding on physical devices before rollout.

## Android

Add the supplied `cx.open:voice-android:0.1.0` package from your configured preview repository. Request `RECORD_AUDIO` permission before starting a call. Use the SDK from the main thread and collect `state` in your app's lifecycle.

```kotlin theme={"dark"}
import cx.open.voice.OpenCXVoice

val voice = OpenCXVoice(context, getToken = { requestId ->
    // Authenticate with your backend and decode with VoiceCredentials.fromJson.
    supportApi.voiceCredentials(requestId)
})
voice.onError = { error -> showCallError(error.message) }
voice.start()
voice.setMuted(true)
voice.end()
// When the owning support screen is permanently removed:
voice.dispose()
```

Do not cancel the only call owner without ending the call. Audio routing follows the system route. Background calling and incoming call alerts require additional app integration and are outside this preview.

## Session history and recording

`sessionId` identifies the OpenCX support session. App calls use the existing voice session history and configured recording behavior. Choosing app calling does not grant permission to read other sessions. Make your recording notice and retention policy available before the customer starts speaking.

## Troubleshooting

| Symptom | Check |
| - | - |
| Creation returns 403 | Organization preview access, API key scope, and contact blocking. |
| Creation returns 404 | Contact and destination belong to the same organization; the team has support enabled. |
| Creation returns 409 | An existing active call or reuse of a request ID with different settings. |
| Call stays waiting | Network access, destination readiness, or unavailable support agents. The SDK reports a startup timeout. |
| Microphone denied | Device/browser permission and the host page's frame permissions. |
| Connected but silent | Device route, muted speaker, or browser playback permission; offer `resumeAudio()` on web. |
| Call ends during a network change | A brief reconnect is supported, but a prolonged disconnect ends the call. Offer a fresh call attempt. |

Test your supported browser and device versions, human acceptance, unavailable teams, queues, hangup during connection, and Wi-Fi/cellular changes before enabling this for customers.
