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

Azure Functions 的 Twilio 绑定

This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions 支持 Twilio 的输出绑定。

此参考信息面向 Azure Functions 开发人员。 Azure Functions 的新手请从以下资源入手:

Install extension

你安装的扩展 NuGet 包取决于你在函数应用中使用的 C# 模式:

函数在独立的 C# 工作进程中执行。 若要了解详细信息,请参阅有关在独立工作进程中运行 C# Azure Functions 的指南

扩展的功能因扩展版本而异:

当前不支持 Twilio 用于独立工作进程应用。

Install bundle

Starting with Functions version 2.x, the HTTP extension is part of an extension bundle, which is specified in your host.json project file. To learn more, see extension bundle.

This version of the extension should already be available to your function app with extension bundle, version 2.x.

Example

除非另有说明,否则这些示例特定于版本 2.x 和更高版本的 Functions 运行时。

可以使用以下 C# 模式之一创建 C# 函数:

  • 独立辅助角色模型:编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要隔离的工作进程来支持长期支持 (LTS) 和非 LTS 版本的 .NET 和 .NET Framework 上运行的 C# 函数。
  • In-process model: Compiled C# function that runs in the same process as the Azure Functions runtime.
  • C# script: Used primarily when you create C# functions in the Azure portal.

在独立工作进程中运行的函数应用当前不支持 Twilio 绑定。

The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

Here's binding data in the function.json file:

Example function.json:

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

JavaScript 代码如下所示:

module.exports = async 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
    };
};

完整的 PowerShell 示例当前不可用于 SendGrid 绑定。

The following example shows how to send an SMS message using the output binding as defined in the following function.json.

    {
      "type": "twilioSms",
      "name": "twilioMessage",
      "accountSidSetting": "TwilioAccountSID",
      "authTokenSetting": "TwilioAuthToken",
      "from": "+1XXXXXXXXXX",
      "direction": "out",
      "body": "Azure Functions Testing"
    }

可以将序列化的 JSON 对象传递到 func.Out 参数以发送短信。

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, twilioMessage: func.Out[str]) -> func.HttpResponse:

    message = req.params.get('message')
    to = req.params.get('to')

    value = {
      "body": message,
      "to": to
    }

    twilioMessage.set(json.dumps(value))

    return func.HttpResponse(f"Message sent")

The following example shows how to use the TwilioSmsOutput annotation to send an SMS message. tofrombody 的值在属性定义中是必需的,即使以编程方式重写它们也是如此。

package com.function;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

public class TwilioOutput {

    @FunctionName("TwilioOutput")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = { HttpMethod.GET, HttpMethod.POST },
                authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @TwilioSmsOutput(
                name = "twilioMessage",
                accountSid = "AzureWebJobsTwilioAccountSID",
                authToken = "AzureWebJobsTwilioAuthToken",
                to = "+1XXXXXXXXXX",
                body = "From Azure Functions",
                from = "+1XXXXXXXXXX") OutputBinding<String> twilioMessage,
            final ExecutionContext context) {

        String message = request.getQueryParameters().get("message");
        String to = request.getQueryParameters().get("to");

        StringBuilder builder = new StringBuilder()
            .append("{")
            .append("\"body\": \"%s\",")
            .append("\"to\": \"%s\"")
            .append("}");

        final String body = String.format(builder.toString(), message, to);

        twilioMessage.setValue(body);

        return request.createResponseBuilder(HttpStatus.OK).body("Message sent").build();
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the output binding. C# 脚本改为使用 function.json 配置文件

在独立工作进程中运行的函数应用当前不支持 Twilio 绑定。

Annotations

The TwilioSmsOutput annotation allows you to declaratively configure the Twilio output binding by providing the following configuration values:

+

Place the TwilioSmsOutput annotation on an OutputBinding<T> parameter, where T may be any native Java type such as int, String, byte[], or a POJO type.

Configuration

The following table explains the binding configuration properties that you set in the function.json file, which differs by runtime version:

function.json property Description
type 必须设置为 twilioSms
direction 必须设置为 out
name 在 Twilio 短信的函数代码中使用的变量名。
accountSidSetting 此值必须设置为保留 Twilio 帐户 Sid 的应用设置的名称 (TwilioAccountSid)。 未设置时,默认应用设置名称为 AzureWebJobsTwilioAccountSid
authTokenSetting 此值必须设置为保留 Twilio 身份验证令牌的应用设置的名称 (TwilioAccountAuthToken)。 未设置时,默认应用设置名称为 AzureWebJobsTwilioAuthToken
from 此值设置为发送短信的电话号码。
body 如果不需要在函数的代码中动态设置短信,则可以使用此值对其进行硬编码。

在版本 2.x 中,可以在代码中设置 to 值。

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Next steps