快速入門:取得和管理電話號碼

重要

SMS 和 PSTN 功能取決於您使用的電話號碼,以及您根據 Azure 帳單地址所決定在內運作的國家/地區。 如需詳細資訊,請瀏覽訂用 帳戶資格 檔。

重要

如需大量訂單,或如果您的所需電話號碼無法使用,請造訪 此頁面 以取得進一步的協助。

必要條件

取得電話號碼

若要開始布建數位,請移至 Azure 入口網站 上的通訊服務資源。

顯示通訊服務資源主頁面的螢幕快照。

搜尋可用的 電話 號碼

瀏覽至資源選單中的 [電話 數位] 刀鋒視窗。

顯示通訊服務資源電話頁面的螢幕快照。

按 [ 取得] 按鈕以啟動精靈。 [電話 號碼] 刀鋒視窗上的精靈會逐步引導您完成一系列問題,以協助您選擇最符合您案例的電話號碼。

您必須先選擇 您想要布建電話號碼的國家/地區 。 選取國家/地區之後,您必須選取 最適合您需求的使用案例

顯示 [取得電話號碼] 檢視的螢幕快照。

選取您的電話號碼功能

設定您的電話號碼分成兩個步驟:

  1. 數位類型的選取範圍
  2. 選取 數位功能

您可以從兩種電話號碼類型中選取: 本機付費電話。 當您選取數字類型時,就可以選擇功能。

在我們的範例中,我們已選取 [撥打電話] 和 [傳送和接收簡訊] 功能的免付費電話號碼類型

顯示 [選取功能] 檢視的螢幕快照。

從這裡,按兩下頁面底部的 [ 下一步:數位 ] 按鈕,以自定義您想要布建的電話號碼。

自訂電話號碼

在 [ 號碼 ] 頁面上,您將自定義您想要布建的電話號碼。

顯示 [數位] 選取頁面的螢幕快照。

注意

本快速入門顯示 付費電話號碼類型自定義流程。 如果您已選擇 [ 本機 數位] 類型,則體驗可能會稍有不同,但最終結果會相同。

從可用的 [區域代碼] 列表中選擇 [區域代碼],然後輸入您想要布建的數量,然後按兩下 [搜尋] 以尋找符合所選需求的號碼。 符合您需求的電話號碼會連同其每月成本一起顯示。

顯示 [號碼] 選取頁面的螢幕快照,其中包含保留號碼。

注意

可用性取決於 [數字類型]、[位置] 和您選取的功能。 在交易到期之前,號碼會保留一小段時間。 如果交易到期,您必須重新選取數位。

若要檢視購買摘要並下訂單,請按下頁面底部的 [ 下一步:摘要] 按鈕。

購買 電話 號碼

摘要頁面會檢閱 [號碼類型]、[功能]、[電話 號碼] 和 [每月總成本] 來布建電話號碼。

注意

顯示的價格是 每月週期性費用 ,涵蓋將所選電話號碼租用給您的成本。 此檢視 中不包含隨用隨付成本,這是您在撥打或接聽電話時所產生的成本 。 價目表可 在這裡取得。 這些成本取決於呼叫的數字類型和目的地。 例如,從西雅圖區域號碼到紐約地區號碼的通話每分鐘價格,以及從相同號碼到英國行動電話號碼的通話可能會不同。

最後,按下 頁面底部的 [下單 ] 以確認。

顯示 [摘要] 頁面的螢幕快照,其中顯示 [數字類型]、[功能]、[電話 編號] 和 [每月總成本]。

在 Azure 入口網站 上尋找您的電話號碼

瀏覽至 Azure 入口網站上的 Azure 通訊服務 資源:

顯示通訊服務資源主頁面的螢幕快照。

選取功能表中的 [電話 號碼] 刀鋒視窗來管理您的電話號碼。

顯示通訊服務資源電話號碼頁面的螢幕快照。

注意

可能需要幾分鐘的時間,布建的數位才會顯示在此頁面上。

更新 電話 數位功能

[電話 號碼] 頁面上,您可以選取要設定的電話號碼。

顯示更新功能頁面的螢幕快照。

從可用的選項中選取功能,然後按下 [ 儲存 ] 以套用您的選取專案。

版本 電話 號碼

