Azure Functions 的通知中樞輸出繫結Notification Hubs output binding for Azure Functions

這篇文章說明如何在 Azure Functions 中使用 Azure 通知中樞繫結來傳送推播通知。This article explains how to send push notifications by using Azure Notification Hubs bindings in Azure Functions. Azure Functions 會支援通知中樞的輸出繫結。Azure Functions supports output bindings for Notification Hubs.

必須為您要使用的平台通知服務 (PNS) 設定 Azure 通知中樞。Azure Notification Hubs must be configured for the Platform Notifications Service (PNS) you want to use. 若要了解如何在用戶端應用程式中收到通知中樞的推播通知,請參閱開始使用通知中心,並從靠近頁面頂端的下拉式清單中選取目標用戶端平台。To learn how to get push notifications in your client app from Notification Hubs, see Getting started with Notification Hubs and select your target client platform from the drop-down list near the top of the page.

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

重要

Google 已淘汰 Google 雲端通訊 (GCM), 取而代之的是 Firebase 雲端通訊 (FCM)Google has deprecated Google Cloud Messaging (GCM) in favor of Firebase Cloud Messaging (FCM). 此輸出系結不支援 FCM。This output binding doesn't support FCM. 若要使用 FCM 傳送通知, 請直接在您的函式中使用FIREBASE API , 或使用範本通知To send notifications using FCM, use the Firebase API directly in your function or use template notifications.

套件 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet 套件 1.x 版中提供通知中樞繫結。The Notification Hubs bindings are provided in the Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet package, version 1.x. 套件的原始程式碼位於 azure-webjobs-sdk-extensions GitHub 存放庫中。Source code for the package is in the azure-webjobs-sdk-extensions 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

Functions 2.x 中不提供此繫結。This binding is not available in Functions 2.x.

範例 - 範本Example - template

您傳送的通知可以是原生通知或範本通知The notifications you send can be native notifications or template notifications. 原生通知是以輸出繫結的 platform 屬性中所設定的特定用戶端平台為目標。Native notifications target a specific client platform as configured in the platform property of the output binding. 範本通知可用來以多個平台為目標。A template notification can be used to target multiple platforms.

請參閱特定語言的範例:See the language-specific example:

C# 指令碼範本範例 - out 參數C# script template example - out parameter

這個範例會傳送在範本中包含 message 預留位置的範本註冊通知。This example sends a notification for a template registration that contains a message placeholder in the template.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static void Run(string myQueueItem,  out IDictionary<string, string> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = GetTemplateProperties(myQueueItem);
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return templateProperties;
}

C# 指令碼範本範例 - 非同步C# script template example - asynchronous

如果您使用非同步程式碼,則不允許使用 out 參數。If you are using asynchronous code, out parameters are not allowed. 在此情況下,請使用 IAsyncCollector 來傳回您的範本通知。In this case use IAsyncCollector to return your template notification. 下列程式碼是上述程式碼的非同步範例。The following code is an asynchronous example of the code above.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static async Task Run(string myQueueItem, IAsyncCollector<IDictionary<string,string>> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    log.Info($"Sending Template Notification to Notification Hub");
    await notification.AddAsync(GetTemplateProperties(myQueueItem));    
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["user"] = "A new user wants to be added : " + message;
    return templateProperties;
}

C# 指令碼範本範例 - JSONC# script template example - JSON

這個範例會使用有效的 JSON 字串來傳送在範本中包含 message 預留位置的範本註冊通知。This example sends a notification for a template registration that contains a message placeholder in the template using a valid JSON string.

using System;

public static void Run(string myQueueItem,  out string notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = "{\"message\":\"Hello from C#. Processed a queue item!\"}";
}

C# 指令碼範本範例 - 程式庫類型C# script template example - library types

這個範例示範如何使用 Microsoft Azure 通知中樞程式庫中定義的類型。This example shows how to use types defined in the Microsoft Azure Notification Hubs Library.

#r "Microsoft.Azure.NotificationHubs"

using System;
using System.Threading.Tasks;
using Microsoft.Azure.NotificationHubs;

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

private static TemplateNotification GetTemplateNotification(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return new TemplateNotification(templateProperties);
}

F # 範本範例F# template example

這個範例會傳送包含 locationmessage範本註冊通知。This example sends a notification for a template registration that contains location and message.

let Run(myTimer: TimerInfo, notification: byref<IDictionary<string, string>>) =
    notification = dict [("location", "Redmond"); ("message", "Hello from F#!")]

JavaScript 範本範例JavaScript template example

這個範例會傳送包含 locationmessage範本註冊通知。This example sends a notification for a template registration that contains location and message.

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node.js is running late!');
    }
    context.log('Node.js timer trigger function ran!', timeStamp);  
    context.bindings.notification = {
        location: "Redmond",
        message: "Hello from Node!"
    };
    context.done();
};

範例 - APNS 原生Example - APNS native

