다음을 통해 공유


단축 URL 보내기

SMS 메시지는 160자로 제한되어 고객에게 URL을 보내는 기능을 손상시킬 수 있습니다. URL은 쿼리 매개 변수, 암호화된 정보 등을 포함하므로 160자 제한을 초과할 수 있습니다. Azure URL 단축기를 사용하여 SMS를 통해 보내는 데 적합한 짧은 URL이 160자 제한을 훨씬 밑도는 짧은 URL을 생성할 수 있습니다. 

이 문서에서는 Azure Communication Services를 Azure URL Shortener와 통합하는 프로세스를 간략하게 설명합니다. URL Shortener는 단축된 링크를 쉽게 만들고, 관리하고, 모니터링할 수 있는 오픈 소스 서비스입니다.

샘플 코드

이 자습서의 완료된 코드는 C#용 Azure Samples GitHub SMS URL Shortener에서 찾을 수 있습니다.

필수 조건

아키텍처 개요

이 문서에서는 Azure URL Shortener 서비스를 통해 SMS를 보내고 URL을 단축하도록 요청을 오케스트레이션하도록 미들웨어를 설정하는 방법을 설명합니다. 이 미들웨어는 Azure Communication Services와 상호 작용하여 SMS 전송을 완료합니다.

아키텍처 개요를 위한 다이어그램

Azure Function 설정

시작하려면 새 Azure Function을 만들어야 합니다. Azure Functions의 단계에 따라 Azure Functions를 만들 수 있습니다. Azure Function을 사용하는 대신 다른 프레임워크를 사용하는 경우 이 단계를 건너뛰고 다음 섹션으로 진행합니다.