在 [ 號碼 ] 頁面上,您可以釋出電話號碼。

顯示發行電話號碼頁面的螢幕快照。

選取您要釋放的電話號碼,然後按兩下 [發行 ] 按鈕。

重要

Azure 通訊服務 這項功能目前處於預覽狀態。

預覽 API 和 SDK 在沒有服務等級協議的情況下提供。 我們建議您不要將它們用於生產工作負載。 某些功能可能不受支援,或可能具有限制的功能。

如需詳細資訊,請檢閱 Microsoft Azure 預覽版的補充使用規定。

Azure 通訊服務 引進了購買電話號碼的新用戶體驗。 此體驗目前正在正式發行前小眾測試版中,您可能會在購買 Azure 入口網站 中的電話號碼時介紹此體驗。 如果您有此體驗的意見反應,請毫不猶豫地透過 Azure 入口網站 延伸模組上的 [提供意見反應] 按鈕來提供。

必要條件

購買電話號碼

  1. 流覽至 Azure 入口網站 中的通訊服務資源。

    顯示通訊服務資源主頁面的螢幕快照。

  2. 在通訊服務資源概觀中,選取左側功能表中的 [電話 數位] 選項。

    顯示通訊服務資源電話號碼頁面的螢幕快照。

  3. 選取 頁面左上方的 [取得 ],以購買您的電話號碼。 選取此選項會啟動我們的購物精靈:

    顯示電話號碼購物車搜尋精靈的螢幕快照。

  4. 選擇您想要布建電話號碼的國家/地區。 國家/地區可用性是以 Azure 訂用帳戶的計費位置為基礎。 如需每個國家/地區可用號碼的詳細資訊,請參閱 這裡。 接下來,您將選擇 數字類型。 您可以從兩種電話號碼類型中選取: 本機付費電話。

  5. 選取 [ 搜尋 ] 以提取符合所選準則的數位。 您有各種篩選條件可搜尋符合您需求的數位,包括:

    • 使用案例:這是針對您是否使用此號碼從應用程式 (A2P) 或人類代理程式 (P2P) 呼叫。
    • 通話:這是用來判斷您想要撥打電話號碼的通話功能:撥打電話和/或接聽電話。
    • SMS:這是用來判斷您想要用於電話號碼的 SMS 功能:傳送和/或接收簡訊。
    • 自訂:您也可以新增自定義篩選,以取得電話號碼中的特定前置詞或數位集。

    顯示具有可用電話號碼的電話號碼購買頁面的螢幕快照。

  6. 一旦您找到您選擇的電話號碼或號碼,請選取 [新增至購物車] 以保存電話語音購物車 中的號碼。 這些號碼會在自動清除購物車之前保留 16 分鐘。

    顯示購物車中具有兩個電話號碼的電話號碼螢幕快照。

    注意

    顯示的價格是 每月週期性費用 ,涵蓋將所選電話號碼租用給您的成本。 此檢視 中不包含隨用隨付成本,這是您在撥打或接聽電話時所產生的成本 。 價目表可 在這裡取得。 這些成本取決於呼叫的數字類型和目的地。 例如,從西雅圖區域號碼到紐約地區號碼的通話每分鐘價格,以及從相同號碼到英國行動電話號碼的通話可能會不同。

  7. 選取 [ 下一步 ] 以檢閱您的購買。 若要完成購買,請選取 [ 立即購買]。

    顯示檢閱和購買2個電話號碼的螢幕快照。

  8. 您可以在 電話 編號頁面上找到已購買的數位。 布建數位可能需要幾分鐘的時間。

    [電話號碼] 頁面的螢幕快照,其中新購買的電話號碼以紅色框線框線。

更新 電話 數位功能

[電話 號碼] 頁面上,您可以選取要設定的電話號碼。

顯示更新功能頁面的螢幕快照。

從可用的選項中選取功能,然後選取 [ 儲存 ] 以套用您的選取專案。

版本 電話 號碼

在 [ 號碼 ] 頁面上,您可以釋出電話號碼。

顯示發行電話號碼頁面的螢幕快照。

選取您要發行的電話號碼,然後在 [發行] 按鈕上選取 。

必要條件

設定

新增擴充功能

使用 az extension 命令新增 Azure CLI 的 Azure 通訊服務 擴充功能。

