다음을 통해 공유


JavaScript용 Azure 통신 전화 번호 클라이언트 라이브러리 - 버전 1.5.0

전화 번호 라이브러리는 전화 번호 관리를 위한 기능을 제공합니다.

구매한 전화 번호는 국가, 번호 유형 및 할당 유형에 따라 많은 기능을 사용할 수 있습니다. 기능의 예로는 SMS 인바운드 및 아웃바운드 사용, PSTN 인바운드 및 아웃바운드 사용이 있습니다. 웹후크 URL을 통해 전화 번호를 봇에 할당할 수도 있습니다.

시작

필수 구성 요소

설치

npm install @azure/communication-phone-numbers

브라우저 지원

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서참조하세요.

주요 개념

이 SDK는 direct offerdirect routing 숫자를 쉽게 관리할 수 있는 기능을 제공합니다.

숫자는 direct offer 지리적, Toll-Free 및 모바일의 세 가지 유형으로 제공됩니다. 지리적 및 휴대폰 요금제는 위치와 연결된 전화 요금제로, 전화 번호의 지역 번호는 지리적 위치의 지역 번호와 연결됩니다. Toll-Free 전화 요금제는 연결된 위치가 아닌 전화 요금제입니다. 예를 들어 미국에서 무료 번호는 800 또는 888과 같은 지역 번호와 함께 제공 될 수 있습니다. PhoneNumbersClient 사용하여 관리됩니다.

direct routing 기능을 사용하면 기존 전화 통신 인프라를 ACS에 연결할 수 있습니다. 구성은 전화 통신 서브넷에 대한 호출을 제대로 처리하기 위해 SIP 트렁크 및 음성 라우팅 규칙을 설정하는 방법을 제공하는 SipRoutingClient사용하여 관리됩니다.

전화 번호 클라이언트

전화 번호 유형

전화번호는 세 가지 유형으로 제공됩니다. 지리적, Toll-Free 및 모바일. Toll-Free 번호는 위치와 연결되지 않습니다. 예를 들어 미국에서 무료 번호는 800 또는 888과 같은 지역 번호와 함께 제공 될 수 있습니다. 지리적 및 휴대폰 번호는 위치와 연결된 전화번호입니다.

동일한 국가의 전화 번호 유형은 해당 전화 번호 유형의 전화 요금제 그룹으로 그룹화됩니다. 예를 들어, 동일한 국가 내의 모든 Toll-Free 전화 번호는 전화 요금제 그룹으로 그룹화됩니다.

숫자 검색 및 획득

전화번호는 전화번호 유형(지리적, 수신자 부담 또는 모바일), 할당 유형(개인 또는 애플리케이션), 통화 및 SMS 기능, 지역 번호 및 전화번호 수를 제공하여 검색 생성 API를 통해 검색할 수 있습니다. 제공된 전화 번호 수량은 15분 동안 예약됩니다. 이 전화 번호 검색은 취소하거나 구매할 수 있습니다. 검색이 취소되면 다른 사용자가 전화 번호를 사용할 수 있게 됩니다. 검색을 구매하면 Azure 리소스에 대한 전화 번호가 획득됩니다.

전화 번호 구성

전화 번호는 기능의 조합을 가질 수 있습니다. 인바운드 및/또는 아웃바운드 통화를 지원하도록 구성하거나 통화에 전화 번호를 사용하지 않을 경우 둘 다 구성할 수 없습니다. SMS 기능도 마찬가지입니다.

전화 번호의 할당 유형을 고려하는 것이 중요합니다. 일부 기능은 특정 할당 유형으로 제한됩니다.

전화번호 찾아보기 및 예약

Browse 및 Reservations API는 장바구니와 같은 환경을 통해 전화 번호를 획득할 수 있는 대체 방법을 제공합니다. 이는 단일 LRO를 사용하여 번호를 찾고 예약하는 검색 작업을 두 개의 개별 동기 단계인 Browse 및 Reservation으로 분할하여 수행됩니다.

찾아보기 작업은 지정된 국가에서 구매할 수 있는 전화 번호의 무작위 샘플을 검색하며, 선택적 필터링 조건을 사용하여 결과 범위를 좁힙니다. 반환된 전화 번호는 고객을 위해 예약되지 않습니다.

