Aracılığıyla paylaş


PHP'den Notification Hubs'ı kullanma

Notification Hubs REST API'leri MSDN konusunda açıklandığı gibi Notification Hubs REST arabirimini kullanarak Java/PHP/Ruby arka ucundaki tüm Notification Hubs özelliklerine erişebilirsiniz.

Bu konuda şunların nasıl yapıldığını göstereceğiz:

İstemci arabirimi

Ana istemci arabirimi, .NET Notification Hubs SDK'sında bulunan yöntemlerin aynısını sağlayabilir ve bu sayede bu sitede mevcut olan tüm öğreticileri ve örnekleri doğrudan çevirebilir ve topluluk tarafından İnternet'te katkıda bulunulabilir.

Php REST sarmalayıcı örneğinde bulunan tüm kodu bulabilirsiniz.

Örneğin, bir istemci oluşturmak için:

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

iOS yerel bildirimi göndermek için:

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

Uygulama

Henüz yapmadıysanız arka ucu uygulamanız gereken son bölüme kadar [Başlangıç öğreticisi] bölümünü izleyin. Ayrıca, isterseniz PHP REST sarmalayıcı örneğindeki kodu kullanabilir ve doğrudan Öğreticiyi tamamlama bölümüne gidebilirsiniz.

Tam REST sarmalayıcı uygulamayla ilgili tüm ayrıntılar MSDN'de bulunabilir. Bu bölümde Notification Hubs REST uç noktalarına erişmek için gereken ana adımların PHP uygulamasını açıklayacağız:

  1. Bağlantı dizesini ayrıştırma
  2. Yetkilendirme belirtecini oluşturma
  3. HTTP çağrısı gerçekleştirme

Bağlantı dizesini ayrıştırma

Bağlantı dizesini ayrıştıran oluşturucusunun istemcisini uygulayan ana sınıf aşağıdadır:

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

Güvenlik belirteci oluşturma

SAS Güvenlik Belirteci Oluşturma hakkında bilgi için Azure belgelerine bakın.

Geçerli isteğin generateSasTokenNotificationHub URI'sini ve bağlantı dizesinden ayıklanan kimlik bilgilerini temel alarak belirteci oluşturmak için sınıfına yöntemini ekleyin.

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

Bildirim gönderme

İlk olarak, bildirimi temsil eden bir sınıf tanımlayalım.

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

Bu sınıf, yerel bildirim gövdesi için bir kapsayıcı veya şablon bildirimi durumunda bir özellik kümesi ve biçim (yerel platform veya şablon) ve platforma özgü özellikler (Apple expiration özelliği ve WNS üst bilgileri gibi) içeren üst bilgi kümesidir.

Kullanılabilir tüm seçenekler için Notification Hubs REST API'leri belgelerine ve belirli bildirim platformlarının biçimlerine bakın.

Bu sınıfla birlikte, artık sınıfın içinde NotificationHub bildirim gönderme yöntemlerini yazabiliriz:

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

Yukarıdaki yöntemler bildirim hub'ınızın uç noktasına, bildirimi göndermek için /messages doğru gövdeyi ve üst bilgileri içeren bir HTTP POST isteği gönderir.

Öğreticiyi tamamlayın

Artık PHP arka uçtan bildirim göndererek Başlarken öğreticisini tamamlayabilirsiniz.

Notification Hubs istemcinizi başlatın ([Başlangıç öğreticisinde] belirtildiği gibi bağlantı dizesini ve hub adını kullanın):

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

Ardından hedef mobil platformunuza bağlı olarak gönderme kodunu ekleyin.

Windows Mağazası ve Windows Phone 8.1 (Silverlight dışı)

$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);

Android

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

Windows Phone 8.0 ve 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 kodunuzu çalıştırmak artık hedef cihazınızda görünen bir bildirim oluşturmalıdır.

Sonraki Adımlar

Bu konu başlığında Notification Hubs için basit bir PHP REST istemcisinin nasıl oluşturulacağını gösterdik. Burada yapabilecekleriniz:

  • Yukarıdaki tüm kodu içeren tam PHP REST sarmalayıcı örneğini indirin.
  • [Son Dakika Haberleri öğreticisi] bölümünde Notification Hubs etiketleme özelliği hakkında bilgi edinerek devam edin
  • Tek tek kullanıcılara anında iletme bildirimleri gönderme hakkında bilgi edinmek için [Kullanıcıları Bilgilendirme öğreticisi]

Daha fazla bilgi için bkz. PHP Geliştirici Merkezi.

Azure Notification Hubs kullanarak iOS uygulamalarına anında iletme bildirimleri gönderme