az extension add --name communication

登入 Azure CLI

您必須登入 Azure CLI。 您可以從終端機登入 az login ,並提供您的認證。

Operations

列出已購買的電話號碼(秒)

執行下列命令以擷取所有已購買的電話號碼。

az communication phonenumber list --connection-string "<yourConnectionString>"

在程式代碼中進行此取代:

  • <yourConnectionString> 取代為實際的連接字串。

取得購買的電話號碼詳細數據

執行下列命令以取得已購買電話號碼的電話號碼詳細數據。

az communication phonenumber show --phonenumber <purchasedPhoneNumber> --connection-string "<yourConnectionString>"

在程式代碼中進行這些取代:

  • 將取代 <purchasedPhoneNumber> 為您的通訊服務資源相關聯的電話號碼。
  • <yourConnectionString> 取代為實際的連接字串。

注意

Azure CLI 選項僅提供列出及顯示電話號碼的功能。 它不支援其他作業,例如搜尋、購買、編輯或發行電話號碼。

(選擇性)使用 Azure CLI 電話號碼作業而不傳入 連接字串

您可以將環境變數設定AZURE_COMMUNICATION_CONNECTION_STRING為使用 Azure CLI 電話號碼作業,而不需要使用 --connection_string 傳入 連接字串。 若要設定環境變數,請開啟控制台視窗,然後從下列索引標籤中選取您的作業系統。 將 <yourConnectionString> 用實際的連接字串取代。

開啟主控台視窗,然後輸入下列命令:

setx AZURE_COMMUNICATION_CONNECTION_STRING "<yourConnectionString>"

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

必要條件

先決條件檢查

  • 在終端機或命令視窗中,執行 dotnet 命令來檢查是否已安裝 .NET 用戶端連結庫。

設定

建立新的 C# 應用程式

在主控台視窗中 (例如 cmd、PowerShell 或 Bash),使用 dotnet new 命令建立名為 PhoneNumbersQuickstart 的新主控台應用程式。 此命令會建立簡單的 "Hello World" C# 專案,內含單一原始程式檔:Program.cs

dotnet new console -o PhoneNumbersQuickstart

將您的目錄變更為新建立的應用程式資料夾,然後使用 dotnet build 命令來編譯您的應用程式。

cd PhoneNumbersQuickstart
dotnet build

Install the package

在應用程式目錄中,使用 dotnet add package 命令安裝適用於 .NET 套件的 Azure Communication 電話 Numbers 用戶端連結庫。

dotnet add package Azure.Communication.PhoneNumbers --version 1.0.0

using將指示詞新增至Program.cs端以包含命名空間。

using System;
using System.Linq;
using System.Threading.Tasks;
using Azure.Communication.PhoneNumbers;

將函式簽章更新 Main 為異步。

static async Task Main(string[] args)
{
  ...
}

驗證用戶端

電話 號碼用戶端可以使用從 Azure 入口網站 中的 Azure 通訊服務 資源取得的 連接字串 進行驗證。

// Get a connection string to our Azure Communication Services resource.
var connectionString = "<connection_string>";
var client = new PhoneNumbersClient(connectionString);

電話 Number 用戶端也可以選擇使用 Microsoft Entra 驗證進行驗證。 使用此選項時, AZURE_CLIENT_SECRET必須設定、 AZURE_CLIENT_IDAZURE_TENANT_ID 環境變數以進行驗證。

// Get an endpoint to our Azure Communication Services resource.
var endpoint = new Uri("<endpoint_url>");
TokenCredential tokenCredential = new DefaultAzureCredential();
client = new PhoneNumbersClient(endpoint, tokenCredential);

管理電話號碼

搜尋可用的電話號碼

若要購買電話號碼,您必須先搜尋可用的電話號碼。 若要搜尋電話號碼,請提供分區代碼、指派類型、電話號碼功能電話號碼類型和數量。 請注意,針對免付費電話號碼類型,提供區域代碼是選擇性的。

var capabilities = new PhoneNumberCapabilities(calling:PhoneNumberCapabilityType.None, sms:PhoneNumberCapabilityType.Outbound);
var searchOptions = new PhoneNumberSearchOptions { AreaCode = "833", Quantity = 1 };

