您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

Azure Functions 的 Twilio 绑定Twilio binding for Azure Functions

本文介绍如何使用 Azure Functions 中的 Twilio 绑定发送短信。This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions 支持 Twilio 的输出绑定。Azure Functions supports output bindings for Twilio.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.Twilio NuGet 包 1.x 版中提供了 Twilio 绑定。The Twilio bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Twilio NuGet package, version 1.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 1.xFunctions 1.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#Local development - C# script, JavaScript, F# 自动Automatic
门户开发Portal development 自动Automatic

包 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.Twilio NuGet 包 3.x 版中提供了 Twilio 绑定。The Twilio bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Twilio NuGet package, version 3.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

示例 - Functions 1.xExample - Functions 1.x

参阅语言特定的示例:See the language-specific example:

C# 示例C# example

以下示例演示在队列消息触发时发送短信的 C# 函数The following example shows a C# function that sends a text message when triggered by a queue message.

[FunctionName("QueueTwilio")]
[return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX" )]
public static SMSMessage Run(
    [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order,
    TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {order}");

    var message = new SMSMessage()
    {
        Body = $"Hello {order["name"]}, thanks for your order!",
        To = order["mobileNumber"].ToString()
    };

    return message;
}

此示例使用包含方法返回值的 TwilioSms 特性。This example uses the TwilioSms attribute with the method return value. 一种替代方法是使用包含 out SMSMessage 参数或者 ICollector<SMSMessage>IAsyncCollector<SMSMessage> 参数的特性。An alternative is to use the attribute with an out SMSMessage parameter or an ICollector<SMSMessage> or IAsyncCollector<SMSMessage> parameter.

C# 脚本示例C# script example

以下示例演示 function.json 文件中的一个 Twilio 输出绑定以及使用该绑定的 C# 脚本函数The following example shows a Twilio output binding in a function.json file and a C# script function that uses the binding. 该函数使用 out 参数发送短信。The function uses an out parameter to send a text message.

下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:

示例 function.json:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSid": "TwilioAccountSid",
  "authToken": "TwilioAuthToken",
  "to": "+1704XXXXXXX",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

C# 脚本代码如下所示:Here's C# script code:

#r "Newtonsoft.Json"
#r "Twilio.Api"

using System;
using Newtonsoft.Json;
using Twilio;

public static void Run(string myQueueItem, out SMSMessage message,  TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a 
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // Even if you want to use a hard coded message and number in the binding, you must at least 
    // initialize the SMSMessage variable.
    message = new SMSMessage();

    // A dynamic message can be set instead of the body in the output binding. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    message.Body = msg;
    message.To = order.mobileNumber;
}

不能在同步代码中使用 out 参数。You can't use out parameters in synchronous code. 下面是异步 C# 脚本代码的示例:Here's an asynchronous C# script code example:

#r "Newtonsoft.Json"
#r "Twilio.Api"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Twilio;

public static async Task Run(string myQueueItem, IAsyncCollector<SMSMessage> message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a 
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // Even if you want to use a hard coded message and number in the binding, you must at least 
    // initialize the SMSMessage variable.
    SMSMessage smsText = new SMSMessage();

    // A dynamic message can be set instead of the body in the output binding. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    smsText.Body = msg;
    smsText.To = order.mobileNumber;

    await message.AddAsync(smsText);
}

JavaScript 示例JavaScript example

以下示例演示 function.json 文件中的一个 Twilio 输出绑定以及使用该绑定的 JavaScript 函数The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:

示例 function.json:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSid": "TwilioAccountSid",
  "authToken": "TwilioAuthToken",
  "to": "+1704XXXXXXX",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);

    // In this example the queue item is a JSON string representing an order that contains the name of a 
    // customer and a mobile number to send text updates to.
    var msg = "Hello " + myQueueItem.name + ", thank you for your order.";

    // Even if you want to use a hard coded message and number in the binding, you must at least 
    // initialize the message binding.
    context.bindings.message = {};

    // A dynamic message can be set instead of the body in the output binding. In this example, we use 
    // the order information to personalize a text message to the mobile number provided for
    // order status updates.
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };

    context.done();
};

示例 - Functions 2.xExample - Functions 2.x

参阅语言特定的示例:See the language-specific example:

2.x C# 示例2.x C# example

