Azure的通知集线器REST API与PHP [英] Azure Notification Hubs REST API with PHP

查看:153
本文介绍了Azure的通知集线器REST API与PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建在PHP中的Azure通知集线器API一个SharedAccessSignature。

我不断收到错误无效授权令牌的签名。

任何人有创造PHP 5.4+的SAS的例子吗?
有对API的一些文档: http://msdn.microsoft.com/ EN-US /库/ dn170477.aspx 的,但有些人说,从执行的文件是不同的。

这是我失败的实现:

 私有静态函数get_authentication_header()
    {
        $ URI =htt​​ps://x.servicebus.windows.net/x;
        $ =到期时间()+(60 * 60);
        $字符串= utf8_en code(urlen code($ URI)\\ n$到期);
        $键名=DefaultFullSharedAccessSignature;
        $键= base64_de code(静态:: HUB_KEY);
        $签名= base64_en code(hash_hmac('SHA256',$字符串,$键));
        $ SAS ='SharedAccessSignature SIG ='。 $签名。 '和; SE ='。 $到期。 '和; SKN ='。 $键名。 '和; SR ='。 urlen code($ URI);
        返回$ SAS;
 }


解决方案

下面是一个简单的包装将通知发送给通知集线器用PHP。

 < PHP包括Notification.php';类NotificationHub {    常量API_VERSION =API版本= 2013-10?    私人$端点;
    私人$ hubPath;
    私人$ sasKeyName;
    私人$ sasKeyValue;    功能__construct($的connectionString,$ hubPath){
        $这个 - > hubPath = $ hubPath;        $这个 - > parseConnectionString($的connectionString);
    }    私有函数parseConnectionString($的connectionString){
        $部分=爆炸(;,$的connectionString);
        如果(sizeof的($份)!= 3){
            抛出新的异常(错误分析连接字符串:$的connectionString);
        }        的foreach($部分为$一部分){
            如果(strpos($一部分,端点)=== 0){
                $这个 - >终点=htt​​ps开头。 SUBSTR($一部分,11);
            }否则如果(strpos($一部分,SharedAccessKeyName)=== 0){
                $这个 - > sasKeyName = SUBSTR($一部分,20);
            }否则如果(strpos($一部分,SharedAccessKey)=== 0){
                $这个 - > sasKeyValue = SUBSTR($一部分,16);
            }
        }
    }    私有函数generateSasToken($ URI){
        $ targetUri =用strtolower(rawurlen code(用strtolower($ URI)));        $ =到期时间();
        $ expiresInMins = 60;
        $到期= $到期+ $ expiresInMins * 60;
        $ toSign = $ targetUri。 \\ n。 $届满;        $签名= rawurlen code(base64_en code(hash_hmac('SHA256',$ toSign,$这个 - > sasKeyValue,TRUE)));        $令牌=SharedAccessSignature SR =。 $ targetUri。与& SIG =
                    。 $签名。与& SE =。 $到期。与& SKN =。 $这个 - > sasKeyName;        返回$令牌;
    }    公共职能broadcastNotification($通知){
        $这个 - > sendNotification时($通知);
    }    公共职能sendNotification时($通知$ tagsOrTagEx pression){
        回声$ tagsOrTagEx pression< P>中。        如果(is_array($ tagsOrTagEx pression)){
            $ tagEx pression =破灭(||,$ tagsOrTagEx pression);
        }其他{
            $ tagEx pression = $ tagsOrTagEx pression;
        }        #构建URI
        $ URI = $这个 - >端点。 $这个 - > hubPath。 /信息。 NotificationHub :: API_VERSION;        回声$ URI< P>中。        $ CH = curl_init($ URI);        如果(in_array($通知 - >的格式,[模板,苹果,GCM])){
            $的contentType =应用/ JSON;
        }其他{
            $的contentType =application / xml进行;
        }        $令牌= $这个 - > generateSasToken($ URI);        $标题= [
            授权:'。$令牌,
            内容类型:'$的contentType。
            ServiceBusNotification格式的:'$通知 - >的格式。
        ];        如果(!== $ tagEx pression){
            $头[] ='ServiceBusNotification-标签:'$ tagEx pression。
        }        #添加其他平台的头
        如果(is_array($通知 - >头)){
            $头= array_merge($标题,$通知 - >头);
        }        curl_setopt_array($ CH,阵列(
            CURLOPT_POST =>真正,
            CURLOPT_RETURNTRANSFER =>真正,
            CURLOPT_SSL_VERIFYPEER =>假,
            CURLOPT_HTTPHEADER => $头,
            CURLOPT_POSTFIELDS => $通知 - >有效载荷
        ));        //发送请求
        $响应= curl_exec($ CH);        //检查错误
        如果($响应=== FALSE){
            抛出新的异常(curl_error($ CH));
        }        $信息= curl_getinfo($ CH);        如果($信息['HTTP_ code'<> 201){
            抛出新的异常(发送错误notificaiton:'$信息['HTTP_ code']'信息:'$回应。);
        }        //的print_r($信息);        //回声$反应;
    }
}?>

我不知道,如果你想发送推送或做登记管理。不难修改上面的做登记管理如图所示的NH REST API的(记得在XML文档事项的顺序!)的 http://msdn.microsoft.com/en-us/library/dn223264.aspx

让我知道如果你仍然遇到问题。

埃利奥

I'm trying to create a SharedAccessSignature for the Azure Notifications Hubs API in PHP.

I keep getting the error "Invalid authorization token signature".

Anyone has an example of creating the SAS in PHP 5.4+? There is some documentation of the API on: http://msdn.microsoft.com/en-us/library/dn170477.aspx, but some people say that the implementation differs from the documentation.

This is my failing implementation:

private static function get_authentication_header()
    {
        $uri = "https://x.servicebus.windows.net/x";
        $expiry = time() + (60*60);
        $string = utf8_encode(urlencode($uri) . "\n" . $expiry);
        $keyname = "DefaultFullSharedAccessSignature";
        $key = base64_decode(static::HUB_KEY);
        $signature = base64_encode(hash_hmac('sha256', $string,  $key));
        $sas = 'SharedAccessSignature sig=' . $signature . '&se=' . $expiry . '&skn=' .      $keyname . '&sr=' . urlencode($uri);
        return $sas;
 }

解决方案

Here is a simple wrapper to send notifications to Notification Hubs with PHP.

<?php

include 'Notification.php';

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

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

    public function broadcastNotification($notification) {
        $this->sendNotification($notification, "");
    }

    public function sendNotification($notification, $tagsOrTagExpression) {
        echo $tagsOrTagExpression."<p>";

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

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

        echo $uri."<p>";

        $ch = curl_init($uri);

        if (in_array($notification->format, ["template", "apple", "gcm"])) {
            $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 notificaiton: '. $info['http_code'] . ' msg: ' . $response);
        }

        //print_r($info);

        //echo $response;
    } 
}

?>

I do not know if you wanted to send pushes or to do registration management. It is not hard to modify the above to do registration management as shown in the NH REST APIs (remember the order in the xml documents matters!): http://msdn.microsoft.com/en-us/library/dn223264.aspx.

Let me know if you still run into problems.

Elio

这篇关于Azure的通知集线器REST API与PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