var searchOperation = await client.StartSearchAvailablePhoneNumbersAsync("US", PhoneNumberType.TollFree, PhoneNumberAssignmentType.Application, capabilities, searchOptions);
await searchOperation.WaitForCompletionAsync();

購買電話號碼

搜尋電話號碼的結果為 PhoneNumberSearchResult。 這包含 SearchId 可傳遞至購買號碼 API 的 ,以取得搜尋中的數位。 請注意,呼叫購買電話號碼 API 會導致您的 Azure 帳戶收費。

var purchaseOperation = await client.StartPurchasePhoneNumbersAsync(searchOperation.Value.SearchId);
await purchaseOperation.WaitForCompletionResponseAsync();

取得電話號碼

購買號碼之後,您可以從用戶端擷取。

var getPhoneNumberResponse = await client.GetPurchasedPhoneNumberAsync("+14255550123");
Console.WriteLine($"Phone number: {getPhoneNumberResponse.Value.PhoneNumber}, country code: {getPhoneNumberResponse.Value.CountryCode}");

您也可以擷取所有已購買的電話號碼。

var purchasedPhoneNumbers = client.GetPurchasedPhoneNumbersAsync();
await foreach (var purchasedPhoneNumber in purchasedPhoneNumbers)
{
    Console.WriteLine($"Phone number: {purchasedPhoneNumber.PhoneNumber}, country code: {purchasedPhoneNumber.CountryCode}");
}

更新電話號碼功能

透過購買的數位,您可以更新功能。

var updateCapabilitiesOperation = await client.StartUpdateCapabilitiesAsync("+14255550123", calling: PhoneNumberCapabilityType.Outbound, sms: PhoneNumberCapabilityType.InboundOutbound);
await updateCapabilitiesOperation.WaitForCompletionAsync();

發行電話號碼

您可以釋放購買的電話號碼。

var releaseOperation = await client.StartReleasePhoneNumberAsync("+14255550123");
await releaseOperation.WaitForCompletionResponseAsync();

執行程式碼

使用 dotnet run 命令從應用程式目錄執行應用程式。

dotnet run

範例程式碼

您可以從 GitHub 下載範例應用程式

必要條件

建立

建立新的 Java 應用程式

開啟終端機或命令視窗。 流覽至您要建立 Java 應用程式的目錄。 執行下列命令,從 maven-archetype-quickstart 範本產生 Java 專案。

mvn archetype:generate -DgroupId=com.communication.quickstart -DartifactId=communication-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

您會發現『generate』 工作已建立與 相同名稱的 artifactId目錄。 在此目錄下,src/main/java 目錄包含專案原始程式碼、 src/test/java directory 包含測試來源,而 pom.xml 檔案是專案的 Project 物件模型或 POM。

Install the package

文本編輯器中開啟pom.xml 檔案。 將下列相依性元素新增至相依性群組。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-common</artifactId>
    <version>1.0.0</version>
</dependency>

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-phonenumbers</artifactId>
    <version>1.0.0</version>
</dependency>

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.2.3</version>
</dependency>

設定應用程式架構

從專案目錄:

  1. 流覽至 /src/main/java/com/communication/quickstart 目錄
  2. 編輯器中開啟App.java 檔案
  3. System.out.println("Hello world!");取代語句
  4. 新增 import 指示詞

使用下列程式代碼開始:

import com.azure.communication.phonenumbers.*;
import com.azure.communication.phonenumbers.models.*;
import com.azure.core.http.rest.*;
import com.azure.core.util.Context;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.SyncPoller;
import com.azure.identity.*;
import java.io.*;

public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Communication Services - Phone Numbers Quickstart");
        // Quickstart code goes here
    }
}

驗證 電話 號碼用戶端

電話 NumberClientBuilder 已啟用使用 Microsoft Entra 驗證

// You can find your endpoint and access key from your resource in the Azure portal
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";

PhoneNumbersClient phoneNumberClient = new PhoneNumbersClientBuilder()
    .endpoint(endpoint)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

或者,您也可以使用來自通訊資源的端點和存取金鑰進行驗證。

// You can find your connection string from your resource in the Azure portal
String connectionString = "endpoint=https://<RESOURCE_NAME>.communication.azure.com/;accesskey=<ACCESS_KEY>";