Azure Function이 설정되면 파일로 local.settings.json 이동하여 저장해야 하는 세 가지 값(Azure Communication Services 연결 문자열, 전화 번호(예: +15555555555) 및 URL Shortener 엔드포인트(예: https://<Azure_Function_URL>/api/UrlCreate)를 추가합니다. 이러한 변수는 아티클의 시작 부분에 있는 필수 구성 요소에서 생성한 모든 값입니다.


{
    "IsEncrypted": false,
    "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ACS_CONNECTIONSTRING": "<AZURE COMMUNICATION SERVICES CONNECTION STRING>",
    "ACS_PHONE_NUMBER": "<AZURE COMMUNICATION SERVICES PHONE NUMBER>",
    "URL_SHORTENER": "<URL SHORTENER ENDPOINT>" 
    }
}

쿼리 매개 변수 구성

Azure Function을 만든 후에는 트리거하는 데 필요한 쿼리 매개 변수를 구성해야 합니다. 함수에는 전화 번호 및 URL이 필요합니다. 전화 번호는 SMS 메시지의 수신자입니다. URL은 단축되어 수신자에게 전송되는 링크입니다.


namespace Company.Function
{
    public static class SendSMSUrlShortener
    {
        [FunctionName("SendSMSUrlShortener")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
            string urlToShorten = req.Query["url"]; // get url to shorten query parameter

            return new OkObjectResult(null);
        }
    }
}

URL 단축

이제 전화 번호 및 URL이 있으므로 Azure URL Shortener 서비스를 사용하여 URL을 단축할 수 있습니다. Azure URL Shortener 서비스를 배포했는지 확인합니다. 이 서비스에는 여러 엔드포인트가 포함되어 있지만 이 자습서에서는 UrlCreate 엔드포인트가 초점입니다. PostAsync 메서드를 사용하여 단축하려는 URL을 사용하여 Azure URL Shortener 서비스에 POST 요청을 보냅니다.

서비스는 단축된 URL이 포함된 JSON 개체를 반환합니다. 단축된 URL을 shortUrl 변수에 저장합니다. 코드 조각에서 배포된 Azure URL Shortener 서비스의 엔드포인트를 삽입합니다. 엔드포인트를 가져오는 방법에 대한 자세한 내용은 배포 유효성 검사를 참조하세요.

...
using System.Net.Http;
using System.Text.Json;
using System.Text;

namespace Company.Function
{
    public class ShortenedUrl
    {
        public string ShortUrl { get; set; }
    }

    public static class SendSMSUrlShortener
    {
        static string urlShortener = Environment.GetEnvironmentVariable("URL_SHORTENER", EnvironmentVariableTarget.Process);

        [FunctionName("SendSMSUrlShortener")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //Parse Query Parameters
            string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
            string urlToShorten = req.Query["url"]; // get url to shorten query parameter
            
            //Get short URL from Azure URL Shortener
            using var client = new HttpClient();
            var requestData = new
            {
                Url = urlToShorten //Body request for the POST call
            };
            var requestBody = JsonSerializer.Serialize(requestData);
            var httpContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(urlShortener, httpContent); // POST call to the Azure URL Shortener
            var content = await response.Content.ReadAsStringAsync();
            var data = System.Text.Json.JsonSerializer.Deserialize<ShortenedUrl>(content); // Parse content to ShortenedUrl object
            var url = data.ShortUrl;
            log.LogInformation("Shortened URL " + url);

            return new OkObjectResult(null);
        }
    }
}

SMS 보내기

URL이 단축되었으므로 이제 Azure Communication Services를 사용하여 SMS를 보낼 수 있습니다. send 패키지의 SmsClient 클래스에서 Azure.Communication.Sms 메서드를 사용합니다.


dotnet add package Azure.Communication.Sms

이 메서드는 쿼리 매개 변수에 제공된 전화 번호로 SMS를 보냅니다. SMS에는 단축된 URL이 포함됩니다. SMS를 보내는 방법에 대한 자세한 내용은 SMS 보내기를 참조하세요.

...
using Azure;
using Azure.Communication;
using Azure.Communication.Sms;

namespace Company.Function
{
    // Class to deserialize URL Shortener response
    public class ShortenedUrl
    {
        public string ShortUrl { get; set; }
    }

    public static class SendSMSUrlShortener
    {
        [FunctionName("SendSMSUrlShortener")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            
            //Parse Query Parameters
            string phoneNumberTo = req.Query["phoneNumber"]; // get phone number query parameter
            string urlToShorten = req.Query["url"]; // get url to shorten query parameter
            
            //Get short URL from Azure URL Shortener
            using var client = new HttpClient();
            var requestData = new
            {
                Url = urlToShorten //Body request for the POST call
            };
            var requestBody = JsonSerializer.Serialize(requestData);
            var httpContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
            string urlShortener = Environment.GetEnvironmentVariable("URL_SHORTENER", EnvironmentVariableTarget.Process); // Ex. https://<Azure Function URL>/api/UrlCreate
            var response = await client.PostAsync(urlShortener, httpContent); // POST call to the Azure URL Shortener
            var content = await response.Content.ReadAsStringAsync();
            var data = System.Text.Json.JsonSerializer.Deserialize<ShortenedUrl>(content); // Parse content to ShortenedUrl object
            var url = data.ShortUrl;
            log.LogInformation("Shortened URL " + url);
            
            //Send SMS with Azure Communication Services
            string connectionString = Environment.GetEnvironmentVariable("ACS_CONNECTIONSTRING", EnvironmentVariableTarget.Process);
            string phoneNumberFrom = Environment.GetEnvironmentVariable("ACS_PHONE_NUMBER", EnvironmentVariableTarget.Process); // Ex. +15555555555
            SmsClient smsClient = new SmsClient(connectionString);            
            SmsSendResult sendResult = smsClient.Send(
                from: phoneNumberFrom,
                to: phoneNumberTo,
                message: "Here is your shortened URL: " + url
            ); // Send SMS message with shortened URL
            
            return new OkObjectResult(sendResult);
        }
    }
}

로컬에서 테스트

참고

URL을 사용하여 SMS 메시지를 보낼 전화 번호를 확인해야 합니다. 확인 애플리케이션이 보류 중 상태(1~2일)로 설정되면 URL을 보낼 수 있도록 설정할 전화 번호입니다. 전체 확인에는 5~6주가 걸립니다. 무료 번호 확인에 대한 자세한 내용은 무료 확인 FAQ를 참조 하세요.

Visual Studio Code를 눌러 F5 Azure Function을 로컬로 실행하거나 터미널에서 다음 명령을 실행합니다.

func host start

그런 다음 Postman 과 같은 도구를 사용하여 Azure Function의 엔드포인트에 POST 요청을 하여 함수를 테스트합니다. 전화 번호 및 URL을 쿼리 매개 변수로 제공해야 합니다. 예를 들어 Azure Function이 로컬로 실행되는 경우 http://localhost:7071/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com에 요청할 수 있습니다. 단축된 URL과 Success의 상태가 포함된 응답을 받아야 합니다.

Azure에 배포

Azure Function을 배포하려면 단계별 지침을 따릅니다.

배포 후에는 로컬에서 테스트할 때와 비슷한 방법을 통해 함수에 액세스할 수 있습니다. 전화 번호 및 URL을 쿼리 매개 변수로 제공해야 합니다. 예를 들어 Azure Function이 Azure에 배포된 경우 https://<YOUR AZURE FUNCTION NAME>.azurewebsites.net/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com에 요청할 수 있습니다. 단축된 URL과 Success의 상태가 포함된 응답을 받아야 합니다.

샘플 코드

이 자습서의 완료된 코드는 JavaScript용 Azure Samples GitHub SMS URL Shortener에서 찾을 수 있습니다.

필수 조건

아키텍처 개요

이 문서에서는 AZURE URL Shortener 서비스를 통해 SMS 및 URL 단축을 보내기 위한 요청을 오케스트레이션하는 미들웨어를 설정하는 방법을 설명합니다. 이 미들웨어는 Azure Communication Services와 상호 작용하여 SMS 전송을 완료합니다.

아키텍처 개요를 위한 다이어그램

Azure Function 설정

시작하려면 새 Azure Function을 만들어야 합니다. Azure Functions 설명서의 단계에 따라 Azure Function을 만들 수 있습니다. Azure Function을 사용하는 대신 다른 프레임워크를 사용하는 경우 이 단계를 건너뛰고 다음 섹션으로 진행합니다.

Azure Function이 설정되면 파일로 local.settings.json 이동하여 저장해야 하는 세 가지 값(예: Azure Communication Services 연결 문자열, 전화 번호(예: +15555555555) 및 URL Shortener 엔드포인트(예: https://<Azure_Function_URL>/api/UrlCreate)를 추가합니다. 이러한 변수는 이 문서의 시작 부분에 있는 필수 구성 요소에서 생성한 모든 값입니다.


{
    "IsEncrypted": false,
    "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "ACS_CONNECTIONSTRING": "<AZURE COMMUNICATION SERVICES CONNECTION STRING>",
    "ACS_PHONE_NUMBER": "<AZURE COMMUNICATION SERVICES PHONE NUMBER>",
    "URL_SHORTENER": "<URL SHORTENER ENDPOINT>" 
    }
}

쿼리 매개 변수 구성

Azure Function을 만든 후에는 트리거하는 데 필요한 쿼리 매개 변수를 구성해야 합니다. 함수에는 전화 번호 및 URL이 필요합니다. 전화 번호는 SMS 메시지의 수신자로 사용됩니다. URL은 단축되어 수신자에게 전송되는 링크입니다.


const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    //Parse Query Parameters
    let phoneNumber = req.query.phoneNumber; // get phone number query parameter
    let url =  req.query.url; // get url to shorten query parameter

    context.res = {
      // status: 200, /* Defaults to 200 */
      body: null
    };
};

export default httpTrigger;

URL 단축

이제 전화 번호 및 URL이 있으므로 Azure URL Shortener 서비스를 사용하여 URL을 단축할 수 있습니다. Azure URL Shortener 서비스를 이미 배포했는지 확인합니다. 이 서비스에는 여러 엔드포인트가 포함되어 있지만 이 자습서에서는 UrlCreate 엔드포인트가 초점입니다. fetch 메서드를 사용하여 단축하려는 URL을 사용하여 Azure URL Shortener 서비스에 POST 요청을 보냅니다.

서비스는 단축된 URL이 포함된 JSON 개체를 반환합니다. 단축된 URL을 shortUrl 변수에 저장합니다. 코드 조각에서 배포된 Azure URL Shortener 서비스의 엔드포인트를 삽입합니다. 엔드포인트를 가져오는 방법에 대한 자세한 내용은 배포 유효성 검사를 참조하세요.


const urlShortener = process.env.URL_SHORTENER

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    //Parse Query Parameters    
    let phoneNumberTo = req.query.phoneNumber; // get phone number query parameter
    let urlToShorten =  req.query.url; // get url to shorten query parameter
    
    //Get short URL from Azure URL Shortener
    const body =  JSON.stringify({ "Url": url})
    await fetch(urlShortener, {
      method: 'POST',
      body: body
    })
    .then(res => res.json())
    .then(async data => {
      const shortUrl = data["ShortUrl"]
      context.log(shortUrl)
      }
    })

    context.res = {
      // status: 200, /* Defaults to 200 */
      body: null
    };
};

