次の方法で共有


Azure Functions の Azure Notification Hubs 出力バインド

この記事では、Azure Functions で Azure Notification Hubs のバインドを使用してプッシュ通知を送信する方法について説明します。 Azure Functions は、Notification Hubs の出力バインドをサポートします。

使用するプラットフォーム通知サービス (PNS) の Notification Hubs を構成する必要があります。 Notification Hubs からクライアント アプリでプッシュ通知を取得する方法の詳細については、「 Quickstart: 通知ハブでプッシュ通知を設定する」を参照してください。

重要

Google では Google Cloud Messaging (GCM) は非推奨となり、Firebase Cloud Messaging (FCM) が推奨されます。 ただし、Notification Hubs の出力バインドは FCM をサポートしていません。 FCM を使用して通知を送信するには、Firebase API を関数に直接使用するか、テンプレート通知を使用します。

パッケージ: 関数 1.x

Notification Hubs バインディングは Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet パッケージ、バージョン 1.x で提供されます。 パッケージのソース コードは、azure-webjobs-sdk-extensions GitHub リポジトリにあります。

次の表に、各開発環境で出力バインドのサポートを追加する方法を示します。

開発環境 Functions 1.x でサポートを追加するには
ローカル開発: C# クラス ライブラリ パッケージをインストールする
ローカル開発: C# スクリプト、JavaScript、F# 自動
Portal 開発 自動

パッケージ: 関数 2.x 以降

出力バインドは、Functions 2.x 以降では使用できません。

テンプレートの例:

送信できる通知は、ネイティブ通知またはテンプレート通知です。 ネイティブ通知は、出力バインディングの platform プロパティで構成されているように、特定のクライアント プラットフォームを対象とします。 テンプレート通知は、複数のプラットフォームを対象として使用できます。

各言語のテンプレートの例:

C# スクリプト テンプレートの例: out パラメーター

次の例では、テンプレートにmessageプレースホルダーを含むテンプレート登録の通知を送信します。

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# スクリプト テンプレートの例: 非同期

非同期コードを使用している場合、out パラメーターは許可されません。 この場合は、 IAsyncCollector を使用してテンプレート通知を返します。 次のコードは、前の例の非同期の例です。

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# スクリプト テンプレートの例: JSON

この例では、有効な JSON 文字列を使用してテンプレートにmessageプレースホルダーを含むテンプレート登録の通知を送信します。

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# スクリプト テンプレートの例: ライブラリの種類

この例では、 Microsoft Azure Notification Hubs ライブラリで定義されている型を使用する方法を示します

#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# テンプレートの例

この例では、locationmessageを含むテンプレート登録の通知を送信します。

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

JavaScript テンプレートの例

この例では、locationmessageを含むテンプレート登録の通知を送信します。

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

例: APNS ネイティブ

この C# スクリプトの例では、ネイティブの Apple Push Notification Service (APNS) 通知を送信する方法を示します。

#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 Apple Push Notification Service (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 ネイティブ

この C# スクリプトの例では、 Microsoft Azure Notification Hubs ライブラリ で定義されている型を使用して、ネイティブ Windows プッシュ通知サービス (WNS) トースト通知を送信する方法を示します。

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

属性

C# クラス ライブラリでは、NotificationHub 属性を使用します。

属性のコンストラクターパラメーターとプロパティについては、「 Configuration 」セクションで説明します。

構成

次の表に、 function.json ファイルで設定したバインド構成プロパティと NotificationHub 属性を示します。

function.json のプロパティ 属性のプロパティ 説明
type 該当なし notificationHub に設定します。
direction 該当なし out に設定します。
name 該当なし 通知ハブ メッセージの関数コードで使用される変数名。
tagExpression TagExpression タグ式を使用すると、タグ式に一致する通知を受信するように登録されている一連のデバイスに通知を配信するように指定できます。 詳細については、「ルーティングとタグ式」を参照してください。
hubName HubName Azure portal の通知ハブ リソースの名前。
connection ConnectionStringSetting Notification Hubs 接続文字列を含むアプリ設定の名前。 接続文字列を通知ハブの DefaultFullSharedAccessSignature 値に設定します。 詳細については、「 Connection 文字列のセットアップ」を参照してください。
platform プラットフォーム platform プロパティは、通知の対象となるクライアント プラットフォームを示します。 既定では、プラットフォームのプロパティが出力バインドから省略されている場合、テンプレート通知は、Azure 通知ハブで構成されている任意のプラットフォームを対象として使用できます。 テンプレートを使用して Azure Notification Hub でクロスプラットフォーム通知を送信する方法の詳細については、「 Notification Hubs テンプレート」を参照してください。 platformが設定されている場合は、次のいずれかの値である必要があります。

ローカルで開発する場合は、Values コレクション内の local.settings.json ファイルにアプリケーション設定を追加します。

function.json ファイルの例

function.json ファイル内の Notification Hubs バインドの例を次に示します。

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

接続文字列の設定

通知ハブの出力バインドを使用するには、ハブの接続文字列を設定する必要があります。 既存の通知ハブを選択するか、Azure portal の Integrate タブから新しい通知ハブを作成できます。 接続文字列を手動で構成することもできます。

既存の通知ハブに対する接続文字列を構成するには:

  1. Azure Portal で通知ハブに移動し、[アクセスポリシー] を選択して、[DefaultFullSharedAccessSignature] ポリシーの横にあるコピー ボタンを選択します。

    DefaultFullSharedAccessSignature ポリシーの接続文字列が通知ハブにコピーされます。 この接続文字列を使用して、関数からハブに通知メッセージを送信できます。 通知ハブの接続文字列をコピーする方法を示すスクリーンショット。

  2. Azure portal で関数アプリに移動し、 Settings を展開し、 Environment 変数を選択します。

  3. [ App 設定 タブで、 + Add を選択して、 MyHubConnectionString などのキーを追加。 このアプリ設定の Name は、 function.json または .NET 属性の出力バインド接続設定です。 詳細については、構成に関するページを参照してください。

  4. 値として、通知ハブからコピーしたDefaultFullSharedAccessSignature 接続文字列を貼り付け、Apply を選択します。

ローカルで開発する場合は、Values コレクション内の local.settings.json ファイルにアプリケーション設定を追加します。

例外とリターン コード

バインド リファレンス
Notification Hub 運用ガイド