PhoneNumbersClient phoneNumberClient = new PhoneNumbersClientBuilder()
    .connectionString(connectionString)
    .buildClient();

管理 電話 數位

搜尋可用的 電話 編號

若要購買電話號碼,您必須先搜尋可用的電話號碼。 若要搜尋電話號碼,請提供分區代碼、指派類型、電話號碼功能電話號碼類型和數量。 請注意,針對免付費電話號碼類型,提供區域代碼是選擇性的。

 PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities()
    .setCalling(PhoneNumberCapabilityType.INBOUND)
    .setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setAreaCode("833").setQuantity(1);

SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = phoneNumberClient
    .beginSearchAvailablePhoneNumbers("US", PhoneNumberType.TOLL_FREE, PhoneNumberAssignmentType.APPLICATION, capabilities, searchOptions, Context.NONE);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
String searchId = "";

if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
    PhoneNumberSearchResult searchResult = poller.getFinalResult();
    searchId = searchResult.getSearchId();
    System.out.println("Searched phone numbers: " + searchResult.getPhoneNumbers());
    System.out.println("Search expires by: " + searchResult.getSearchExpiresBy());
    System.out.println("Phone number costs:" + searchResult.getCost().getAmount());
}

購買 電話 號碼

搜尋電話號碼的結果是 電話 NumberSearchResult。 這包含 searchId 可傳遞至購買號碼 API 的 ,以取得搜尋中的數位。 請注意,呼叫購買電話號碼 API 會導致您的 Azure 帳戶收費。

PollResponse<PhoneNumberOperation> purchaseResponse = phoneNumberClient.beginPurchasePhoneNumbers(searchId, Context.NONE).waitForCompletion();
System.out.println("Purchase phone numbers operation is: " + purchaseResponse.getStatus());

取得 電話 數位

購買號碼之後,您可以從用戶端擷取。

PurchasedPhoneNumber phoneNumber = phoneNumberClient.getPurchasedPhoneNumber("+14255550123");
System.out.println("Phone Number Country Code: " + phoneNumber.getCountryCode());

您也可以擷取所有已購買的電話號碼。

PagedIterable<PurchasedPhoneNumber> phoneNumbers = phoneNumberClient.listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber phoneNumber = phoneNumbers.iterator().next();
System.out.println("Phone Number Country Code: " + phoneNumber.getCountryCode());

更新 電話 數位功能

透過購買的數位,您可以更新功能。

PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities
    .setCalling(PhoneNumberCapabilityType.INBOUND)
    .setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);

SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber> poller = phoneNumberClient.beginUpdatePhoneNumberCapabilities("+18001234567", capabilities, Context.NONE);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
    PurchasedPhoneNumber phoneNumber = poller.getFinalResult();
    System.out.println("Phone Number Calling capabilities: " + phoneNumber.getCapabilities().getCalling()); //Phone Number Calling capabilities: inbound
    System.out.println("Phone Number SMS capabilities: " + phoneNumber.getCapabilities().getSms()); //Phone Number SMS capabilities: inbound+outbound
}

版本 電話 號碼

您可以釋放購買的電話號碼。

PollResponse<PhoneNumberOperation> releaseResponse =
    phoneNumberClient.beginReleasePhoneNumber("+14255550123", Context.NONE).waitForCompletion();
System.out.println("Release phone number operation is: " + releaseResponse.getStatus());

執行程式碼

流覽至包含pom.xml檔案的目錄,並使用下列mvn命令編譯專案。

mvn compile

然後,建置套件。

mvn package

執行下列 mvn 命令以執行應用程式。

mvn exec:java -Dexec.mainClass="com.communication.quickstart.App" -Dexec.cleanupDaemonThreads=false

應用程式的輸出會描述已完成的每個動作:

Azure Communication Services - Phone Numbers Quickstart

Searched phone numbers: [+18001234567]

Purchase phone numbers operation is: SUCCESSFULLY_COMPLETED

Phone Number Country Code: US

Phone Number Calling capabilities: inbound

Phone Number SMS capabilities: inbound

Release phone number operation is: SUCCESSFULLY_COMPLETED

必要條件

設定

建立新的 Python 應用程式