예약은 특정 고객에 의해 잠겨 구매를 기다리고 있는 전화 번호의 모음을 나타냅니다. 만료 시간은 마지막 수정 후 15분 또는 생성 시간으로부터 2시간입니다. 예약에는 검색 작업과 달리 다른 국가의 번호가 포함될 수 있습니다. 고객은 예약을 생성, 검색, 수정(번호 추가 및 제거), 삭제 및 구매할 수 있습니다. 예약 구매는 LRO입니다.

SIP 라우팅 클라이언트

직접 라우팅 기능을 사용하면 고객이 제공한 전화 통신 인프라를 Azure Communication Resources에 연결할 수 있습니다. 라우팅 구성을 올바르게 설정하려면 고객이 호출에 대한 SIP 트렁크 구성 및 SIP 라우팅 규칙을 제공해야 합니다. SIP 라우팅 클라이언트는 이 구성을 설정하는 데 필요한 인터페이스를 제공합니다.

호출이 이루어지면 시스템은 대상 번호를 정의된 경로의 정규식 번호 패턴과 일치시키려고 시도합니다. 숫자와 일치하는 첫 번째 경로가 선택됩니다. regex 일치 순서는 구성의 경로 순서와 동일하므로 경로 순서가 중요합니다. 경로가 일치하면 호출이 경로의 트렁크 목록의 첫 번째 트렁크로 라우팅됩니다. 트렁크를 사용할 수 없는 경우 목록에서 다음 트렁크가 선택됩니다.

예제

인증

Communication Services API에 액세스하는 클라이언트 개체를 만들려면 Communication Services 리소스의 connection string 또는 endpointcredential필요합니다. 전화 번호 클라이언트는 Azure Active Directory 자격 증명 또는 API 키 자격 증명을 사용하여 인증할 수 있습니다.

Azure PortalCommunication Services 리소스에서 키 및/또는 연결 문자열을 가져올 수 있습니다. 또한 Azure PortalCommunication Services 리소스에 대한 엔드포인트를 찾을 수 있습니다.

키가 있으면 다음 방법 중 원하는 방법으로 클라이언트를 인증할 수 있습니다.

연결 문자열 사용

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

const connectionString = "endpoint=<endpoint>;accessKey=<accessKey>";
const client = new PhoneNumbersClient(connectionString);
import { SipRoutingClient } from "@azure/communication-phone-numbers";

const connectionString = "endpoint=<endpoint>;accessKey=<accessKey>";
const client = new SipRoutingClient(connectionString);

AzureKeyCredential 액세스 키 사용

키를 사용하여 클라이언트를 초기화하는 경우 적절한 엔드포인트도 제공해야 합니다. Azure Portal Communication Services 리소스에서 이 엔드포인트를 가져올 수 있습니다. 키와 엔드포인트가 있으면 다음 코드로 인증할 수 있습니다.

import { AzureKeyCredential } from "@azure/core-auth";
import { PhoneNumbersClient } from "@azure/communication-phone-numbers";

const credential = new AzureKeyCredential("<key-from-resource>");
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);
import { AzureKeyCredential } from "@azure/core-auth";
import { SipRoutingClient } from "@azure/communication-phone-numbers";

const credential = new AzureKeyCredential("<key-from-resource>");
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

Azure Active Directory 자격 증명 사용

연결 문자열 인증은 대부분의 예제에서 사용되지만 Azure ID 라이브러리사용하여 Azure Active Directory로 인증할 수도 있습니다. 아래에 표시된 DefaultAzureCredential 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용하려면 @azure/identity 패키지를 설치하세요.

npm install @azure/identity

@azure/identity 패키지는 애플리케이션에서 이 작업을 수행하는 데 사용할 수 있는 다양한 자격 증명 유형을 제공합니다. @azure/identity 대한 추가 정보는 시작하기 위한 자세한 내용과 샘플을 제공합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);
import { DefaultAzureCredential } from "@azure/identity";
import { SipRoutingClient } from "@azure/communication-phone-numbers";

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

사용법

다음 섹션에서는 Azure Communication Services 전화 번호 클라이언트를 사용하는 몇 가지 일반적인 작업을 다루는 코드 조각을 제공합니다. 여기서 다루는 시나리오는 다음으로 구성됩니다.

전화 번호클라이언트

SipRouting클라이언트

전화 번호클라이언트

사용 가능한 전화 번호 검색

