Delen via


Twilio-binding voor Azure Functions

This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions ondersteunt uitvoerbindingen voor Twilio.

Dit is referentie-informatie voor Azure Functions-ontwikkelaars. Als u nog geen ervaring hebt met Azure Functions, begint u met de volgende resources:

Install extension

Het NuGet-extensiepakket dat u installeert, is afhankelijk van de C#-modus die u gebruikt in uw functie-app:

Functies worden uitgevoerd in een geïsoleerd C#-werkproces. Zie De handleiding voor het uitvoeren van C# Azure Functions in een geïsoleerd werkproces voor meer informatie.

De functionaliteit van de extensie varieert afhankelijk van de extensieversie:

Er is momenteel geen ondersteuning voor Twilio voor een geïsoleerde werkproces-app.

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

Tenzij anders vermeld, zijn deze voorbeelden specifiek voor versie 2.x en latere versie van de Functions-runtime.

U kunt een C#-functie maken met behulp van een van de volgende C#-modi:

  • Geïsoleerd werkrolmodel: gecompileerde C#-functie die wordt uitgevoerd in een werkproces dat is geïsoleerd van de runtime. Er is een geïsoleerd werkproces vereist om C#-functies te ondersteunen die worden uitgevoerd op langetermijnondersteuning (LTS) en niet-LTS-versies voor .NET en .NET Framework.
  • 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.

De Twilio-binding wordt momenteel niet ondersteund voor een functie-app die wordt uitgevoerd in een geïsoleerd werkproces.

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"
}

Dit is de JavaScript-code:

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

Volledige PowerShell-voorbeelden zijn momenteel niet beschikbaar voor SendGrid-bindingen.

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"
    }

U kunt een geserialiseerd JSON-object doorgeven aan de func.Out parameter om het SMS-bericht te verzenden.

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. Waarden voor to, fromen body zijn vereist in de kenmerkdefinitie, zelfs als u deze programmatisch overschrijft.

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#-script maakt in plaats daarvan gebruik van een function.json configuratiebestand.

De Twilio-binding wordt momenteel niet ondersteund voor een functie-app die wordt uitgevoerd in een geïsoleerd werkproces.

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 moet zijn ingesteld op twilioSms.
direction moet zijn ingesteld op out.
name Variabelenaam die wordt gebruikt in functiecode voor het sms-bericht van Twilio.
accountSidSetting Deze waarde moet worden ingesteld op de naam van een app-instelling die uw Twilio-account-sid (TwilioAccountSid) bevat. Als deze instelling niet is ingesteld, is AzureWebJobsTwilioAccountSidde standaardnaam van de app-instelling.
authTokenSetting Deze waarde moet worden ingesteld op de naam van een app-instelling die uw Twilio-verificatietoken (TwilioAccountAuthToken) bevat. Als deze instelling niet is ingesteld, is AzureWebJobsTwilioAuthTokende standaardnaam van de app-instelling.
from Deze waarde wordt ingesteld op het telefoonnummer van waaruit de sms-tekst wordt verzonden.
body Deze waarde kan worden gebruikt om het sms-tekstbericht in code vast te stellen als u deze niet dynamisch hoeft in te stellen in de code voor uw functie.

In versie 2.x stelt u de to waarde in uw code in.

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

Next steps