開啟終端機或命令視窗,然後為您的應用程式建立新的目錄,然後流覽至該目錄。

mkdir phone-numbers-quickstart && cd phone-numbers-quickstart

使用文字編輯器在專案根目錄中建立名為 phone_numbers_sample.py 的檔案,並新增下列程序代碼。 我們將在下列各節中新增其餘快速入門程序代碼。

import os
from azure.communication.phonenumbers import PhoneNumbersClient

try:
   print('Azure Communication Services - Phone Numbers Quickstart')
   # Quickstart code goes here
except Exception as ex:
   print('Exception:')
   print(ex)

Install the package

在應用程式目錄中,使用 pip install 命令安裝適用於 Python 套件的 Azure 通訊服務 管理員 istration 用戶端連結庫。

pip install azure-communication-phonenumbers

驗證 電話 號碼用戶端

PhoneNumbersClient已啟用 使用 Microsoft Entra 驗證。 DefaultAzureCredential使用 對像是開始使用 Microsoft Entra ID 的最簡單方式,您可以使用 命令加以安裝pip install

pip install azure-identity

建立 DefaultAzureCredential 物件需要您擁有 AZURE_CLIENT_IDAZURE_CLIENT_SECRET,且 AZURE_TENANT_ID 已經設定為環境變數,以及來自已註冊 Microsoft Entra 應用程式的對應值。

如需如何取得這些環境變數的快速增加,您可以遵循 從 CLI 快速入門設定服務主體。

安裝連結 azure-identity 庫之後,我們可以繼續驗證用戶端。

import os
from azure.communication.phonenumbers import PhoneNumbersClient
from azure.identity import DefaultAzureCredential

# You can find your endpoint from your resource in the Azure portal
endpoint = 'https://<RESOURCE_NAME>.communication.azure.com'
try:
    print('Azure Communication Services - Phone Numbers Quickstart')
    credential = DefaultAzureCredential()
    phone_numbers_client = PhoneNumbersClient(endpoint, credential)
except Exception as ex:
    print('Exception:')
    print(ex)

或者,您也可以使用來自通訊資源的端點和存取金鑰進行驗證。

import os
from azure.communication.phonenumbers import PhoneNumbersClient

# You can find your connection string from your resource in the Azure portal
connection_string = 'https://<RESOURCE_NAME>.communication.azure.com/;accesskey=<YOUR_ACCESS_KEY>'
try:
    print('Azure Communication Services - Phone Numbers Quickstart')
    phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_string)
except Exception as ex:
    print('Exception:')
    print(ex)

函式

PhoneNumbersClient驗證之後,我們可以開始處理它可以執行的不同函式。

搜尋可用的 電話 號碼

若要購買電話號碼,您必須先搜尋任何可用的電話號碼。 若要搜尋電話號碼,請提供區域代碼、指派類型、電話號碼功能電話號碼類型和數量(預設數量設定為1)。 請注意,針對免付費電話號碼類型,提供區域代碼是選擇性的。

import os
from azure.communication.phonenumbers import PhoneNumbersClient, PhoneNumberCapabilityType, PhoneNumberAssignmentType, PhoneNumberType, PhoneNumberCapabilities
from azure.identity import DefaultAzureCredential

# You can find your endpoint from your resource in the Azure portal
endpoint = 'https://<RESOURCE_NAME>.communication.azure.com'
try:
    print('Azure Communication Services - Phone Numbers Quickstart')
    credential = DefaultAzureCredential()
    phone_numbers_client = PhoneNumbersClient(endpoint, credential)
    capabilities = PhoneNumberCapabilities(
        calling = PhoneNumberCapabilityType.INBOUND,
        sms = PhoneNumberCapabilityType.INBOUND_OUTBOUND
    )
    search_poller = phone_numbers_client.begin_search_available_phone_numbers(
        "US",
        PhoneNumberType.TOLL_FREE,
        PhoneNumberAssignmentType.APPLICATION,
        capabilities,
        polling = True
    )
    search_result = search_poller.result()
    print ('Search id: ' + search_result.search_id)
    phone_number_list = search_result.phone_numbers
    print('Reserved phone numbers:')
    for phone_number in phone_number_list:
        print(phone_number)

except Exception as ex:
    print('Exception:')
    print(ex)

