次の方法で共有


PHP から Notification Hubs を使用する方法

MSDN トピック Notification Hubs REST API の説明に従って、Notification Hub REST インターフェイスを使用して、Java/PHP/Ruby バックエンドからすべての Notification Hubs 機能にアクセスできます。

このトピックでは、次の方法について説明します。

クライアント インターフェイス

メイン クライアント インターフェイスでは、 .NET Notification Hubs SDK で使用できるのと同じメソッドを提供できます。これにより、このサイトで現在利用できるすべてのチュートリアルとサンプルを直接翻訳でき、インターネット上のコミュニティから提供されます。

使用可能なすべてのコードは、 PHP REST ラッパー サンプルで確認できます。

たとえば、クライアントを作成するには、次のようにします。

$hub = new NotificationHub("connection string", "hubname");

iOS ネイティブ通知を送信するには:

$notification = new Notification("apple", '{"aps":{"alert": "Hello!"}}');
$hub->sendNotification($notification, null);

実装

まだ行っていない場合は、バックエンドを実装する必要がある最後のセクションまでの [概要チュートリアル] に従ってください。 また、必要に応じて 、PHP REST ラッパー サンプル のコードを使用し、「 チュートリアルの完了 」セクションに直接移動します。

完全な REST ラッパーを実装するための詳細については、MSDN を参照 してください。 このセクションでは、Notification Hubs REST エンドポイントにアクセスするために必要な主な手順の PHP 実装について説明します。

  1. 接続文字列を解析する
  2. 承認トークンを生成する
  3. HTTP 呼び出しを実行する

接続文字列を解析する

接続文字列を解析するコンストラクターを持つクライアントを実装するメイン クラスを次に示します。

class NotificationHub {
    const API_VERSION = "?api-version=2013-10";

    private $endpoint;
    private $hubPath;
    private $sasKeyName;
    private $sasKeyValue;

    function __construct($connectionString, $hubPath) {
        $this->hubPath = $hubPath;

        $this->parseConnectionString($connectionString);
    }

    private function parseConnectionString($connectionString) {
        $parts = explode(";", $connectionString);
        if (sizeof($parts) != 3) {
            throw new Exception("Error parsing connection string: " . $connectionString);
        }

        foreach ($parts as $part) {
            if (strpos($part, "Endpoint") === 0) {
                $this->endpoint = "https" . substr($part, 11);
            } else if (strpos($part, "SharedAccessKeyName") === 0) {
                $this->sasKeyName = substr($part, 20);
            } else if (strpos($part, "SharedAccessKey") === 0) {
                $this->sasKeyValue = substr($part, 16);
            }
        }
    }
}

セキュリティ トークンを作成する

SAS セキュリティ トークンを作成する方法については、Azure のドキュメントを参照してください。

generateSasToken メソッドを NotificationHub クラスに追加して、現在の要求の URI と接続文字列から抽出された資格情報に基づいてトークンを作成します。

private function generateSasToken($uri) {
    $targetUri = strtolower(rawurlencode(strtolower($uri)));

    $expires = time();
    $expiresInMins = 60;
    $expires = $expires + $expiresInMins * 60;
    $toSign = $targetUri . "\n" . $expires;

    $signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $this->sasKeyValue, TRUE)));

    $token = "SharedAccessSignature sr=" . $targetUri . "&sig="
                . $signature . "&se=" . $expires . "&skn=" . $this->sasKeyName;

    return $token;
}

通知を送信する

まず、通知を表すクラスを定義します。

class Notification {
    public $format;
    public $payload;

    # array with keynames for headers
    # Note: Some headers are mandatory: Windows: X-WNS-Type, WindowsPhone: X-NotificationType
    # Note: For Apple you can set Expiry with header: ServiceBusNotification-ApnsExpiry in W3C DTF, YYYY-MM-DDThh:mmTZD (for example, 1997-07-16T19:20+01:00).
    public $headers;

    function __construct($format, $payload) {
        if (!in_array($format, ["template", "apple", "windows", "fcm", "windowsphone"])) {
            throw new Exception('Invalid format: ' . $format);
        }

        $this->format = $format;
        $this->payload = $payload;
    }
}

このクラスは、ネイティブ通知本文のコンテナー、またはテンプレート通知の場合の一連のプロパティ、および形式 (ネイティブ プラットフォームまたはテンプレート) とプラットフォーム固有のプロパティ (Apple の有効期限プロパティや WNS ヘッダーなど) を含むヘッダーのセットです。

