JavaScript용 Azure Communication SMS 클라이언트 라이브러리 - 버전 1.1.0

Azure Communication SMS 서비스는 개발자에게 Communication Services를 통해 구입할 수 있는 전화 번호에서 SMS 메시지를 보낼 수 있는 기능을 제공합니다.

시작

필수 구성 요소

  • Azure 구독.
  • 기존 Communication Services 리소스입니다. 리소스를 만들어야 하는 경우 Azure Portal, Azure PowerShell 또는 Azure CLI를 사용할 수 있습니다.
  • Communication Services 리소스에 할당된 전화 번호입니다. Communication Services 리소스 에 전화 번호를 추가하는 방법에 대한 지침은 전화 번호를 얻는 방법을 참조하세요.

설치

npm install @azure/communication-sms

전화 번호를 얻는 방법

전화 번호를 획득하고 Azure Portal에서 Communication Services 리소스에 할당할 수 있습니다. Azure Portal을 사용하여 전화 번호를 가져오는 방법에 대한 지침은 여기에서 찾을 수 있습니다.

패키지를 사용하여 @azure/communication-phone-numbers 전화 번호를 받을 수도 있습니다. 패키지를 사용하는 방법에 대한 지침은 패키지의 추가 정보에서 찾을 수 있습니다.

브라우저 지원

JavaScript 번들

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

주요 개념

SmsClient

SmsClient 는 이 클라이언트 라이브러리를 사용하는 개발자를 위한 기본 인터페이스입니다. SMS 메시지를 보내는 비동기 메서드를 제공합니다.

예제

인증

Azure Portal의 Communication Services 리소스에서 키 및/또는 연결 문자열 가져올 수 있습니다. 키가 있으면 다음 방법 중 원하는 방법으로 인증할 수 있습니다.

연결 문자열 사용

import { SmsClient } from "@azure/communication-sms";

const connectionString = `endpoint=https://<resource-name>.communication.azure.com/;accessKey=<Base64-Encoded-Key>`;
const client = new SmsClient(connectionString);

을 사용하여 자격 증명 만들기 AzureKeyCredential

import { AzureKeyCredential } from "@azure/core-auth";
import { SmsClient } from "@azure/communication-sms";

const endpoint = "https://<resource-name>.communication.azure.com";
const credential = new AzureKeyCredential("<Base64-Encoded-Key>");
const client = new SmsClient(endpoint, credential);

Azure Active Directory 관리 ID 사용

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

npm install @azure/identity

패키지는 @azure/identity 애플리케이션에서 이 작업을 수행하는 데 사용할 수 있는 다양한 자격 증명 형식을 제공합니다. @azure/identity README 파일은 시작 방법에 대한 자세한 내용과 샘플을 제공합니다. AZURE_CLIENT_SECRET, AZURE_CLIENT_ID 및 AZURE_TENANT_ID 환경 변수는 DefaultAzureCredential 개체를 만드는 데 필요합니다.

import { DefaultAzureCredential } from "@azure/identity";
import { SmsClient } from "@azure/communication-sms";

const endpoint = "https://<resource-name>.communication.azure.com";
let credential = new DefaultAzureCredential();
const client = new SmsClient(endpoint, credential);

1:N SMS 메시지 보내기

SMS 메시지를 보내려면 에서 함수를 send 호출합니다 SmsClient. 개체를 전달 SmsSendRequest 해야 합니다. 옵션 개체에 패스를 추가하여 배달 보고서를 사용할지 여부를 지정하고 보고서에 대한 사용자 지정 태그를 설정할 수도 있습니다. 배열 SmsSendResult 이 반환됩니다. successful 플래그는 각 개별 메시지가 성공적으로 전송되었는지 확인하는 데 사용됩니다.

const sendResults = await client.send(
  {
    from: "<from-phone-number>", // Your E.164 formatted phone number used to send SMS
    to: ["<to-phone-number-1>", "<to-phone-number-2>"], // The list of E.164 formatted phone numbers to which message is being sent
    message: "Weekly Promotion!" // The message being sent
  },
  {
    enableDeliveryReport: true,
    tag: "marketing"
  }
);

for (const sendResult of sendResults) {
  if (sendResult.successful) {
    console.log("Success: ", sendResult);
  } else {
    console.error("Something went wrong when trying to send this message: ", sendResult);
  }
}

문제 해결

서버에 대한 요청이 실패하면 SMS 작업이 예외를 throw합니다. 오류가 개별 메시지로 인해 발생하는 경우 전체 요청으로 인해 오류가 발생하는 경우에만 예외가 throw되지 않습니다. 플래그를 successful 사용하여 각 개별 결과의 유효성을 검사하여 메시지가 전송되었는지 확인하세요.

try {
  const sendResults = await client.send({
    from: "<from-phone-number>", // Your E.164 formatted phone number used to send SMS
    to: ["<to-phone-number-1>", "<to-phone-number-2>"], // The list of E.164 formatted phone numbers to which message is being sent
    message: "Hello World via SMS!" // The message being sent
  });
  for (const sendResult of sendResults) {
    if (sendResult.successful) {
      console.log("Success: ", sendResult);
    } else {
      console.error("Something went wrong when trying to send this message: ", sendResult);
    }
  }
} catch (e) {
  console.error(e.message);
}

다음 단계

참여

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

Impressions