beginSearchAvailablePhoneNumbers 메서드를 사용하여 전화 번호를 검색하고 예약합니다. 반환된 전화 번호는 15분 동안 예약되며 이 기간 동안 searchId 메서드에 beginPurchasePhoneNumbers 제공하여 구매할 수 있습니다.

beginSearchAvailablePhoneNumbers 장기 실행 작업이며 폴러를 반환합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const searchRequest: SearchAvailablePhoneNumbersRequest = {
  countryCode: "US",
  phoneNumberType: "tollFree",
  assignmentType: "application",
  capabilities: {
    sms: "outbound",
    calling: "none",
  },
  quantity: 1,
};

const searchPoller = await client.beginSearchAvailablePhoneNumbers(searchRequest);

// The search is underway. Wait to receive searchId.
const searchResults = await searchPoller.pollUntilDone();
console.log(`Found phone number: ${searchResults.phoneNumbers[0]}`);
console.log(`searchId: ${searchResults.searchId}`);

beginPurchasePhoneNumbers 방법을 사용하여 검색에서 전화 번호를 구입합니다. 구매한 전화 번호는 클라이언트를 시작할 때 사용되는 Communication Services 리소스에 할당됩니다. searchId 반환된 beginSearchAvailablePhoneNumbers 필요합니다.

beginPurchasePhoneNumbers 장기 실행 작업이며 폴러를 반환합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const searchRequest: SearchAvailablePhoneNumbersRequest = {
  countryCode: "US",
  phoneNumberType: "tollFree",
  assignmentType: "application",
  capabilities: {
    sms: "outbound",
    calling: "none",
  },
  quantity: 1,
};

const searchPoller = await client.beginSearchAvailablePhoneNumbers(searchRequest);

// The search is underway. Wait to receive searchId.
const { searchId, phoneNumbers } = await searchPoller.pollUntilDone();

const purchasePoller = await client.beginPurchasePhoneNumbers(searchId);

// Purchase is underway.
await purchasePoller.pollUntilDone();
console.log(`Successfully purchased ${phoneNumbers[0]}`);

사용 가능한 전화번호 찾아보기 및 예약

Browse 및 Reservations API를 사용하여 전화 번호를 예약합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const browseAvailableNumberRequest: BrowseAvailableNumbersRequest = {
  countryCode: "US",
  phoneNumberType: "tollFree",
};

const browseAvailableNumbers = await client.browseAvailablePhoneNumbers(
  browseAvailableNumberRequest,
  {
    capabilities: {
      calling: "outbound",
    },
    assignmentType: "application",
  },
);
const phoneNumbers = browseAvailableNumbers.phoneNumbers;
const phoneNumbersList = [phoneNumbers[0], phoneNumbers[1]];
const reservationResponse = await client.createOrUpdateReservation(
  {
    reservationId: "reservationId",
  },
  {
    add: phoneNumbersList,
  },
);
const numbersWithError: AvailablePhoneNumber[] = [];
for (const number of Object.values(reservationResponse.phoneNumbers || {})) {
  if (number != null && number.status === "error") {
    numbersWithError.push(number);
  }
}
if (numbersWithError.length > 0) {
  console.log("Errors occurred during reservation");
} else {
  console.log("Reservation operation completed without errors.");
}

구매한 전화 번호 해제

beginReleasePhoneNumber 방법을 사용하여 이전에 구입한 전화 번호를 해제합니다. 릴리스된 전화 번호는 더 이상 Communication Services 리소스와 연결되지 않으며 다른 작업(예: 리소스의 SMS) 해제되는 전화 번호가 필요합니다.

beginReleasePhoneNumber 장기 실행 작업이며 폴러를 반환합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const phoneNumberToRelease = "<phone-number-to-release>";

const releasePoller = await client.beginReleasePhoneNumber(phoneNumberToRelease);

// Release is underway.
await releasePoller.pollUntilDone();
console.log("Successfully release phone number.");

전화 번호 기능 업데이트

beginUpdatePhoneNumberCapabilities 방법을 사용하여 구매한 전화 번호의 기능을 업데이트합니다. 전화 번호는 인바운드 및/또는 아웃바운드 통화 및 SMS를 지원하도록 구성할 수 있습니다.

beginUpdatePhoneNumberCapabilities 장기 실행 작업이며 폴러를 반환합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const phoneNumberToUpdate = "<phone-number-to-update>";

