> For the complete documentation index, see [llms.txt](https://docs.sudoplatform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sudoplatform.com/guides/telephony/phone-numbers.md).

# Manage Phone Numbers

Phone numbers are a central part of the **Telephony SDK**. Phone numbers from different countries around the world can be provisioned and used to communicate with other phone numbers.

Provisioning a phone number is a two-step process. First, a search is performed to determine which numbers are available in a country and area code. Once results are returned and the desired number is selected, that number can be provisioned.

## Get Supported Countries

A phone number can only be provisioned in a country supported by your Sudo Platform account. A call to the `getSupportedCountries` method returns these countries as [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes, and a returned code is the value to supply as the `countryCode` when performing a search.

{% tabs %}
{% tab title="Typescript" %}

```js
try {
  const countries = await telephonyClient.getSupportedCountries()
  // `countries` contains a list of supported country codes, for example ['US', 'CA'].
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let countries = try await telephonyClient.getSupportedCountries()
    /// `countries` contains a list of supported country codes, for example ["US", "CA"].
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val countries = withContext(Dispatchers.IO) {
            telephonyClient.getSupportedCountries()
        }
        // [countries] contains a list of supported country codes, for example ["US", "CA"].
    } catch (e: SupportedCountriesException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Each project in your Sudo Platform account can be configured to support a specific set of country codes. Your solutions engineer can assist you in selecting the desired country codes.
{% endhint %}

## Search Available Phone Numbers

A call to the `searchAvailablePhoneNumbers` method returns a search result containing the numbers the carrier has available. The `countryCode` must be one of the values returned by `getSupportedCountries`, and a three-digit `areaCode` is required for provisioning US numbers. An optional `limit` controls the number of results.

{% tabs %}
{% tab title="Typescript" %}

```js
try {
  const search = await telephonyClient.searchAvailablePhoneNumbers({
    countryCode: 'US',
    areaCode: '415',
    limit: 10, // Optional, defaults to 10
  })
  // `search.id` identifies the search and is supplied when provisioning.
  // `search.results` contains the available numbers.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let searchInput = SearchAvailablePhoneNumbersInput(
        countryCode: "US",
        areaCode: "415",
        limit: 10 /// Optional, defaults to 10
    )
    let search = try await telephonyClient.searchAvailablePhoneNumbers(searchInput)
    /// `search.id` identifies the search and is supplied when provisioning.
    /// `search.results` contains the available numbers.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val input = SearchAvailablePhoneNumbersInput(
            countryCode = "US",
            areaCode = "415",
            limit = 10 // Optional, defaults to 10
        )
        val search = withContext(Dispatchers.IO) {
            telephonyClient.searchAvailablePhoneNumbers(input)
        }
        // [search.id] identifies the search and is supplied when provisioning.
        // [search.results] contains the available numbers.
    } catch (e: PhoneNumberSearchException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
A search can legitimately return no results, because availability depends on the carrier's inventory for the requested area code. An empty result is a normal outcome rather than an error, and your application should allow the user to try another area code.
{% endhint %}

{% hint style="warning" %}
A search result is not a reservation. The carrier does not hold the returned numbers, so another user may provision one between your search and your provision call. It is recommended that your application attempt the next result when a number is reported as unavailable.
{% endhint %}

## Provision a Phone Number

Once an available number has been found, it can be provisioned by calling the `provisionPhoneNumber` method with the `id` of the search and the chosen number. The newly provisioned phone number object is returned. Phone numbers are represented in the [E.164 phone number format](https://en.wikipedia.org/wiki/E.164).

The SDK generates the key pair that the number's messages are sealed to and registers the public key as part of this call, so no key material is supplied as input.

An optional `clientRefId` can be provided to make the request idempotent. Repeating a request with the same value returns the number provisioned by the first request rather than provisioning an additional number.

An `ownershipProofToken` is required in deployments configured to require Sudo ownership proof. This ties together the Sudo and the phone number such that the Sudo becomes the owner of the number. Use the `getOwnershipProof` method on the `SudoProfilesClient` in the **Sudo Profiles SDK** to obtain one. See the [Sudo](https://docs.sudoplatform.com/guides/sudos.md) section for more information.

{% tabs %}
{% tab title="Typescript" %}

```js
// Collect the search id and chosen number from a prior search.
const searchId = search.id
const candidates = search.results.map((result) => result.phoneNumber)

for (const candidate of candidates) {
  try {
    const phoneNumber = await telephonyClient.provisionPhoneNumber({
      searchId,
      phoneNumber: candidate,
      ownershipProofToken, // Where required by the deployment
      clientRefId: 'my-client-reference', // Optional, makes the request idempotent
    })
    // The returned `phoneNumber` is being provisioned and is not yet usable.
    break
  } catch (error) {
    // Handle/notify user of error
    break
  }
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
/// Collect the search id and chosen number from a prior search.
let searchId = search.id
let candidates = search.results.map { $0.phoneNumber }

var lastError: Error?
for candidate in candidates {
    do {
        let provisionInput = ProvisionPhoneNumberInput(
            searchId: searchId,
            phoneNumber: candidate,
            ownershipProofTokens: [ownershipProofToken] /// Where required by the deployment
        )
        let phoneNumber = try await telephonyClient.provisionPhoneNumber(provisionInput)
        /// `phoneNumber` is being provisioned and is not yet usable.
        break
    } catch {
        /// `SudoTelephonyError` does not distinguish a number taken since the search from
        /// another provisioning failure, so the next candidate is attempted.
        lastError = error
        continue
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Collect the search id and chosen number from a prior search.
val searchId = search.id
val candidates = search.results.map { it.phoneNumber }

launch {
    for (candidate in candidates) {
        try {
            val input = ProvisionPhoneNumberInput(
                searchId = searchId,
                phoneNumber = candidate,
                ownershipProofToken = ownershipProofToken // Where required by the deployment
            )
            val phoneNumber = withContext(Dispatchers.IO) {
                telephonyClient.provisionPhoneNumber(input)
            }
            // The returned [phoneNumber] is being provisioned and is not yet usable.
            break
        } catch (e: PhoneNumberException.PhoneNumberUnavailableException) {
            // The number was taken since the search; attempt the next candidate.
        } catch (e: PhoneNumberException) {
            // Handle/notify user of exception
            break
        }
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
The returned phone number is in the `PROVISIONING` state and is not yet usable. The order is completed asynchronously with the carrier, after which the number becomes `ACTIVE` or `FAILED`. Your application should not treat the returned object as final. See [Subscriptions](https://docs.sudoplatform.com/guides/telephony/subscriptions.md).
{% endhint %}

{% hint style="warning" %}
In order to be able to provision a phone number, the user must be entitled. See [Telephony Entitlements](https://docs.sudoplatform.com/guides/telephony/telephony-entitlements.md) for an overview of the required entitlement checks.
{% endhint %}

## Deprovision a Phone Number

A previously provisioned phone number can be deprovisioned using the `deprovisionPhoneNumber` method by passing in the `id` of an existing phone number object. The phone number object that was deprovisioned is returned in the `RELEASED` state. The phone number is handed back to the carrier in the background.

{% tabs %}
{% tab title="Typescript" %}

```js
// Collect the input phone number id however makes sense for your implementation.
const phoneNumberId = phoneNumber.id
try {
  const released = await telephonyClient.deprovisionPhoneNumber(phoneNumberId)
  // The returned `released` has now been deprovisioned.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
/// Collect the input phone number id however makes sense for your implementation.
let phoneNumberId = phoneNumber.id
do {
    let released = try await telephonyClient.deprovisionPhoneNumber(id: phoneNumberId)
    /// `released` is the record that was just deprovisioned.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Collect the input phone number id however makes sense for your implementation.
val phoneNumberId = phoneNumber.id
launch {
    try {
        val released = withContext(Dispatchers.IO) {
            telephonyClient.deprovisionPhoneNumber(phoneNumberId)
        }
        // The returned [released] has now been deprovisioned.
    } catch (e: PhoneNumberException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Only an `ACTIVE` or `SUSPENDED` number can be deprovisioned. Attempting to deprovision a number that is still being provisioned fails with an invalid state error that reports the number's current state. Deprovisioning a number that has already been released returns it unchanged, so the call is safe to repeat.
{% endhint %}

{% hint style="info" %}
Deprovisioning a number does not remove the keys that unseal its messages. Any retained messages remain readable. Keys are removed explicitly, as described in [Message Privacy and Key Management](https://docs.sudoplatform.com/guides/telephony/message-privacy-and-key-management.md).
{% endhint %}

## Retrieving Existing Phone Numbers

Previously provisioned phone numbers can be accessed in two ways: via its identifier ([Single Phone Number by Id](#single-phone-number-by-id)), or via a list method ([All Provisioned Phone Numbers](#all-provisioned-phone-numbers)).

### Single Phone Number by Id

To retrieve a single phone number given its unique `id`, use the `getPhoneNumber` method. This method returns the record if it exists, in any state.

{% tabs %}
{% tab title="Typescript" %}

```js
// Collect the input phone number id however makes sense for your implementation.
const phoneNumberId = phoneNumber.id
try {
  const phoneNumber = await telephonyClient.getPhoneNumber(phoneNumberId)
  // `phoneNumber` contains the phone number object, else `undefined` if not found.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
/// Collect the input phone number id however makes sense for your implementation.
let phoneNumberId = phoneNumber.id
do {
    let phoneNumber = try await telephonyClient.getPhoneNumber(id: phoneNumberId)
    /// `phoneNumber` contains the phone number object, else `nil` if not found.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Collect the input phone number id however makes sense for your implementation.
val phoneNumberId = phoneNumber.id
launch {
    try {
        val phoneNumber = withContext(Dispatchers.IO) {
            telephonyClient.getPhoneNumber(phoneNumberId)
        }
        // [phoneNumber] contains the phone number object, else [null] if not found.
    } catch (e: PhoneNumberException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

### Multiple Provisioned Phone Numbers

The ability to retrieve multiple or all phone numbers available to the user is supported. These results can be paginated.

#### All Provisioned Phone Numbers

To retrieve all provisioned phone numbers for a user, call the `listPhoneNumbers` method. Results are returned oldest first and can be paginated using the returned `nextToken`.

{% tabs %}
{% tab title="Typescript" %}

```js
try {
  const numbers: PhoneNumber[] = []
  let nextToken: string | undefined
  do {
    const output = await telephonyClient.listPhoneNumbers({
      limit: 20,
      nextToken,
    })
    // `output.items` contains the list of phone numbers matching the input.
    numbers.push(...output.items)
    nextToken = output.nextToken
  } while (nextToken)
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var nextToken: String?
var numbers: [PhoneNumber] = []
do {
    repeat {
        let listInput = ListPhoneNumbersInput(limit: 20, nextToken: nextToken)
        let output = try await telephonyClient.listPhoneNumbers(listInput)
        /// `output.items` contains an array of `PhoneNumber`.
        numbers.append(contentsOf: output.items)
        nextToken = output.nextToken
    } while nextToken != nil
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        var nextToken: String? = null
        val numbers = mutableListOf<PhoneNumber>()
        do {
            val input = ListPhoneNumbersInput(limit = 20, nextToken = nextToken)
            val output = withContext(Dispatchers.IO) {
                telephonyClient.listPhoneNumbers(input)
            }
            // [output.items] contains the list of items matching the input.
            numbers.addAll(output.items)
            nextToken = output.nextToken
        } while (nextToken != null)
    } catch (e: PhoneNumberException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

#### All Provisioned Phone Numbers for a Sudo

To retrieve all provisioned phone numbers that are owned by a particular Sudo, call the `listPhoneNumbersForSudoId` method by passing in the `id` of the Sudo to query. Results are returned oldest first and can be paginated using the returned `nextToken`.

{% tabs %}
{% tab title="Typescript" %}

```js
try {
  const numbers: PhoneNumber[] = []
  let nextToken: string | undefined
  do {
    const output = await telephonyClient.listPhoneNumbersForSudoId({
      sudoId,
      limit: 20,
      nextToken,
    })
    // `output.items` contains the list of phone numbers matching the input.
    numbers.push(...output.items)
    nextToken = output.nextToken
  } while (nextToken)
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
var nextToken: String?
var numbers: [PhoneNumber] = []
do {
    repeat {
        let listInput = ListPhoneNumbersForSudoIdInput(
            sudoId: sudoId,
            limit: 20, 
            nextToken: nextToken
        )
        let output = try await telephonyClient.listPhoneNumbersForSudoId(listInput)
        /// `output.items` contains an array of `PhoneNumber`.
        numbers.append(contentsOf: output.items)
        nextToken = output.nextToken
    } while nextToken != nil
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        var nextToken: String? = null
        val numbers = mutableListOf<PhoneNumber>()
        do {
            val input = ListPhoneNumbersForSudoIdInput(
                sudoId = sudoId,
                limit = 20, 
                nextToken = nextToken
            )
            val output = withContext(Dispatchers.IO) {
                telephonyClient.listPhoneNumbersForSudoId(input)
            }
            // [output.items] contains the list of items matching the input.
            numbers.addAll(output.items)
            nextToken = output.nextToken
        } while (nextToken != null)
    } catch (e: PhoneNumberException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}
