Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Get started with the Phone Numbers client library for JavaScript to look up operator information for phone numbers. Use the operator information to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.
Примечание.
To view the source code for this example, see Manage Phone Numbers - JavaScript | GitHub.
Предпосылки
- Учетная запись Azure с активной подпиской. Создайте учетную запись бесплатно .
- Node.js Active LTS (long-term support) and Maintenance LTS versions (8.11.1 and 10.14.1 recommended).
- An active Communication Services resource and connection string. Создайте ресурс Служб коммуникации.
Проверка предварительных условий
In a terminal or command window, run the node --version
command to check that Node.js is installed.
Setting up
To set up an environment for sending lookup queries, take the steps in the following sections.
Создание нового приложения Node.js
In a terminal or command window, create a new directory for your app and navigate to it.
mkdir number-lookup-quickstart && cd number-lookup-quickstart
Воспользуйтесь командой npm init -y
, чтобы создать файл package.json с параметрами по умолчанию.
npm init -y
Create a file called number-lookup-quickstart.js in the root of the directory you created. Add the following snippet to it:
async function main() {
// quickstart code will go here
}
main();
Установка пакета
Use the npm install
command to install the Azure Communication Services Phone Numbers client library for JavaScript.
npm install @azure/[email protected] --save
The --save
option adds the library as a dependency in your package.json file.
Примеры кода
аутентификация клиента;
Import the PhoneNumbersClient from the client library and instantiate it with your connection string, which can be acquired from an Azure Communication Services resource in the Azure portal. Using a COMMUNICATION_SERVICES_CONNECTION_STRING
environment variable is recommended to avoid putting your connection string in plain text within your code. Узнайте, как управлять строкой подключения вашего ресурса.
Add the following code to the top of number-lookup-quickstart.js:
const { PhoneNumbersClient } = require('@azure/communication-phone-numbers');
// This code retrieves 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);
Look up phone number formatting
To search for a phone number's operator information, call searchOperatorInformation
from the PhoneNumbersClient
.
let formattingResults = await phoneNumbersClient.searchOperatorInformation([ "<target-phone-number>" ]);
Replace <target-phone-number>
with the phone number you're looking up, usually a number you'd like to send a message to.
Предупреждение
Provide phone numbers in E.164 international standard format, for example, +14255550123.
Look up operator information for a number
To search for a phone number's operator information, call searchOperatorInformation
from the PhoneNumbersClient
, passing true
for the includeAdditionalOperatorDetails
option.
let searchResults = await phoneNumbersClient.searchOperatorInformation([ "<target-phone-number>" ], { "includeAdditionalOperatorDetails": true });
Предупреждение
Using this function incurs a charge to your account.
Use operator information
You can now use the operator information. For this quickstart guide, we can print some of the details to the console.
First, we can print details about the number format.
let formatInfo = formattingResults.values[0];
console.log(formatInfo.phoneNumber + " is formatted " + formatInfo.internationalFormat + " internationally, and " + formatInfo.nationalFormat + " nationally");
Next, we can print details about the phone number and operator.
let operatorInfo = searchResults.values[0];
console.log(operatorInfo.phoneNumber + " is a " + (operatorInfo.numberType ? operatorInfo.numberType : "unknown") + " number, operated in "
+ operatorInfo.isoCountryCode + " by " + (operatorInfo.operatorDetails.name ? operatorInfo.operatorDetails.name : "an unknown operator"));
You can also use the operator information to determine whether to send an SMS. For more information, see Send an SMS message.
Выполнение кода
Run the application from your terminal or command window with the node
command.
node number-lookup-quickstart.js
Пример кода
You can download the sample app from Manage Phone Numbers - JavaScript | GitHub).
Get started with the Phone Numbers client library for C# to look up operator information for phone numbers. Use the operator information to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.
Примечание.
To view the source code for this example, see Manage Phone Numbers - C# | GitHub.
Предпосылки
- Учетная запись Azure с активной подпиской. Создайте учетную запись бесплатно .
- The latest version of .NET Core client library for your operating system.
- An active Communication Services resource and connection string. Создайте ресурс Служб коммуникации.
Проверка предварительных условий
In a terminal or command window, run the dotnet
command to check that the .NET SDK is installed.
Setting up
To set up an environment for sending lookup queries, take the steps in the following sections.
Создание нового приложения C#
In a terminal or command window, run the dotnet new
command to create a new console app with the name NumberLookupQuickstart
. This command creates a simple "Hello World" C# project with a single source file, Program.cs.
dotnet new console -o NumberLookupQuickstart
Измените каталог на только что созданную папку приложения и выполните команду dotnet build
, чтобы скомпилировать приложение.
cd NumberLookupQuickstart
dotnet build
Connect to dev package feed
The public preview version of the SDK is published to a dev package feed. You can add the dev feed using the NuGet CLI, which adds it to the NuGet.Config file.
nuget sources add -Name "Azure SDK for .NET Dev Feed" -Source "https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json"
More detailed information and other options for connecting to the dev feed can be found in the contributing guide.
Установка пакета
While still in the application directory, install the Azure Communication Services PhoneNumbers client library for .NET package by using the following command.
dotnet add package Azure.Communication.PhoneNumbers --version 1.3.0
Add a using
directive to the top of Program.cs to include the Azure.Communication
namespace.
using System;
using System.Threading.Tasks;
using Azure.Communication.PhoneNumbers;
Update Main
function signature to be async.
internal class Program
{
static async Task Main(string[] args)
{
...
}
}
Примеры кода
аутентификация клиента;
Phone Number clients can be authenticated using connection string acquired from an Azure Communication Services resource in the Azure portal. Using a COMMUNICATION_SERVICES_CONNECTION_STRING
environment variable is recommended to avoid putting your connection string in plain text within your code. Узнайте, как управлять строкой подключения вашего ресурса.
// This code retrieves your connection string from an environment variable.
string? connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
PhoneNumbersClient client = new PhoneNumbersClient(connectionString, new PhoneNumbersClientOptions(PhoneNumbersClientOptions.ServiceVersion.V2024_03_01_Preview));
Phone Number clients can also authenticate with Microsoft Entra authentication. With this option, AZURE_CLIENT_SECRET
, AZURE_CLIENT_ID
, and AZURE_TENANT_ID
environment variables need to be set up for authentication.
// Get an endpoint to our Azure Communication Services resource.
Uri endpoint = new Uri("<endpoint_url>");
TokenCredential tokenCredential = new DefaultAzureCredential();
client = new PhoneNumbersClient(endpoint, tokenCredential);
Look up phone number formatting
To look up the national and international formatting for a number, call SearchOperatorInformationAsync
from the PhoneNumbersClient
.
OperatorInformationResult formattingResult = await client.SearchOperatorInformationAsync(new[] { "<target-phone-number>" });
Replace <target-phone-number>
with the phone number you're looking up, usually a number you'd like to send a message to.
Предупреждение
Provide phone numbers in E.164 international standard format, for example, +14255550123.
Look up operator information for a number
To search for a phone number's operator information, call SearchOperatorInformationAsync
from the PhoneNumbersClient
, passing true
for the IncludeAdditionalOperatorDetails
option.
OperatorInformationResult searchResult = await client.SearchOperatorInformationAsync(new[] { "<target-phone-number>" }, new OperatorInformationOptions() { IncludeAdditionalOperatorDetails = true });
Предупреждение
Using this function incurs a charge to your account.
Use operator information
You can now use the operator information. For this quickstart guide, we can print some of the details to the console.
First, we can print details about the number format.
OperatorInformation formattingInfo = formattingResult.Values[0];
Console.WriteLine($"{formattingInfo.PhoneNumber} is formatted {formattingInfo.InternationalFormat} internationally, and {formattingInfo.NationalFormat} nationally");
Next, we can print details about the phone number and operator.
OperatorInformation operatorInformation = searchResult.Values[0];
Console.WriteLine($"{operatorInformation.PhoneNumber} is a {operatorInformation.NumberType ?? "unknown"} number, operated in {operatorInformation.IsoCountryCode} by {operatorInformation.OperatorDetails.Name ?? "an unknown operator"}");
You can also use the operator information to determine whether to send an SMS. For more information about sending an SMS, see Send an SMS message.
Выполнение кода
Run the application from your terminal or command window with the dotnet run
command.
dotnet run --interactive
Пример кода
You can download the sample app from Manage Phone Numbers - C# | GitHub.
Get started with the Phone Numbers client library for Java to look up operator information for phone numbers. Use the operator information to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.
Примечание.
To view the source code for this example, see Manage Phone Numbers - Java | GitHub.
Предпосылки
- Учетная запись Azure с активной подпиской. Создайте учетную запись бесплатно .
- комплект разработки Java (JDK) версии 8 или выше.
- Apache Maven.
- An active Communication Services resource and connection string. Создайте ресурс Служб коммуникации.
Проверка предварительных условий
In a terminal or command window, run the mvn -v
command to check that Maven is installed.
Setting up
To set up an environment for sending lookup queries, take the steps in the following sections.
Создание нового приложения Java
In a terminal or command window, navigate to the directory where you'd like to create your Java application. Выполните следующую команду, чтобы создать проект Java из шаблона maven-archetype-quickstart.
mvn archetype:generate -DgroupId=com.communication.lookup.quickstart -DartifactId=communication-lookup-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
The 'generate' task creates a directory with the same name as the artifactId
. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory
contains the test source, and the pom.xml
file is the project's Project Object Model, or POM.
Connect to dev package feed
The public preview version of the SDK is published to a dev package feed. To connect to the dev feed, open the pom.xml file in your text editor and add the dev repo to both your pom.xml's <repositories>
and <distributionManagement>
sections that you can add if they don't already exist.
<repository>
<id>azure-sdk-for-java</id>
<url>https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
You might need to add or edit the settings.xml
file in ${user.home}/.m2
<server>
<id>azure-sdk-for-java</id>
<username>azure-sdk</username>
<password>[PERSONAL_ACCESS_TOKEN]</password>
</server>
You can generate a Personal Access Token with Packaging read & write scopes and paste it into the <password>
tag.
More detailed information and other options for connecting to the dev feed can be found here.
Установка пакета
Add the following dependency elements to the group of dependencies in the pom.xml file.
<dependencies>
<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.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.41.0</version>
</dependency>
</dependencies>
Check the properties
section to ensure your project is targeting Maven version 1.8 or above.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Примеры кода
Настройка платформы приложения
Из каталога проекта:
- Navigate to the /src/main/java/com/communication/lookup/quickstart directory
- Open the App.java file in your editor
- Replace the
System.out.println("Hello world!");
statement - Add
import
directives
Use the following code to begin:
package com.communication.lookup.quickstart;
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.identity.*;
import java.io.*;
import java.util.ArrayList;
public class App
{
public static void main( String[] args ) throws IOException
{
System.out.println("Azure Communication Services - Number Lookup Quickstart");
// Quickstart code goes here
}
}
аутентификация клиента;
The client can be authenticated using a connection string acquired from an Azure Communication Services resource in the Azure portal. Using a COMMUNICATION_SERVICES_CONNECTION_STRING
environment variable is recommended to avoid putting your connection string in plain text within your code. Узнайте, как управлять строкой подключения вашего ресурса.
// This code retrieves your connection string from an environment variable
String connectionString = System.getenv("COMMUNICATION_SERVICES_CONNECTION_STRING");
PhoneNumbersClient phoneNumberClient = new PhoneNumbersClientBuilder()
.connectionString(connectionString)
.buildClient();
Alternatively, you can authenticate using Microsoft Entra authentication. Using the DefaultAzureCredentialBuilder
is the easiest way to get started with Microsoft Entra ID. You can acquire your resource name from an Azure Communication Services resource in the Azure portal.
// You can find your resource name 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();
Look up phone number formatting
To look up the national and international formatting for a number, call searchOperatorInformation
from the PhoneNumbersClient
.
ArrayList<String> phoneNumbers = new ArrayList<String>();
phoneNumbers.add("<target-phone-number>");
// Use the free number lookup functionality to get number formatting information
OperatorInformationResult formattingResult = phoneNumberClient.searchOperatorInformation(phoneNumbers);
OperatorInformation formattingInfo = formattingResult.getValues().get(0);
Replace <target-phone-number>
with the phone number you're looking up, usually a number you'd like to send a message to.
Предупреждение
Provide phone numbers in E.164 international standard format, for example, +14255550123.
Look up operator information for a number
To search for a phone number's operator information, call searchOperatorInformationWithResponse
from the PhoneNumbersClient
, passing true
for the IncludeAdditionalOperatorDetails
option.
OperatorInformationOptions options = new OperatorInformationOptions();
options.setIncludeAdditionalOperatorDetails(true);
Response<OperatorInformationResult> result = phoneNumberClient.searchOperatorInformationWithResponse(phoneNumbers, options, Context.NONE);
OperatorInformation operatorInfo = result.getValue().getValues().get(0);
Предупреждение
Using this function incurs a charge to your account.
Use operator information
You can now use the operator information. For this quickstart guide, we can print some of the details to the console.
First, we can print details about the number format.
System.out.println(formattingInfo.getPhoneNumber() + " is formatted "
+ formattingInfo.getInternationalFormat() + " internationally, and "
+ formattingInfo.getNationalFormat() + " nationally");
Next, we can print details about the phone number and operator.
String numberType = operatorInfo.getNumberType() == null ? "unknown" : operatorInfo.getNumberType().toString();
String operatorName = "an unknown operator";
if (operatorInfo.getOperatorDetails()!= null && operatorInfo.getOperatorDetails().getName() != null)
{
operatorName = operatorInfo.getOperatorDetails().getName();
}
System.out.println(operatorInfo.getPhoneNumber() + " is a " + numberType + " number, operated in "
+ operatorInfo.getIsoCountryCode() + " by " + operatorName);
You can also use the operator information to determine whether to send an SMS. For more information, see Send an SMS message.
Выполнение кода
Run the application from your terminal or command window with the following commands: Navigate to the directory containing the pom.xml file and compile the project.
mvn compile
Then, build the package.
mvn package
To execute the app, use the mvn
command.
mvn exec:java -D"exec.mainClass"="com.communication.lookup.quickstart.App" -D"exec.cleanupDaemonThreads"="false"
Пример кода
You can download the sample app from Manage Phone Numbers - Java | GitHub.
Get started with the Phone Numbers client library for Python to look up operator information for phone numbers. Use the operator information to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.
Примечание.
To view the source code for this example, see Manage Phone Numbers - Python | GitHub.
Предпосылки
- Учетная запись Azure с активной подпиской. Создайте учетную запись бесплатно .
- Python версии 3.7 и выше.
- An active Communication Services resource and connection string. Создайте ресурс Служб коммуникации.
Проверка предварительных условий
В окне терминала или команды выполните команду python --version
, чтобы проверить, установлен ли пакет Python.
Setting up
To set up an environment for sending lookup queries, take the steps in the following sections.
Создание приложения Python
In a terminal or command window, create a new directory for your app and navigate to it.
mkdir number-lookup-quickstart && cd number-lookup-quickstart
Use a text editor to create a file called number_lookup_sample.py
in the project root directory and add the following code. The remaining quickstart code is added in the following sections.
import os
from azure.communication.phonenumbers import PhoneNumbersClient
try:
print('Azure Communication Services - Number Lookup Quickstart')
# Quickstart code goes here
except Exception as ex:
print('Exception:')
print(ex)
Установка пакета
While still in the application directory, install the Azure Communication Services PhoneNumbers client library for Python package by using the pip install
command.
pip install azure-communication-phonenumbers==1.2.0
Примеры кода
аутентификация клиента;
The client can be authenticated using a connection string acquired from an Azure Communication Services resource in the Azure portal. Using a COMMUNICATION_SERVICES_CONNECTION_STRING
environment variable is recommended to avoid putting your connection string in plain text within your code. Узнайте, как управлять строкой подключения вашего ресурса.
# This code retrieves your connection string from an environment variable
connection_string = os.getenv('COMMUNICATION_SERVICES_CONNECTION_STRING')
try:
phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_string)
except Exception as ex:
print('Exception:')
print(ex)
Alternatively, the client can be authenticated using Microsoft Entra authentication. Using the DefaultAzureCredential
object is the easiest way to get started with Microsoft Entra ID and you can install it using the pip install
command.
pip install azure-identity
Creating a DefaultAzureCredential
object requires you to have AZURE_CLIENT_ID
, AZURE_CLIENT_SECRET
, and AZURE_TENANT_ID
already set as environment variables with their corresponding values from your registered Microsoft Entra application.
For a ramp-up on how to get these environment variables, you can learn how to set up service principals from CLI.
Once the azure-identity
library is installed, you can continue authenticating the client.
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:
credential = DefaultAzureCredential()
phone_numbers_client = PhoneNumbersClient(endpoint, credential)
except Exception as ex:
print('Exception:')
print(ex)
Look up phone number formatting
To look up the national and international formatting for a number, call search_operator_information
from the PhoneNumbersClient
.
formatting_results = phone_numbers_client.search_operator_information("<target-phone-number>")
Replace <target-phone-number>
with the phone number you're looking up, usually a number you'd like to send a message to.
Предупреждение
Provide phone numbers in E.164 international standard format, for example, +14255550123.
Look up operator information for a number
To search for a phone number's operator information, call search_operator_information
from the PhoneNumbersClient
, passing True
for the include_additional_operator_details
option.
options = { "include_additional_operator_details": True }
operator_results = phone_numbers_client.search_operator_information("<target-phone-number>", options=options)
Предупреждение
Using this function incurs a charge to your account.
Use operator information
You can now use the operator information. For this quickstart guide, we can print some of the details to the console.
First, we can print details about the number format.
formatting_info = formatting_results.values[0]
print(str.format("{0} is formatted {1} internationally, and {2} nationally", formatting_info.phone_number, formatting_info.international_format, formatting_info.national_format))
Next, we can print details about the phone number and operator.
operator_information = operator_results.values[0]
number_type = operator_information.number_type if operator_information.number_type else "unknown"
if operator_information.operator_details is None or operator_information.operator_details.name is None:
operator_name = "an unknown operator"
else:
operator_name = operator_information.operator_details.name
print(str.format("{0} is a {1} number, operated in {2} by {3}", operator_information.phone_number, number_type, operator_information.iso_country_code, operator_name))
You can also use the operator information to determine whether to send an SMS. For more information about sending an SMS, see Send an SMS message.
Выполнение кода
Run the application from your terminal or command window with the python
command.
python number_lookup_sample.py
Пример кода
You can download the sample app from Manage Phone Numbers - Python | GitHub.
Устранение неполадок
Common questions and issues:
- Changes to environment variables might not take effect in programs that are already running. If you notice your environment variables aren't working as expected, try closing and reopening any programs you're using to run and edit code.
- The data returned by this endpoint is subject to various international laws and regulations, therefore the accuracy of the results depends on several factors. These factors include whether the number was ported, the country code, and the approval status of the caller. Based on these factors, operator information might not be available for some phone numbers or could reflect the original operator of the phone number, not the current operator.
Дальнейшие действия
В этой статье описано, как:
- Look up number formatting
- Look up operator information for a phone number