這個 C# 指令碼範例會示範如何傳送原生 APNS 通知。This C# script example shows how to send a native APNS notification.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The JSON format for a native APNS notification is ...
    // { "aps": { "alert": "notification message" }}  

    log.LogInformation($"Sending APNS notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string apnsNotificationPayload = "{\"aps\": {\"alert\": \"A new user wants to be added (" + 
                                        user.name + ")\" }}";
    log.LogInformation($"{apnsNotificationPayload}");
    await notification.AddAsync(new AppleNotification(apnsNotificationPayload));        
}

範例 - WNS 原生Example - WNS native

這個 C# 指令碼範例示範如何使用 Microsoft Azure 通知中樞程式庫中定義的類型來傳送原生 WNS 快顯通知。This C# script example shows how to use types defined in the Microsoft Azure Notification Hubs Library to send a native WNS toast notification.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The XML format for a native WNS toast notification is ...
    // <?xml version="1.0" encoding="utf-8"?>
    // <toast>
    //      <visual>
    //     <binding template="ToastText01">
    //       <text id="1">notification message</text>
    //     </binding>
    //   </visual>
    // </toast>

    log.Info($"Sending WNS toast notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string wnsNotificationPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<toast><visual><binding template=\"ToastText01\">" +
                                        "<text id=\"1\">" + 
                                            "A new user wants to be added (" + user.name + ")" + 
                                        "</text>" +
                                    "</binding></visual></toast>";

    log.Info($"{wnsNotificationPayload}");
    await notification.AddAsync(new WindowsNotification(wnsNotificationPayload));        
}

屬性Attributes

C# 類別庫中,使用 NotificationHub 屬性。In C# class libraries, use the NotificationHub attribute.

屬性的建構函式參數和屬性會在組態一節中加以敘述。The attribute's constructor parameters and properties are described in the configuration section.

組態Configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 NotificationHub 屬性:The following table explains the binding configuration properties that you set in the function.json file and the NotificationHub attribute:

function.json 屬性function.json property 屬性內容Attribute property 描述Description
typetype n/an/a 必須設定為 "notificationHub"。Must be set to "notificationHub".
directiondirection n/an/a 必須設定為 "out"。Must be set to "out".
namename n/an/a 函式程式碼中用於通知中樞訊息的變數名稱。Variable name used in function code for the notification hub message.
tagExpressiontagExpression TagExpressionTagExpression 標籤運算式可讓您指定將通知傳遞到一組裝置,這些裝置已註冊要接收與標籤運算式相符的通知。Tag expressions allow you to specify that notifications be delivered to a set of devices that have registered to receive notifications that match the tag expression. 如需詳細資訊,請參閱 路由與標籤運算式For more information, see Routing and tag expressions.
hubNamehubName HubNameHubName Azure 入口網站中通知中樞資源的名稱。Name of the notification hub resource in the Azure portal.
連接connection ConnectionStringSettingConnectionStringSetting 包含「通知中樞」連接字串的應用程式設定名稱。The name of an app setting that contains a Notification Hubs connection string. 必須針對通知中樞將連接字串設為 DefaultFullSharedAccessSignature 值。The connection string must be set to the DefaultFullSharedAccessSignature value for your notification hub. 請參閱本文稍後的連線字串設定See Connection string setup later in this article.
platformplatform 平台Platform 此平台屬性指出作為您通知目標的用戶端平台。The platform property indicates the client platform your notification targets. 依照預設,如果輸出繫結中省略平台屬性,範本通知可用來以「Azure 通知中樞」上所設定的任何平台為目標。By default, if the platform property is omitted from the output binding, template notifications can be used to target any platform configured on the Azure Notification Hub. 如需有關一般使用範本搭配「Azure 通知中樞」來傳送跨平台通知的詳細資訊,請參閱範本For more information on using templates in general to send cross platform notifications with an Azure Notification Hub, see Templates. platform 在設定時必須是以下其中一個值:When set, platform must be one of the following values:

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

function.json 檔案範例function.json file example

以下是 function.json 檔案中「通知中樞」繫結的範例。Here's an example of a Notification Hubs binding in a function.json file.

{
  "bindings": [
    {
      "type": "notificationHub",
      "direction": "out",
      "name": "notification",
      "tagExpression": "",
      "hubName": "my-notification-hub",
      "connection": "MyHubConnectionString",
      "platform": "apns"
    }
  ],
  "disabled": false
}

連接字串設定Connection string setup

若要使用通知中樞輸出繫結,必須設定中樞的連接字串。To use a notification hub output binding, you must configure the connection string for the hub. 您可以直接從 Azure 入口網站中的 [整合] 索引標籤選取現有通知中樞或建立新的通知中樞。You can select an existing notification hub or create a new one right from the Integrate tab in the Azure portal. 您也可以手動設定連接字串。You can also configure the connection string manually.

若要將連接字串設定為現有通知中樞:To configure the connection string to an existing notification hub:

  1. 瀏覽至 Azure 入口網站中的通知中樞,選擇 [存取原則],然後選取 DefaultFullSharedAccessSignature 原則旁邊的 [複製] 按鈕。Navigate to your notification hub in the Azure portal, choose Access policies, and select the copy button next to the DefaultFullSharedAccessSignature policy. 這會將 DefaultFullSharedAccessSignature 原則的連接字串複製到通知中樞。This copies the connection string for the DefaultFullSharedAccessSignature policy to your notification hub. 這個連接字串可讓您的函式將通知訊息傳送至中樞。This connection string lets your function send notification messages to the hub. 複製通知中樞連接字串Copy the notification hub connection string
  2. 瀏覽至 Azure 入口網站中的函式應用程式,選擇 [應用程式設定],新增 MyHubConnectionString 之類的金鑰,貼上針對通知中樞所複製的 DefaultFullSharedAccessSignature 來作為值,然後按一下 [儲存]。Navigate to your function app in the Azure portal, choose Application settings, add a key such as MyHubConnectionString, paste the copied DefaultFullSharedAccessSignature for your notification hub as the value, and then click Save.

此應用程式設定的名稱是 function.json或 .NET 屬性中輸出繫結連線設定的內容。The name of this application setting is what goes in the output binding connection setting in function.json or the .NET attribute. 請參閱本文中稍早的組態區段See the Configuration section earlier in this article.

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

例外狀況和傳回碼Exceptions and return codes

繫結Binding 參考資料Reference
通知中樞Notification Hub 操作指南 (英文)Operations Guide

後續步驟Next steps