購買 電話 號碼

搜尋電話號碼的結果為 PhoneNumberSearchResult。 這包含 searchId 可傳遞至購買號碼 API 的 ,以取得搜尋中的數位。 請注意,呼叫購買電話號碼 API 會導致您的 Azure 帳戶收費。

import os
from azure.communication.phonenumbers import (
    PhoneNumbersClient,
    PhoneNumberCapabilityType,
    PhoneNumberAssignmentType,
    PhoneNumberType,
    PhoneNumberCapabilities
)
from azure.identity import DefaultAzureCredential

# You can find your endpoint from your resource in the Azure portal
endpoint = 'https://<RESOURCE_NAME>.communication.azure.com'
try:
    print('Azure Communication Services - Phone Numbers Quickstart')
    credential = DefaultAzureCredential()
    phone_numbers_client = PhoneNumbersClient(endpoint, credential)
    capabilities = PhoneNumberCapabilities(
        calling = PhoneNumberCapabilityType.INBOUND,
        sms = PhoneNumberCapabilityType.INBOUND_OUTBOUND
    )
    search_poller = phone_numbers_client.begin_search_available_phone_numbers(
        "US",
        PhoneNumberType.TOLL_FREE,
        PhoneNumberAssignmentType.APPLICATION,
        capabilities,
        area_code="833",
        polling = True
    )
    search_result = poller.result()
    print ('Search id: ' + search_result.search_id)
    phone_number_list = search_result.phone_numbers
    print('Reserved phone numbers:')
    for phone_number in phone_number_list:
        print(phone_number)

    purchase_poller = phone_numbers_client.begin_purchase_phone_numbers(search_result.search_id, polling = True)
    purchase_poller.result()
    print("The status of the purchase operation was: " + purchase_poller.status())
except Exception as ex:
    print('Exception:')
    print(ex)

取得購買的電話號碼

購買號碼之後,您可以從用戶端擷取。

purchased_phone_number_information = phone_numbers_client.get_purchased_phone_number("+18001234567")
print('Phone number: ' + purchased_phone_number_information.phone_number)
print('Country code: ' + purchased_phone_number_information.country_code)

您也可以擷取所有已購買的電話號碼。

purchased_phone_numbers = phone_numbers_client.list_purchased_phone_numbers()
print('Purchased phone numbers:')
for purchased_phone_number in purchased_phone_numbers:
    print(purchased_phone_number.phone_number)

更新 電話 數位功能

您可以更新先前購買電話號碼的功能。

update_poller = phone_numbers_client.begin_update_phone_number_capabilities(
    "+18001234567",
    PhoneNumberCapabilityType.OUTBOUND,
    PhoneNumberCapabilityType.OUTBOUND,
    polling = True
)
update_poller.result()
print('Status of the operation: ' + update_poller.status())

版本 電話 號碼

您可以釋放購買的電話號碼。

release_poller = phone_numbers_client.begin_release_phone_number("+18001234567")
release_poller.result()
print('Status of the operation: ' + release_poller.status())

執行程式碼

從主控台提示字元,流覽至包含phone_numbers_sample.py檔案的目錄,然後執行下列 Python 命令來執行應用程式。

python phone_numbers_sample.py

必要條件

  • 具有有效訂用帳戶的 Azure 帳戶。 免費建立帳戶
  • Node.js主動 LTS 和維護 LTS 版本(建議使用 8.11.1 和 10.14.1)。
  • 作用中的通訊服務資源和 連接字串。 建立通訊服務資源

先決條件檢查

  • 在終端機或命令視窗中,執行 node --version 以檢查是否已安裝Node.js。

設定

建立新的Node.js應用程式

首先,開啟終端機或命令視窗,為您的應用程式建立新的目錄,然後流覽至該目錄。

mkdir phone-numbers-quickstart && cd phone-numbers-quickstart

執行 npm init -y 以使用預設設定建立 package.json 檔案。

npm init -y

在您剛建立的目錄根目錄中,建立名為 phone-numbers-quickstart.js 的檔案。 將下列代碼段新增至其中:

async function main() {
    // quickstart code will here
}

main();

Install the package

npm install使用 命令來安裝適用於 JavaScript 的 Azure 通訊服務 電話 Numbers 用戶端連結庫。