以下示例演示在队列消息触发时发送短信的 C# 函数The following example shows a C# function that sends a text message when triggered by a queue message.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioQueueOutput
{
    public static class QueueTwilio
    {
        [FunctionName("QueueTwilio")]
        [return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]
        public static CreateMessageOptions Run(
        [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order,
        ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {order}");

            var message = new CreateMessageOptions(new PhoneNumber(order["mobileNumber"].ToString()))
            {
                Body = $"Hello {order["name"]}, thanks for your order!"
            };

            return message;
        }
    }
}

此示例使用包含方法返回值的 TwilioSms 特性。This example uses the TwilioSms attribute with the method return value. 一种替代方法是使用包含 out CreateMessageOptions 参数或者 ICollector<CreateMessageOptions>IAsyncCollector<CreateMessageOptions> 参数的特性。An alternative is to use the attribute with an out CreateMessageOptions parameter or an ICollector<CreateMessageOptions> or IAsyncCollector<CreateMessageOptions> parameter.

2.x C# 脚本示例2.x C# script example

以下示例演示 function.json 文件中的一个 Twilio 输出绑定以及使用该绑定的 C# 脚本函数The following example shows a Twilio output binding in a function.json file and a C# script function that uses the binding. 该函数使用 out 参数发送短信。The function uses an out parameter to send a text message.

下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:

示例 function.json:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

C# 脚本代码如下所示:Here's C# script code:

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static void Run(string myQueueItem, out CreateMessageOptions message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    message = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    message.Body = msg;
}

不能在同步代码中使用 out 参数。You can't use out parameters in synchronous code. 下面是异步 C# 脚本代码的示例:Here's an asynchronous C# script code example:

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static async Task Run(string myQueueItem, IAsyncCollector<CreateMessageOptions> message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    CreateMessageOptions smsText = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    smsText.Body = msg;

    await message.AddAsync(smsText);
}

2.x JavaScript 示例2.x JavaScript example

以下示例演示 function.json 文件中的一个 Twilio 输出绑定以及使用该绑定的 JavaScript 函数The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:

示例 function.json:Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    var msg = "Hello " + myQueueItem.name + ", thank you for your order.";

    // Even if you want to use a hard coded message in the binding, you must at least
    // initialize the message binding.
    context.bindings.message = {};

    // A dynamic message can be set instead of the body in the output binding. The "To" number 
    // must be specified in code. 
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };

    context.done();
};

属性Attributes

C# 类库中,使用 TwilioSms 特性。In C# class libraries, use the TwilioSms attribute.

有关可以配置的特性属性的信息,请参阅配置For information about attribute properties that you can configure, see Configuration. 下面是某个方法签名中的 TwilioSms 特性示例:Here's a TwilioSms attribute example in a method signature:

[FunctionName("QueueTwilio")]
[return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]
public static CreateMessageOptions Run(
[QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order, ILogger log)
{
    ...
}

有关完整示例,请参阅 C# 示例For a complete example, see C# example.

配置Configuration

下表解释了在 function.json 文件和 TwilioSms 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the TwilioSms attribute.

v1 function.json 属性v1 function.json property v2 function.json 属性v2 function.json property Attribute 属性Attribute property 说明Description
typetype typetype 必须设置为 twilioSmsmust be set to twilioSms.
directiondirection directiondirection 必须设置为 outmust be set to out.
namename namename 在 Twilio 短信的函数代码中使用的变量名。Variable name used in function code for the Twilio SMS text message.
accountSidaccountSid AccountSidSettingaccountSidSetting AccountSidSettingAccountSidSetting 此值必须设置为保留 Twilio 帐户 Sid 的应用设置的名称,例如 TwilioAccountSid。This value must be set to the name of an app setting that holds your Twilio Account Sid e.g. TwilioAccountSid. 如果未设置,默认应用设置名称为“AzureWebJobsTwilioAccountSid”。If not set, the default app setting name is "AzureWebJobsTwilioAccountSid".
authTokenauthToken AuthTokenSettingauthTokenSetting AuthTokenSettingAuthTokenSetting 此值必须设置为保留 Twilio 身份验证令牌的应用设置的名称,例如 TwilioAccountAuthToken。This value must be set to the name of an app setting that holds your Twilio authentication token e.g. TwilioAccountAuthToken. 如果未设置,默认应用设置名称为“AzureWebJobsTwilioAuthToken”。If not set, the default app setting name is "AzureWebJobsTwilioAuthToken".
toto 不适用 - 在代码中指定N/A - specify in code 收件人To 此值设置为短信将发送到的电话号码。This value is set to the phone number that the SMS text is sent to.
fromfrom fromfrom FromFrom 此值设置为发送短信的电话号码。This value is set to the phone number that the SMS text is sent from.
bodybody bodybody 正文Body 如果不需要在函数的代码中动态设置短信,则可以使用此值对其进行硬编码。This value can be used to hard code the SMS text message if you don't need to set it dynamically in the code for your function.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

后续步骤Next steps