export default httpTrigger;

SMS 보내기

이제 단축된 URL이 있으므로 Azure Communication Services를 사용하여 SMS를 보냅니다. send 패키지의 SmsClient 클래스에서 @azure/communication-sms 메서드를 시작합니다.


npm i @azure/communication-sms --save

이 메서드는 쿼리 매개 변수에 제공된 전화 번호로 SMS를 보냅니다. SMS에는 단축된 URL이 포함됩니다. SMS를 보내는 방법에 대한 자세한 내용은 SMS 보내기를 참조하세요.


import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { SmsClient }  from "@azure/communication-sms"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    //Parse Query Parameters
    let to = req.query.phoneNumber; // Get phone number to send SMS to
    let urlToShorten =  req.query.url; // Get URL to shorten

    //Get short URL from Azure URL Shortener
    const body =  JSON.stringify({ "Url": urlToShorten})
    const urlShortener = process.env.URL_SHORTENER
    await fetch(urlShortener, {
      method: 'POST',
      body: body
    })
    .then(res => res.json())
    .then(async data => {
      const url = data["ShortUrl"]
      const connectionString =  process.env.ACS_CONNECTIONSTRING
      const phoneNumberFrom = process.env.ACS_PHONE_NUMBER
      const smsClient = new SmsClient(connectionString);
      // Send the SMS message
      const sendResults = await smsClient.send({
        from: phoneNumberFrom,
        to: [to],
        message: "Join your scheduled appointment here: " + url
      }, {
        enableDeliveryReport: true
      });
      // Use the "successful" property to verify the status.
      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);
        }
      }
      context.res = {
        // status: 200, /* Defaults to 200 */
        body: url
      };
    })

};

