如何确认实际发送了firebase通知(fcm)?

时间:2017-06-05 07:06:24

标签: php jquery firebase firebase-cloud-messaging firebase-notifications

我允许用户通过我的网站发送通知。通知正在运行,但是,我想要一种方法来实际确认通知是否已发出(在代码中),或者如果不可能至少确认卷曲有效,那么我可以在我的网站上显示一条消息它要么成功要么失败了。在我的jquery post请求中,状态似乎总是“成功”,即使我在我的php中提供了无效的API_ACCESS_KEY(因此它显然没有发送通知但它仍然说成功)。我如何确定通知已发出?感谢任何帮助。

以下是我在index.html中的帖子请求:

$("#send-button").click(function(){     
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});

这是send-notification.php:

<?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>

2 个答案:

答案 0 :(得分:2)

您可以使用curl_getinfo

检查响应信息,如果你的状态代码200满足一切正常。

$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpcode == 200) {
    //everything ok
}

答案 1 :(得分:1)

您将获得成功结果 $ result = curl_exec($ ch); 结果格式为

 "multicast_id": 6581315937669460028,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1495111364345221%d8a1cb15f9fd7ecd"
    }
  ]
}
相关问题