你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 Azure 通信服务通过短信发送缩短器链接

短信限制为 160 个字符,这限制了向客户发送 URL 的能力。 URL 可能超过 160 个字符的限制,因为它们包含查询参数、加密信息等。通过使用 Azure URL 缩短器,可以生成适合通过短信发送的短 URL,因为它们远远低于 160 个字符的限制。 

本文档概述了将 Azure 通信服务 与 Azure URL 缩短器(一种开放源代码服务)集成的过程,使你能够轻松创建、管理和监视缩短的链接。

代码示例

可以在 GitHub 上找到本教程的已完成代码。

先决条件

体系结构概述

在本教程中,重点是设置一个中间件,用于协调通过 Azure URL 缩短器服务发送短信的请求和 URL 的缩短。 它与 Azure 通信服务交互以完成短信的发送。

体系结构概述示意图。

设置 Azure Functions

若要开始,需要创建新的 Azure 函数。 可以按照 Azure Functions 文档中的步骤创建 Azure 函数。 如果不使用 Azure 函数,而是使用其他框架,请跳过此步骤,继续学习下一部分。

设置 Azure 函数后,转到 local.settings.json 文件并添加需要存储的另外三个值:Azure 通信服务连接字符串、电话号码 (Ex. +15555555555) 和 URL 缩短器终结点 (Ex. 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 函数后,需要配置触发它所需的查询参数。 函数需要电话号码和 URL。 电话号码用作短信的收件人。 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 缩短器服务来缩短 URL。 确保已部署此服务。 服务包含多个终结点,但本教程中的重点是 UrlCreate 终结点。 使用 PostAsync 方法向 Azure URL 缩短器服务发出 POST 请求,其中包含要缩短的 URL。 服务返回包含已缩短的 URL 的 JSON 对象。 将已缩短的 URL 存储在名为 shortUrl 的变量中。 在代码片段中,插入已部署的 Azure URL 缩短器服务的终结点。 有关如何获取终结点的信息,请参阅验证部署

...
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);
        }
    }
}

发送短信

现在 URL 已缩短,可以使用 Azure 通信服务发送短信。 使用 Azure.Communication.Sms 包中 SmsClient 类的 send 方法。


dotnet add package Azure.Communication.Sms

此方法将短信发送到查询参数中提供的电话号码。 短信包含缩短的 URL。 有关如何发送短信的详细信息,请参阅发送短信

...
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 的短信消息。 将验证应用程序设置为挂起状态(1-2 天)后,将启用用于发送 URL 的电话号码。 完整验证需要 5-6 周。 有关免费号码验证的详细信息,请参阅免费验证常见问题解答

现在,可以通过按 Visual Studio Code 中的 F5 或在终端中运行以下命令在本地运行 Azure 函数:


func host start

然后,使用 Postman 等工具,可以通过向 Azure 函数的终结点发出 POST 请求来测试函数。 需要提供电话号码和 URL 作为查询参数。 例如,如果 Azure 函数在本地运行,则可以向 http://localhost:7071/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com 发出请求。 应会收到一个响应,其表明 URL 已缩短,状态为 Success

部署到 Azure

若要部署 Azure 函数,可以按照分布说明进行操作。

部署后,可以通过与在本地测试时类似的方法访问函数。 需要提供电话号码和 URL 作为查询参数。 例如,如果 Azure 函数部署到 Azure,则可以向 https://<YOUR AZURE FUNCTION NAME>.azurewebsites.net/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com 发出请求。 应会收到一个响应,其表明 URL 已缩短,状态为 Success

代码示例

可以在 GitHub 上找到本教程的已完成代码。

先决条件

体系结构概述

在本教程中,重点是设置一个中间件,用于协调通过 Azure URL 缩短器服务发送短信的请求和 URL 的缩短。 它与 Azure 通信服务交互以完成短信的发送。

体系结构概述示意图。

设置 Azure Functions

若要开始,需要创建新的 Azure 函数。 可以按照 Azure Functions 文档中的步骤创建 Azure 函数。 如果不使用 Azure 函数,而是使用其他框架,请跳过此步骤,继续学习下一部分。

设置 Azure 函数后,转到 local.settings.json 文件并添加需要存储的另外三个值:Azure 通信服务连接字符串、电话号码 (Ex. +15555555555) 和 URL 缩短器终结点 (Ex. 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 函数后,需要配置触发它所需的查询参数。 函数需要电话号码和 URL。 电话号码用作短信的收件人。 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 缩短器服务来缩短 URL。 确保已部署此服务。 服务包含多个终结点,但本教程中的重点是 UrlCreate 终结点。 使用 fetch 方法向 Azure URL 缩短器服务发出 POST 请求,其中包含要缩短的 URL。 服务返回包含已缩短的 URL 的 JSON 对象。 将已缩短的 URL 存储在名为 shortUrl 的变量中。 在代码片段中,插入已部署的 Azure URL 缩短器服务的终结点。 有关如何获取终结点的信息,请参阅验证部署


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;

发送短信

有了短 URL 后,可使用 Azure 通信服务发送短信。 开始使用 @azure/communication-sms 包中 SmsClient 类的 send 方法。


npm i @azure/communication-sms --save

此方法将短信发送到查询参数中提供的电话号码。 短信包含短 URL。 有关如何发送短信的详细信息,请参阅发送短信


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 的短信消息。 将验证应用程序设置为挂起状态(1-2 天)后,将启用用于发送 URL 的电话号码。 完整验证需要 5-6 周。 有关免费号码验证的详细信息,请参阅免费验证常见问题解答

现在,可以通过按 Visual Studio Code 中的 F5 或在终端中运行以下命令在本地运行 Azure 函数:


func host start

然后,使用 Postman 等工具,可以通过向 Azure 函数的终结点发出 POST 请求来测试函数。 需要提供电话号码和 URL 作为查询参数。 例如,如果 Azure 函数在本地运行,则可以向 http://localhost:7071/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com 发出请求。 应会收到一个响应,其表明 URL 已缩短,状态为 Success

部署到 Azure

若要部署 Azure 函数,可以按照分布说明进行操作。

部署后,可以通过与在本地测试时类似的方法访问函数。 需要提供电话号码和 URL 作为查询参数。 例如,如果 Azure 函数部署到 Azure,则可以向 https://<YOUR AZURE FUNCTION NAME>.azurewebsites.net/api/<FUNCTION NAME>?phoneNumber=%2B15555555555&url=https://www.microsoft.com 发出请求。 应会收到一个响应,其表明 URL 已缩短,状态为 Success

后续步骤