// This will update phone number to send and receive sms, but only send calls.
const updateRequest: PhoneNumberCapabilitiesRequest = {
  sms: "inbound+outbound",
  calling: "outbound",
};

const updatePoller = await client.beginUpdatePhoneNumberCapabilities(
  phoneNumberToUpdate,
  updateRequest,
);

// Update is underway.
const { capabilities } = await updatePoller.pollUntilDone();
console.log(`These are the update capabilities: ${capabilities}`);

구매한 전화 번호 가져오기

getPurchasedPhoneNumber 방법을 사용하여 구매한 전화 번호에 대한 정보를 가져옵니다. 이 정보에는 전화 번호의 유형, 기능, 비용 및 구매 날짜가 포함됩니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const phoneNumberToGet = "<phone-number-to-get>";

const phoneNumber = await client.getPurchasedPhoneNumber(phoneNumberToGet);

console.log(`The id is the same as the phone number: ${phoneNumber.id}`);
console.log(`Phone number type is ${phoneNumber.phoneNumberType}`);

구매 예약

기존 및 활성 예약이 있는 경우 해당 예약의 전화 번호를 구매합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const reservationId = "<reservation-id>";

const purchasePoller = await client.beginReservationPurchase(reservationId);

// Purchase is underway.
const purchaseResult = await purchasePoller.pollUntilDone();
console.log(`Successfully purchased phone numbers in reservation: ${reservationId}`);

구매한 전화 번호 나열

listPurchasedPhoneNumbers 방법을 사용하여 구매한 모든 전화 번호를 페이징합니다.

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

const credential = new DefaultAzureCredential();
const client = new PhoneNumbersClient("<endpoint-from-resource>", credential);

const phoneNumbers = client.listPurchasedPhoneNumbers();

for await (const phoneNumber of phoneNumbers) {
  console.log(`The id is the same as the phone number: ${phoneNumber.id}`);
  console.log(`Phone number type is ${phoneNumber.phoneNumberType}`);
}

SipRouting클라이언트

SIP 트렁크 및 경로 검색

현재 구성된 트렁크 또는 경로 목록을 가져옵니다.

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

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

const trunks = client.listTrunks();
const routes = client.listRoutes();
for await (const trunk of trunks) {
  console.log(`Trunk ${trunk.fqdn}:${trunk.sipSignalingPort}`);
}

for await (const route of routes) {
  console.log(`Route ${route.name} with pattern ${route.numberPattern}`);
  console.log(`Route's trunks: ${route.trunks?.join()}`);
}

SIP 트렁크 및 경로 바꾸기

현재 구성된 트렁크 또는 경로 목록을 새 값으로 바꿉니다.

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

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

await client.setTrunks([
  {
    fqdn: "sbc.one.domain.com",
    sipSignalingPort: 1234,
  },
  {
    fqdn: "sbc.two.domain.com",
    sipSignalingPort: 1234,
  },
]);

await client.setRoutes([
  {
    name: "First Route",
    description: "route's description",
    numberPattern: "^+[1-9][0-9]{3,23}$",
    trunks: ["sbc.one.domain.com"],
  },
  {
    name: "Second Route",
    description: "route's description",
    numberPattern: "^.*$",
    trunks: ["sbc.two.domain.com", "sbc.one.domain.com"],
  },
]);

단일 트렁크 검색

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

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

const trunk = await client.getTrunk("sbc.one.domain.com");
if (trunk) {
  console.log(`Trunk ${trunk.fqdn}:${trunk.sipSignalingPort}`);
} else {
  console.log("Trunk not found");
}

단일 트렁크 설정

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

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

await client.setTrunk({
  fqdn: "sbc.one.domain.com",
  sipSignalingPort: 4321,
});

단일 트렁크 삭제

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

const credential = new DefaultAzureCredential();
const client = new SipRoutingClient("<endpoint-from-resource>", credential);

await client.deleteTrunk("sbc.one.domain.com");

문제 해결

로깅

로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info설정합니다. 또는 setLogLevel@azure/logger 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서확인할 수 있습니다.

다음 단계

이 라이브러리를 사용하는 방법에 대한 자세한 예제는 샘플 디렉터리를 살펴보세요.

기여

이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

  • Javascript용 Microsoft Azure SDK