npm install @azure/communication-phone-numbers --save

選項--save會將連結庫新增為package.json檔案中的相依性。

驗證用戶端

從客戶端連結庫匯入 電話 NumbersClient,並使用您的 連接字串 加以具現化。 下列程式代碼會從名為COMMUNICATION_SERVICES_CONNECTION_STRING的環境變數擷取資源的 連接字串。 瞭解如何管理資源的 連接字串

將下列程式代碼新增至phone-numbers-quickstart.js端:

const { PhoneNumbersClient } = require('@azure/communication-phone-numbers');

// This code demonstrates how to fetch your connection string
// from an environment variable.
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

// Instantiate the phone numbers client
const phoneNumbersClient = new PhoneNumbersClient(connectionString);

管理電話號碼

搜尋可用的電話號碼

若要購買電話號碼,您必須先搜尋可用的電話號碼。 若要搜尋電話號碼,請提供分區代碼、指派類型、電話號碼功能電話號碼類型和數量。 請注意,針對免付費電話號碼類型,提供區域代碼是選擇性的。

將下列代碼段新增至您的 main 函式:

/**
 * Search for Available Phone Number
 */

// Create search request
const searchRequest = {
    countryCode: "US",
    phoneNumberType: "tollFree",
    assignmentType: "application",
    capabilities: {
      sms: "outbound",
      calling: "none"
    },
    areaCode: "833",
    quantity: 1
  };

const searchPoller = await phoneNumbersClient.beginSearchAvailablePhoneNumbers(searchRequest);

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

console.log(`Found phone number: ${phoneNumber}`);
console.log(`searchId: ${searchId}`);

購買電話號碼

搜尋電話號碼的結果為 PhoneNumberSearchResult。 這包含 searchId 可傳遞至購買號碼 API 的 ,以取得搜尋中的數位。 請注意,呼叫購買電話號碼 API 會導致您的 Azure 帳戶收費。

將下列代碼段新增至您的 main 函式:

/**
 * Purchase Phone Number
 */

const purchasePoller = await phoneNumbersClient.beginPurchasePhoneNumbers(searchId);

// Purchase is underway.
await purchasePoller.pollUntilDone();
console.log(`Successfully purchased ${phoneNumber}`);

更新電話號碼功能

現在已購買電話號碼,新增下列程式代碼以更新其功能:

/**
 * Update Phone Number Capabilities
 */

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

const updatePoller = await phoneNumbersClient.beginUpdatePhoneNumberCapabilities(
  phoneNumber,
  updateRequest
);

// Update is underway.
await updatePoller.pollUntilDone();
console.log("Phone number updated successfully.");

取得購買的電話號碼

購買號碼之後,您可以從用戶端擷取。 將下列程式代碼新增至您的 main 函式,以取得您剛才購買的電話號碼:

/**
 * Get Purchased Phone Number
 */

const { capabilities } = await phoneNumbersClient.getPurchasedPhoneNumber(phoneNumber);
console.log("These capabilities:", capabilities, "should be the same as these:", updateRequest, ".");

您也可以擷取所有已購買的電話號碼。

const purchasedPhoneNumbers = await phoneNumbersClient.listPurchasedPhoneNumbers();

for await (const purchasedPhoneNumber of purchasedPhoneNumbers) {
  console.log(`Phone number: ${purchasedPhoneNumber.phoneNumber}, country code: ${purchasedPhoneNumber.countryCode}.`);
}

發行電話號碼

您現在可以釋放購買的電話號碼。 將下列代碼段新增至您的 main 函式:

/**
 * Release Purchased Phone Number
 */

const releasePoller = await phoneNumbersClient.beginReleasePhoneNumber(phoneNumber);

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

執行程式碼

node使用 命令來執行您新增至phone-numbers-quickstart.js檔案的程序代碼。

node phone-numbers-quickstart.js

疑難排解

常見問題和問題:

  • 當電話號碼發行時,電話號碼會顯示在 ACS 資源 Azure 入口網站 直到計費週期結束為止。 在計費週期結束之前,也無法重新購買。

  • 刪除通訊服務資源時,會自動同時釋放與該資源相關聯的電話號碼。

下一步

在本快速入門中,您已瞭解如何: