Azure Communication Services

JavaScript SDK for Managing Phone Numbers

Introduction to Phone Numbers SDK

The Azure Communication Services (ACS) Phone Numbers SDK for JavaScript provides developers with the tools to programmatically manage phone numbers associated with their ACS resources. This SDK allows you to discover, acquire, configure, and release phone numbers, integrating voice and SMS capabilities into your applications.

With this SDK, you can:

  • List and search for available phone numbers in specific regions.
  • Purchase new phone numbers for your ACS resource.
  • Manage existing phone numbers, such as updating their capabilities or releasing them.
  • Integrate phone number management directly into your web applications.

Getting Started

To use the Phone Numbers SDK, you first need to set up an Azure Communication Services resource. Then, install the SDK package:

npm install @azure/communication-phone-numbers

You'll need to authenticate your requests. Typically, this involves using an ACS connection string or an Azure Active Directory credential.


import { PhoneNumbersClient } from "@azure/communication-phone-numbers";
import { DefaultAzureCredential } from "@azure/identity";

// Replace with your ACS resource connection string or use Azure Identity
const connectionString = "YOUR_AZURE_COMMUNICATION_SERVICES_CONNECTION_STRING";
const client = new PhoneNumbersClient(connectionString);

// Or using Azure Identity:
// const tokenCredential = new DefaultAzureCredential();
// const client = new PhoneNumbersClient(tokenCredential, { endpoint: "YOUR_ACS_ENDPOINT" });
                    

Managing Phone Numbers

The core functionality of the SDK revolves around managing phone numbers. Here are some common operations:

List Your Purchased Phone Numbers

Retrieve a list of all phone numbers currently assigned to your Communication Services resource.


async function listMyPhoneNumbers() {
    try {
        const result = client.listOwnedPhoneNumbers();
        for await (const phoneNumber of result) {
            console.log("Phone Number:", phoneNumber.phoneNumber);
            console.log("Capabilities:", phoneNumber.capabilities);
        }
    } catch (error) {
        console.error("Error listing phone numbers:", error);
    }
}

listMyPhoneNumbers();
                    

Search Available Phone Numbers

Discover phone numbers available for purchase in a specific country and of a particular type (e.g., voice, SMS).


async function searchAvailableNumbers() {
    const options = {
        country: "US", // Example: United States
        phoneNumberType: "Local", // "Local", "Mobile", "TollFree"
        capabilities: {
            voice: true,
            sms: true
        }
    };
    try {
        const result = client.searchAvailablePhoneNumbers(options);
        for await (const phoneNumber of result) {
            console.log("Available Number:", phoneNumber.phoneNumber);
            console.log("Cost:", phoneNumber.cost);
            console.log("Capabilities:", phoneNumber.capabilities);
        }
    } catch (error) {
        console.error("Error searching for phone numbers:", error);
    }
}

searchAvailableNumbers();
                    

Buy a Phone Number

Acquire a specific available phone number. Ensure you have sufficient credit in your ACS account.


async function buyPhoneNumber(phoneNumberToBuy) {
    const options = {
        country: "US",
        phoneNumber: phoneNumberToBuy,
        capabilities: {
            voice: true,
            sms: true
        }
    };
    try {
        const result = await client.buyPhoneNumber(options);
        console.log(`Successfully bought ${phoneNumberToBuy}. Operation ID: ${result.operationId}`);
        // You can optionally poll for the operation status
    } catch (error) {
        console.error(`Error buying phone number ${phoneNumberToBuy}:`, error);
    }
}

// Example usage: Replace with an actual available number found via search
// buyPhoneNumber("+12345678901");
                    

Release a Phone Number

Free up a purchased phone number, making it available for others to acquire.


async function releasePhoneNumber(phoneNumberToRelease) {
    try {
        await client.releasePhoneNumber(phoneNumberToRelease);
        console.log(`Successfully released ${phoneNumberToRelease}.`);
    } catch (error) {
        console.error(`Error releasing phone number ${phoneNumberToRelease}:`, error);
    }
}

// Example usage: Replace with one of your purchased numbers
// releasePhoneNumber("+19876543210");
                    

Update a Phone Number's Capabilities

Modify the capabilities of an existing phone number, such as enabling or disabling SMS or voice.


async function updatePhoneNumberCapabilities(phoneNumberToUpdate) {
    const capabilities = {
        voice: false, // Example: Disable voice
        sms: true     // Keep SMS enabled
    };
    try {
        await client.updatePhoneNumberCapabilities(phoneNumberToUpdate, capabilities);
        console.log(`Successfully updated capabilities for ${phoneNumberToUpdate}.`);
    } catch (error) {
        console.error(`Error updating capabilities for ${phoneNumberToUpdate}:`, error);
    }
}

// Example usage: Replace with one of your purchased numbers
// updatePhoneNumberCapabilities("+1112223333");
                    

API Reference

Explore the detailed methods available in the Phone Numbers client:

listOwnedPhoneNumbers(options?: { skip?: number, top?: number }): PagedAsyncIterableIterator<PhoneNumber>

Retrieves a paginated list of phone numbers owned by the resource.

ParameterTypeDescription
options{ skip?: number, top?: number }Optional. Configuration for pagination.

searchAvailablePhoneNumbers(options: { country: string, capabilities?: Capabilities, phoneNumberType?: PhoneNumberType, assignmentType?: AssignmentType,addAll?:boolean }): PagedAsyncIterableIterator<PhoneNumber>

Searches for available phone numbers based on specified criteria.

ParameterTypeDescription
options.countrystringThe ISO 3166-1 alpha-2 country code (e.g., "US", "GB").
options.capabilitiesCapabilitiesRequired capabilities for the phone number (e.g., { voice: true, sms: true }).
options.phoneNumberTypePhoneNumberTypeOptional. Type of number to search for (e.g., "Local", "Mobile", "TollFree").
options.assignmentTypeAssignmentTypeOptional. Type of assignment (e.g., "Local", "Agent").
options.addAllbooleanOptional. If true, it searches for all available numbers and doesn't consider pagination. Default is false.

buyPhoneNumber(options: { country: string, phoneNumber: string, capabilities?: Capabilities, assignmentType?: AssignmentType }): Promise<PhoneNumberOperation>

Purchases a specific available phone number.

ParameterTypeDescription
options.countrystringThe ISO 3166-1 alpha-2 country code.
options.phoneNumberstringThe E.164 formatted phone number to purchase (e.g., "+12345678901").
options.capabilitiesCapabilitiesOptional. Capabilities to assign to the new number.
options.assignmentTypeAssignmentTypeOptional. Type of assignment.
TypeDescription
Promise<PhoneNumberOperation>A promise that resolves with the operation details, including the operationId.

releasePhoneNumber(phoneNumber: string): Promise<void>

Releases a purchased phone number.

ParameterTypeDescription
phoneNumberstringThe E.164 formatted phone number to release.

updatePhoneNumberCapabilities(phoneNumber: string, capabilities: Capabilities): Promise<void>

Updates the capabilities of an existing purchased phone number.

ParameterTypeDescription
phoneNumberstringThe E.164 formatted phone number to update.
capabilitiesCapabilitiesThe new capabilities to set for the phone number.

Next Steps

Now that you can manage your phone numbers, consider exploring other Azure Communication Services SDKs to integrate voice calls, SMS messaging, and chat into your applications.

Refer to the official documentation for more in-depth examples and advanced scenarios.