로컬에서 테스트

참고

URL을 사용하여 SMS 메시지를 보낼 전화 번호를 확인해야 합니다. 확인 애플리케이션이 보류 중인 상태(1~2일)로 설정되면 URL을 보낼 수 있도록 설정할 전화 번호입니다. 전체 확인에는 5~6주가 걸립니다. 무료 번호 확인에 대한 자세한 내용은 무료 무료 확인 FAQ를 참조하세요.

Azure Function을 로컬에서 실행하려면 Visual Studio Code에서 F5를 누르거나 터미널에서 다음 명령어를 실행합니다.

func host start

그런 다음 Postman과 같은 도구를 사용하여 Azure Function의 엔드포인트에 요청하여 POST 함수를 테스트합니다. 전화 번호 및 URL을 쿼리 매개 변수로 제공해야 합니다. 예를 들어 Azure Function이 로컬로 실행되는 경우 http://localhost:7071/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com에 요청할 수 있습니다. 단축된 URL과 Success의 상태가 포함된 응답을 받아야 합니다.

Azure에 배포

Azure Function을 배포하려면 단계별 지침을 참조하세요.

배포 후에는 로컬에서 테스트할 때와 비슷한 방법을 통해 함수에 액세스할 수 있습니다. 전화 번호 및 URL을 쿼리 매개 변수로 제공해야 합니다. 예를 들어 Azure Function이 Azure에 배포된 경우 https://<YOUR AZURE FUNCTION NAME>.azurewebsites.net/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com에 요청할 수 있습니다. 단축된 URL과 Success의 상태가 포함된 응답을 받아야 합니다.

다음 단계