使用可能なすべてのオプションについては、 Notification Hubs REST API のドキュメント と特定の通知プラットフォームの形式を参照してください。

このクラスを使用して、 NotificationHub クラス内に送信通知メソッドを記述できるようになりました。

public function sendNotification($notification, $tagsOrTagExpression="") {
    if (is_array($tagsOrTagExpression)) {
        $tagExpression = implode(" || ", $tagsOrTagExpression);
    } else {
        $tagExpression = $tagsOrTagExpression;
    }

    # build uri
    $uri = $this->endpoint . $this->hubPath . "/messages" . NotificationHub::API_VERSION;
    $ch = curl_init($uri);

    if (in_array($notification->format, ["template", "apple", "fcm"])) {
        $contentType = "application/json";
    } else {
        $contentType = "application/xml";
    }

    $token = $this->generateSasToken($uri);

    $headers = [
        'Authorization: '.$token,
        'Content-Type: '.$contentType,
        'ServiceBusNotification-Format: '.$notification->format
    ];

    if ("" !== $tagExpression) {
        $headers[] = 'ServiceBusNotification-Tags: '.$tagExpression;
    }

    # add headers for other platforms
    if (is_array($notification->headers)) {
        $headers = array_merge($headers, $notification->headers);
    }

    curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $notification->payload
    ));

    // Send the request
    $response = curl_exec($ch);

    // Check for errors
    if($response === FALSE){
        throw new Exception(curl_error($ch));
    }

    $info = curl_getinfo($ch);

    if ($info['http_code'] <> 201) {
        throw new Exception('Error sending notification: '. $info['http_code'] . ' msg: ' . $response);
    }
} 

上記のメソッドは、通知を送信するための正しい本文とヘッダーを使用して、通知ハブの /messages エンドポイントに HTTP POST 要求を送信します。

チュートリアルを完了する

これで、PHP バックエンドから通知を送信して、作業の開始チュートリアルを完了できます。

Notification Hubs クライアントを初期化します(「はじめにチュートリアル」の指示に従って、接続文字列とハブ名を置き換えてください)。

$hub = new NotificationHub("connection string", "hubname");

次に、ターゲット モバイル プラットフォームに応じて送信コードを追加します。

Windows ストアと Windows Phone 8.1 (Silverlight 以外)

$toast = '<toast><visual><binding template="ToastText01"><text id="1">Hello from PHP!</text></binding></visual></toast>';
$notification = new Notification("windows", $toast);
$notification->headers[] = 'X-WNS-Type: wns/toast';
$hub->sendNotification($notification, null);

iOS

$alert = '{"aps":{"alert":"Hello from PHP!"}}';
$notification = new Notification("apple", $alert);
$hub->sendNotification($notification, null);

アンドロイド

$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("fcm", $message);
$hub->sendNotification($notification, null);

Windows Phone 8.0 および 8.1 Silverlight

$toast = '<?xml version="1.0" encoding="utf-8"?>' .
            '<wp:Notification xmlns:wp="WPNotification">' .
               '<wp:Toast>' .
                    '<wp:Text1>Hello from PHP!</wp:Text1>' .
               '</wp:Toast> ' .
            '</wp:Notification>';
$notification = new Notification("windowsphone", $toast);
$notification->headers[] = 'X-WindowsPhone-Target : toast';
$notification->headers[] = 'X-NotificationClass : 2';
$hub->sendNotification($notification, null);

Kindle Fire

$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("adm", $message);
$hub->sendNotification($notification, null);

PHP コードを実行すると、ターゲット デバイスに通知が表示されるようになります。

次のステップ

このトピックでは、Notification Hubs 用の単純な PHP REST クライアントを作成する方法について説明しました。 ここでは次のことができます。

  • 上記のすべてのコードを含む完全な PHP REST ラッパー サンプルをダウンロードします。
  • [ニュース速報のチュートリアル] で Notification Hubs のタグ付け機能について引き続き学習する
  • 個々のユーザーにプッシュ通知を送信する方法については、「ユーザーへの通知のチュートリアル」を参照してください

詳細については、 PHP デベロッパー センターも参照してください。

Azure Notification Hubs を使用して iOS アプリにプッシュ通知を送信する