1

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

这里是我的index.html POST请求:

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

这里是发送-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); 
?> 
+1

您是否在任何地方检查'$ result'的值?你应该检查HTTP响应代码,如果它是200,你应该检查响应主体。 – Eran

+0

我有点困惑这是什么意思,但是当我尝试echo $结果时,没有任何东西(即使通知正在工作并发送到设备)。 –

+0

if($ result = curl_exec($ ch))echo“working”;这似乎总是返回true,即使当我设置一个糟糕的API_ACCESS_KEY –

回答

2

您可以使用curl_getinfo

检查响应信息,如果yur状态代码200符合一切正常。

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

谢谢,我已经想出了如何获取代码。现在我已经有了回复代码,我该如何将它传递给我的index.html?有没有办法在index.html中将响应代码发送回我的函数(数据,状态){}? –

+0

当状态码是200时,你可以从php返回一些东西(也许是真的),然后在你的ajax中使用它。 –

+2

你可以在这里看到http状态码:https://en.wikipedia.org/wiki/List_of_HTTP_status_codes 2xx是成功的 –

0

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

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